Skip to content

Commit 95e629b

Browse files
committed
Fix LiteFileStream.SetReadStreamPosition
1 parent 4f77be4 commit 95e629b

File tree

2 files changed

+26
-7
lines changed

2 files changed

+26
-7
lines changed

LiteDB/Client/Storage/LiteFileStream.Read.cs

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -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
}

LiteDB/Client/Storage/LiteFileStream.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using System.Collections.Generic;
23
using System.IO;
34
using System.Linq;
45
using static LiteDB.Constants;
@@ -23,6 +24,7 @@ public partial class LiteFileStream<TFileId> : Stream
2324
private byte[] _currentChunkData = null;
2425
private int _positionInChunk = 0;
2526
private MemoryStream _buffer;
27+
private Dictionary<int, long> _chunkLengths = new Dictionary<int, long>();
2628

2729
internal LiteFileStream(ILiteCollection<LiteFileInfo<TFileId>> files, ILiteCollection<BsonDocument> chunks, LiteFileInfo<TFileId> file, BsonValue fileId, FileAccess mode)
2830
{

0 commit comments

Comments
 (0)