Пример #1
0
        /// <summary>
        /// Gets a <see cref="ReadOnlyMemory{T}"/> containing all written data
        /// </summary>
        /// <returns>A rented buffer containing all written data</returns>
        /// <remarks>Will avoid allocations/copying if possible. The buffer will become invalid after <see cref="O:Reset"/> is called.</remarks>
        public ReadOnlyMemory <T> ToMemory()
        {
            if (TryGetMemory(out var Memory))
            {
                return(Memory.ToArray());
            }

            var BufferLength = (int)Length;

            // Grab a buffer that represents the entire contents of this Writer
            var Buffer = _Pool.Rent(BufferLength);

            // Copy our current chain of buffers into it
            new ReadOnlySequence <T>(_HeadSegment !, 0, _TailSegment !, _TailSegment !.Memory.Length).CopyTo(Buffer);

            // Copy the final segment (if any)
            if (_CurrentOffset > 0)
            {
                _CurrentBuffer.Slice(0, _CurrentOffset).CopyTo(Buffer.AsMemory((int)_TailSegment.RunningIndex + _TailSegment.Memory.Length));
            }

            // Release our old buffers
            Reset();

            // Replace our root buffer with the new buffer we just allocated
            _CurrentBuffer = Buffer;
            _CurrentOffset = BufferLength;

            return(Buffer.AsMemory(0, BufferLength));
        }
Пример #2
0
        /// <summary>
        /// Gets an array containing all written data
        /// </summary>
        /// <returns>A single array containing all written data</returns>
        /// <remarks>The buffer is not rented from the array pool. Does not 'finish' the final segment, so writing can potentially continue without allocating/renting.</remarks>
        public T[] ToArray()
        {
            if (TryGetMemory(out var Memory))
            {
                return(Memory.ToArray());
            }

            var BufferLength = (int)Length;

            // Grab a buffer that represents the entire contents of this Writer
            var Buffer = new T[BufferLength];

            // Copy our current chain of buffers into it
            new ReadOnlySequence <T>(_HeadSegment !, 0, _TailSegment !, _TailSegment !.Memory.Length).CopyTo(Buffer);

            // Copy the final segment (if any)
            if (_CurrentOffset > 0)
            {
                _CurrentBuffer.Slice(0, _CurrentOffset).CopyTo(Buffer.AsMemory((int)_TailSegment.RunningIndex + _TailSegment.Memory.Length));
            }

            return(Buffer);
        }