Microsoft.AspNet.Server.Kestrel.Infrastructure.MemoryPoolIterator2.CopyTo C# (CSharp) Method

CopyTo() public method

public CopyTo ( byte array, int offset, int count, int &actual ) : MemoryPoolIterator2
array byte
offset int
count int
actual int
return MemoryPoolIterator2
        public MemoryPoolIterator2 CopyTo(byte[] array, int offset, int count, out int actual)
        {
            if (IsDefault)
            {
                actual = 0;
                return this;
            }

            var block = _block;
            var index = _index;
            var remaining = count;
            while (true)
            {
                var following = block.End - index;
                if (remaining <= following)
                {
                    actual = count;
                    Buffer.BlockCopy(block.Array, index, array, offset, remaining);
                    return new MemoryPoolIterator2(block, index + remaining);
                }
                else if (block.Next == null)
                {
                    actual = count - remaining + following;
                    Buffer.BlockCopy(block.Array, index, array, offset, following);
                    return new MemoryPoolIterator2(block, index + following);
                }
                else
                {
                    Buffer.BlockCopy(block.Array, index, array, offset, following);
                    offset += following;
                    remaining -= following;
                    block = block.Next;
                    index = block.Start;
                }
            }
        }
    }

Usage Example

        public static ArraySegment <byte> GetArraySegment(this MemoryPoolIterator2 start, MemoryPoolIterator2 end)
        {
            if (start.IsDefault || end.IsDefault)
            {
                return(default(ArraySegment <byte>));
            }
            if (end.Block == start.Block)
            {
                return(new ArraySegment <byte>(start.Block.Array, start.Index, end.Index - start.Index));
            }

            var length = start.GetLength(end);
            var array  = new byte[length];

            start.CopyTo(array, 0, length, out length);
            return(new ArraySegment <byte>(array, 0, length));
        }