33using System . Collections . Generic ;
44using System . Diagnostics ;
55using System . Globalization ;
6+ using System . Net ;
67using System . Text ;
78using System . Threading ;
89using System . Threading . Tasks ;
@@ -24,7 +25,7 @@ internal sealed class SftpSession : SubsystemSession, ISftpSession
2425 private readonly Dictionary < uint , SftpRequest > _requests = new Dictionary < uint , SftpRequest > ( ) ;
2526 private readonly ISftpResponseFactory _sftpResponseFactory ;
2627 private readonly Encoding _encoding ;
27- private System . Net . ArrayBuffer _buffer = new ( 32 * 1024 ) ;
28+ private ArrayBuffer _buffer = new ( 32 * 1024 ) ;
2829 private EventWaitHandle _sftpVersionConfirmed = new AutoResetEvent ( initialState : false ) ;
2930 private IDictionary < string , string > _supportedExtensions ;
3031
@@ -495,7 +496,7 @@ public byte[] RequestRead(byte[] handle, ulong offset, uint length)
495496 length ,
496497 response =>
497498 {
498- data = response . Data ;
499+ data = response . Data . ToArray ( ) ;
499500 wait . SetIgnoringObjectDisposed ( ) ;
500501 } ,
501502 response =>
@@ -526,28 +527,42 @@ public byte[] RequestRead(byte[] handle, ulong offset, uint length)
526527 }
527528
528529 /// <inheritdoc/>
529- public Task< byte [ ] > RequestReadAsync ( byte [ ] handle , ulong offset , uint length , CancellationToken cancellationToken )
530+ public Task< ReadOnlyMemoryOwner > RequestReadAsync ( byte [ ] handle , ulong offset , uint length , CancellationToken cancellationToken )
530531 {
531532 Debug. Assert ( length > 0 , "This implementation cannot distinguish between EOF and zero-length reads" ) ;
532533
533534 if ( cancellationToken . IsCancellationRequested )
534535 {
535- return Task. FromCanceled < byte [ ] > ( cancellationToken ) ;
536+ return Task. FromCanceled < ReadOnlyMemoryOwner > ( cancellationToken ) ;
536537 }
537538
538- var tcs = new TaskCompletionSource< byte [ ] > ( TaskCreationOptions . RunContinuationsAsynchronously ) ;
539+ var tcs = new TaskCompletionSource< ReadOnlyMemoryOwner > ( TaskCreationOptions . RunContinuationsAsynchronously ) ;
539540
540541 SendRequest( new SftpReadRequest ( ProtocolVersion ,
541542 NextRequestId ,
542543 handle ,
543544 offset ,
544545 length ,
545- response => tcs . TrySetResult ( response . Data ) ,
546+ response =>
547+ {
548+ ArrayBuffer buffer = new ( response . Data . Count , usePool : true ) ;
549+
550+ response . Data . AsSpan ( ) . CopyTo ( buffer . AvailableSpan ) ;
551+
552+ buffer . Commit ( response . Data . Count ) ;
553+
554+ ReadOnlyMemoryOwner owner = new ( buffer ) ;
555+
556+ if ( ! tcs . TrySetResult ( owner ) )
557+ {
558+ owner . Dispose ( ) ;
559+ }
560+ } ,
546561 response =>
547562 {
548563 if ( response . StatusCode == StatusCode . Eof )
549564 {
550- _ = tcs . TrySetResult ( Array . Empty < byte > ( ) ) ;
565+ _ = tcs . TrySetResult ( new ( new ( 0 , usePool : true ) ) ) ;
551566 }
552567 else
553568 {
0 commit comments