@@ -870,11 +870,16 @@ public int GetLength(MemoryPoolIterator end)
870
870
871
871
public MemoryPoolIterator CopyTo ( byte [ ] array , int offset , int count , out int actual )
872
872
{
873
- if ( IsDefault )
873
+ // Note: Ensure for any changes in this function Consume is changed to match
874
+ if ( count == 0 || IsDefault )
874
875
{
875
876
actual = 0 ;
876
877
return this ;
877
878
}
879
+ if ( array == null )
880
+ {
881
+ return Consume ( count , out actual ) ;
882
+ }
878
883
879
884
var block = _block ;
880
885
var index = _index ;
@@ -890,27 +895,18 @@ public MemoryPoolIterator CopyTo(byte[] array, int offset, int count, out int ac
890
895
if ( remaining <= following )
891
896
{
892
897
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 ) ;
897
899
return new MemoryPoolIterator ( block , index + remaining ) ;
898
900
}
899
901
else if ( wasLastBlock )
900
902
{
901
903
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 ) ;
906
905
return new MemoryPoolIterator ( block , index + following ) ;
907
906
}
908
907
else
909
908
{
910
- if ( array != null )
911
- {
912
- Buffer . BlockCopy ( block . Array , index , array , offset , following ) ;
913
- }
909
+ Buffer . BlockCopy ( block . Array , index , array , offset , following ) ;
914
910
offset += following ;
915
911
remaining -= following ;
916
912
block = block . Next ;
@@ -919,6 +915,34 @@ public MemoryPoolIterator CopyTo(byte[] array, int offset, int count, out int ac
919
915
}
920
916
}
921
917
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
+
922
946
public void CopyFrom ( byte [ ] data )
923
947
{
924
948
CopyFrom ( data , 0 , data . Length ) ;
0 commit comments