Esempio n. 1
0
        /// <summary>
        /// Set current with <paramref name="s"/>.
        /// </summary>
        /// <param name="s">String to convert into UTF-8.</param>
        public void SetString(string s)
        {
            if (s != null)
            {
                // This code is not optimized. One could actually read the string and copy the content
                // directly in _handle without hitting any allocation. This would require us to include
                // the logic of converting .NET strings into UTF8 ourselves, something we do not want
                // to do for the time being. For now we only avoid the allocation of an extra byte array
                // for small strings (see the implementation of GetUtf8Bytes).
                int    nb;
                byte[] bytes = GetUtf8Bytes(s, out nb);
                if (nb >= _capacity)
                {
                    // By default increase size by the max of 50% or new capacity nb.
                    int    newSize = Math.Max(_capacity + _capacity / 2, nb + 1);
                    IntPtr lPtr    = SDL.SDL_realloc(_handle, (IntPtr)newSize);
                    if (lPtr == IntPtr.Zero)
                    {
                        Dispose();
                        throw new OutOfMemoryException("Cannot reallocate Utf8String");
                    }
                    _handle   = lPtr;
                    _capacity = newSize;
                }
                _count = nb;

                Marshal.Copy(bytes, 0, _handle, nb);
                ((byte *)_handle)[nb] = 0;
            }
            else
            {
                Dispose();
            }

            Contract.Ensures(String().Equals(s), "string_set");
        }