public UnmanagedBuffersPool.AllocatedMemoryData GetMemory(int requestedSize)
        {
            if (requestedSize == 0)
            {
                return new UnmanagedBuffersPool.AllocatedMemoryData
                       {
                           Address     = IntPtr.Zero,
                           SizeInBytes = 0
                       }
            }
            ;

            var actualSize = Bits.NextPowerOf2(requestedSize);
            var index      = UnmanagedBuffersPool.GetIndexFromSize(actualSize);

            if (index == -1)
            {
                return(Pool.Allocate(requestedSize));
            }

            if (_allocatedMemory?[index] == null ||
                _allocatedMemory[index].Count == 0)
            {
                return(Pool.Allocate(actualSize));
            }
            var last = _allocatedMemory[index].Pop();

            return(last);
        }
        public void ReturnMemory(UnmanagedBuffersPool.AllocatedMemoryData buffer)
        {
            if (buffer.SizeInBytes == 0)
            {
                return;
            }

            if (_allocatedMemory == null)
            {
                _allocatedMemory = new Stack <UnmanagedBuffersPool.AllocatedMemoryData> [32];
            }
            var index = UnmanagedBuffersPool.GetIndexFromSize(buffer.SizeInBytes);

            if (index == -1)
            {
                Pool.Return(buffer);
                return;
            }
            if (_allocatedMemory[index] == null)
            {
                _allocatedMemory[index] = new Stack <UnmanagedBuffersPool.AllocatedMemoryData>();
            }
            _allocatedMemory[index].Push(buffer);
        }
 public JsonOperationContext(UnmanagedBuffersPool pool)
 {
     Pool             = pool;
     Encoding         = new UTF8Encoding();
     CachedProperties = new CachedProperties(this);
 }