Skip to content
This repository was archived by the owner on Dec 18, 2018. It is now read-only.

Commit b958e1e

Browse files
committed
Extract Consume from CopyTo
1 parent 55f409b commit b958e1e

File tree

1 file changed

+37
-13
lines changed

1 file changed

+37
-13
lines changed

src/Microsoft.AspNetCore.Server.Kestrel/Internal/Infrastructure/MemoryPoolIterator.cs

+37-13
Original file line numberDiff line numberDiff line change
@@ -870,11 +870,16 @@ public int GetLength(MemoryPoolIterator end)
870870

871871
public MemoryPoolIterator CopyTo(byte[] array, int offset, int count, out int actual)
872872
{
873-
if (IsDefault)
873+
// Note: Ensure for any changes in this function Consume is changed to match
874+
if (count == 0 || IsDefault)
874875
{
875876
actual = 0;
876877
return this;
877878
}
879+
if (array == null)
880+
{
881+
return Consume(count, out actual);
882+
}
878883

879884
var block = _block;
880885
var index = _index;
@@ -890,27 +895,18 @@ public MemoryPoolIterator CopyTo(byte[] array, int offset, int count, out int ac
890895
if (remaining <= following)
891896
{
892897
actual = count;
893-
if (array != null)
894-
{
895-
Buffer.BlockCopy(block.Array, index, array, offset, remaining);
896-
}
898+
Buffer.BlockCopy(block.Array, index, array, offset, remaining);
897899
return new MemoryPoolIterator(block, index + remaining);
898900
}
899901
else if (wasLastBlock)
900902
{
901903
actual = count - remaining + following;
902-
if (array != null)
903-
{
904-
Buffer.BlockCopy(block.Array, index, array, offset, following);
905-
}
904+
Buffer.BlockCopy(block.Array, index, array, offset, following);
906905
return new MemoryPoolIterator(block, index + following);
907906
}
908907
else
909908
{
910-
if (array != null)
911-
{
912-
Buffer.BlockCopy(block.Array, index, array, offset, following);
913-
}
909+
Buffer.BlockCopy(block.Array, index, array, offset, following);
914910
offset += following;
915911
remaining -= following;
916912
block = block.Next;
@@ -919,6 +915,34 @@ public MemoryPoolIterator CopyTo(byte[] array, int offset, int count, out int ac
919915
}
920916
}
921917

918+
private MemoryPoolIterator Consume(int count, out int actual)
919+
{
920+
var block = _block;
921+
var index = _index;
922+
var remaining = count;
923+
while (true)
924+
{
925+
var wasLastBlock = block.Next == null;
926+
var following = block.End - index;
927+
if (remaining <= following)
928+
{
929+
actual = count;
930+
return new MemoryPoolIterator(block, index + remaining);
931+
}
932+
else if (wasLastBlock)
933+
{
934+
actual = count - remaining + following;
935+
return new MemoryPoolIterator(block, index + following);
936+
}
937+
else
938+
{
939+
remaining -= following;
940+
block = block.Next;
941+
index = block.Start;
942+
}
943+
}
944+
}
945+
922946
public void CopyFrom(byte[] data)
923947
{
924948
CopyFrom(data, 0, data.Length);

0 commit comments

Comments
 (0)