@@ -253,27 +253,33 @@ private static async ValueTask<TResult> ParseAsync<TResult, TArg>(this PipeReade
253253
254254 static TResult Parse ( PipeReader reader , TArg arg , ReadOnlySpanFunc < byte , TArg , TResult > parser , int length , ReadOnlySequence < byte > source )
255255 {
256+ var consumed = source . Start ;
256257 try
257258 {
258259 if ( source . Length < length )
259260 {
260- length = ( int ) source . Length ;
261+ consumed = source . End ;
261262 throw new EndOfStreamException ( ) ;
262263 }
263264
264265 if ( source . TryGetBlock ( length , out var block ) )
266+ {
267+ consumed = source . GetPosition ( block . Length , consumed ) ;
265268 return parser ( block . Span , arg ) ;
269+ }
270+ else
271+ {
272+ using var destination = ( uint ) length <= ( uint ) SpanOwner < byte > . StackallocThreshold
273+ ? stackalloc byte [ length ]
274+ : new SpanOwner < byte > ( length ) ;
266275
267- using var destination = ( uint ) length <= ( uint ) SpanOwner < byte > . StackallocThreshold
268- ? stackalloc byte [ length ]
269- : new SpanOwner < byte > ( length ) ;
270-
271- source . CopyTo ( destination . Span , out length ) ;
272- return parser ( destination . Span . Slice ( 0 , length ) , arg ) ;
276+ length = source . CopyTo ( destination . Span , out consumed ) ;
277+ return parser ( destination . Span . Slice ( 0 , length ) , arg ) ;
278+ }
273279 }
274280 finally
275281 {
276- reader . AdvanceTo ( source . GetPosition ( length ) ) ;
282+ reader . AdvanceTo ( consumed ) ;
277283 }
278284 }
279285 }
@@ -422,15 +428,16 @@ public static async ValueTask<int> ReadAtLeastAsync(this PipeReader reader, Memo
422428 static int Read ( PipeReader reader , ReadOnlySequence < byte > source , in Memory < byte > destination , int minimumSize )
423429 {
424430 var readCount = 0 ;
431+ var consumed = source . Start ;
425432 try
426433 {
427- source . CopyTo ( destination . Span , out readCount ) ;
434+ readCount = source . CopyTo ( destination . Span , out consumed ) ;
428435 if ( minimumSize > readCount )
429436 throw new EndOfStreamException ( ) ;
430437 }
431438 finally
432439 {
433- reader . AdvanceTo ( source . GetPosition ( readCount ) ) ;
440+ reader . AdvanceTo ( consumed ) ;
434441 }
435442
436443 return readCount ;
0 commit comments