@@ -19,10 +19,11 @@ public class KaitaiPipeReaderAsyncStream : KaitaiStreamBase, IKaitaiAsyncStream
1919
2020 public PipeReader PipeReader { get ; }
2121 public ReadResult ReadResult { get ; set ; }
22+ private long RemainingBytesInReadResult => ReadResult . Buffer . Length - _pos ;
2223
23- #region Constructors
24+ #region Constructors
2425
25- public KaitaiPipeReaderAsyncStream ( PipeReader pipeReader )
26+ public KaitaiPipeReaderAsyncStream ( PipeReader pipeReader )
2627 {
2728 PipeReader = pipeReader ;
2829 //AsyncBinaryReader = new AsyncBinaryReader(BaseStream);
@@ -75,7 +76,22 @@ public virtual async Task SeekAsync(long position)
7576 }
7677 else
7778 {
78- await ReadBytesAsync ( position - _pos ) ; //TODO Optimize
79+ while ( true )
80+ {
81+ if ( ReadResult . IsCompleted )
82+ {
83+ throw new EndOfStreamException (
84+ $ "requested { position } bytes, but got only { RemainingBytesInReadResult } bytes") ;
85+ }
86+
87+ PipeReader . AdvanceTo ( ReadResult . Buffer . Start , ReadResult . Buffer . GetPosition ( Pos ) ) ;
88+ ReadResult = await PipeReader . ReadAsync ( ) ;
89+ if ( ReadResult . Buffer . Length >= position )
90+ {
91+ _pos = position ;
92+ return ;
93+ }
94+ }
7995 }
8096 }
8197
@@ -274,7 +290,7 @@ public async Task<byte[]> ReadBytesAsync(long count)
274290 if ( ReadResult . IsCompleted )
275291 {
276292 throw new EndOfStreamException (
277- $ "requested { count } bytes, but got only { CountRemainingBytesInReadResult ( ) } bytes") ;
293+ $ "requested { count } bytes, but got only { RemainingBytesInReadResult } bytes") ;
278294 }
279295
280296 PipeReader . AdvanceTo ( ReadResult . Buffer . Start , ReadResult . Buffer . GetPosition ( Pos ) ) ;
@@ -286,7 +302,7 @@ public async Task<byte[]> ReadBytesAsync(long count)
286302
287303 bool TryRead ( out byte [ ] readBytes , long readBytesCount )
288304 {
289- if ( CountRemainingBytesInReadResult ( ) < readBytesCount )
305+ if ( RemainingBytesInReadResult < readBytesCount )
290306 {
291307 readBytes = null ;
292308 return false ;
@@ -295,8 +311,6 @@ bool TryRead(out byte[] readBytes, long readBytesCount)
295311 readBytes = ReadResult . Buffer . Slice ( _pos , readBytesCount ) . ToArray ( ) ;
296312 return true ;
297313 }
298-
299- long CountRemainingBytesInReadResult ( ) => ReadResult . Buffer . Length - _pos ;
300314 }
301315
302316 public async Task < byte [ ] > ReadBytesAsync ( ulong count )
0 commit comments