@@ -42,23 +42,40 @@ private byte[] GetChunkData(int index)
4242 . FindOne ( "_id = { f: @0, n: @1 }" , _fileId , index ) ;
4343
4444 // if chunk is null there is no more chunks
45- return chunk ? [ "data" ] . AsBinary ;
45+ byte [ ] result = chunk ? [ "data" ] . AsBinary ;
46+ if ( result != null ) {
47+ _chunkLengths [ index ] = result . Length ;
48+ }
49+ return result ;
4650 }
4751
4852 private void SetReadStreamPosition ( long newPosition )
4953 {
50- if ( newPosition < 0 && newPosition > Length )
54+ if ( newPosition < 0 || newPosition > Length )
5155 {
5256 throw new ArgumentOutOfRangeException ( ) ;
5357 }
5458 _streamPosition = newPosition ;
5559
5660 // calculate new chunk position
57- _currentChunkIndex = ( int ) _streamPosition / MAX_CHUNK_SIZE ;
58- _positionInChunk = ( int ) _streamPosition % MAX_CHUNK_SIZE ;
59-
60- // get current chunk
61- _currentChunkData = this . GetChunkData ( _currentChunkIndex ) ;
61+ long seekStreamPosition = 0 ;
62+ int loadedChunk = _currentChunkIndex ;
63+ int newChunkIndex = 0 ;
64+ while ( seekStreamPosition <= _streamPosition ) {
65+ if ( ! _chunkLengths . ContainsKey ( newChunkIndex ) ) {
66+ loadedChunk = newChunkIndex ;
67+ _currentChunkData = GetChunkData ( newChunkIndex ) ;
68+ }
69+ seekStreamPosition += _chunkLengths [ newChunkIndex ] ;
70+ newChunkIndex ++ ;
71+ }
72+ newChunkIndex -- ;
73+ seekStreamPosition -= _chunkLengths [ newChunkIndex ] ;
74+ _positionInChunk = ( int ) ( _streamPosition - seekStreamPosition ) ;
75+ _currentChunkIndex = newChunkIndex ;
76+ if ( loadedChunk != _currentChunkIndex ) {
77+ _currentChunkData = GetChunkData ( _currentChunkIndex ) ;
78+ }
6279 }
6380 }
6481}
0 commit comments