/// <summary> /// Construct a new instance of this output stream with this /// initial capacity. /// It is not an error to have this initial capacity be inaccurate. /// If the actual contents end up being larger than the /// initialCapacity, then we will reallocate memory if needed. /// If the actual contents are smaller, then we'll end up wasting /// some memory. /// </summary> /// <param name="pool">The pool to use.</param> /// <param name="initialCapacity"> /// Initial capacity to allocate for this stream. /// </param> public NativePooledByteBufferOutputStream( NativeMemoryChunkPool pool, int initialCapacity) { Preconditions.CheckArgument(initialCapacity > 0); _pool = Preconditions.CheckNotNull(pool); _count = 0; _bufRef = CloseableReference <NativeMemoryChunk> .of(_pool.Get(initialCapacity), _pool); }
/// <summary> /// Creates a new IPooledByteBuffer instance of given size. /// </summary> public IPooledByteBuffer NewByteBuffer(int size) { Preconditions.CheckArgument(size > 0); var chunkRef = CloseableReference <NativeMemoryChunk> .of(_pool.Get(size), _pool); try { return(new NativePooledByteBuffer(chunkRef, size)); } finally { chunkRef.Dispose(); } }
/// <summary> /// Reallocate the local buffer to hold the new length specified. /// Also copy over existing data to this new buffer. /// </summary> /// <param name="newLength">New length of buffer.</param> /// <exception cref="InvalidStreamException"> /// If the stream is invalid. /// </exception> /// <exception cref="SizeTooLargeException"> /// If the allocation from the pool fails. /// </exception> internal void Realloc(int newLength) { EnsureValid(); /* Can the buffer handle @i more bytes, if not expand it */ if (newLength <= _bufRef.Get().Size) { return; } NativeMemoryChunk newbuf = _pool.Get(newLength); _bufRef.Get().Copy(0, newbuf, 0, _count); _bufRef.Dispose(); _bufRef = CloseableReference <NativeMemoryChunk> .of(newbuf, _pool); }