Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix LiteFileStream.SetReadStreamPosition #2459

Merged
merged 10 commits into from
Jun 11, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions LiteDB.Tests/Issues/Issue2458_Tests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using System;
using System.IO;
using Xunit;

namespace LiteDB.Tests.Issues;

public class Issue2458_Tests
{
[Fact]
public void NegativeSeekFails()
{
using var db = new LiteDatabase(":memory:");
var fs = db.FileStorage;
AddTestFile("test", 1, fs);
using Stream stream = fs.OpenRead("test");
Assert.Throws<ArgumentOutOfRangeException>(() => stream.Position = -1);
}

//https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.position?view=net-8.0 says seeking to a position
//beyond the end of a stream is supported, so implementations should support it (error on read).
[Fact]
public void SeekPastFileSucceds()
{
using var db = new LiteDatabase(":memory:");
var fs = db.FileStorage;
AddTestFile("test", 1, fs);
using Stream stream = fs.OpenRead("test");
stream.Position = Int32.MaxValue;
}

[Fact]
public void SeekShortChunks()
{
using var db = new LiteDatabase(":memory:");
var fs = db.FileStorage;
using(Stream writeStream = fs.OpenWrite("test", "test"))
{
writeStream.WriteByte(0);
writeStream.Flush(); //Create single-byte chunk just containing a 0
writeStream.WriteByte(1);
writeStream.Flush();
writeStream.WriteByte(2);
}
using Stream readStream = fs.OpenRead("test");
readStream.Position = 2;
Assert.Equal(2, readStream.ReadByte());
}

private void AddTestFile(string id, long length, ILiteStorage<string> fs)
{
using Stream writeStream = fs.OpenWrite(id, id);
writeStream.Write(new byte[length]);
}
}
48 changes: 41 additions & 7 deletions LiteDB/Client/Storage/LiteFileStream.Read.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ public partial class LiteFileStream<TFileId> : Stream
public override int Read(byte[] buffer, int offset, int count)
{
if (_mode != FileAccess.Read) throw new NotSupportedException();
if (_streamPosition == Length)
{
return 0;
}

var bytesLeft = count;

Expand Down Expand Up @@ -42,23 +46,53 @@ private byte[] GetChunkData(int index)
.FindOne("_id = { f: @0, n: @1 }", _fileId, index);

// if chunk is null there is no more chunks
return chunk?["data"].AsBinary;
byte[] result = chunk?["data"].AsBinary;
if (result != null)
{
_chunkLengths[index] = result.Length;
}
return result;
}

private void SetReadStreamPosition(long newPosition)
{
if (newPosition < 0 && newPosition > Length)
if (newPosition < 0)
{
throw new ArgumentOutOfRangeException();
}
if (newPosition >= Length)
{
_streamPosition = Length;
return;
}
_streamPosition = newPosition;

// calculate new chunk position
_currentChunkIndex = (int)_streamPosition / MAX_CHUNK_SIZE;
_positionInChunk = (int)_streamPosition % MAX_CHUNK_SIZE;

// get current chunk
_currentChunkData = this.GetChunkData(_currentChunkIndex);
long seekStreamPosition = 0;
int loadedChunk = _currentChunkIndex;
int newChunkIndex = 0;
while (seekStreamPosition <= _streamPosition)
{
if (_chunkLengths.TryGetValue(newChunkIndex, out long length))
{
seekStreamPosition += length;
}
else
{
loadedChunk = newChunkIndex;
_currentChunkData = GetChunkData(newChunkIndex);
seekStreamPosition += _currentChunkData.Length;
}
newChunkIndex++;
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While you are at it, add a new line here

newChunkIndex--;
seekStreamPosition -= _chunkLengths[newChunkIndex];
_positionInChunk = (int)(_streamPosition - seekStreamPosition);
_currentChunkIndex = newChunkIndex;
if (loadedChunk != _currentChunkIndex)
{
_currentChunkData = GetChunkData(_currentChunkIndex);
}
}
}
}
2 changes: 2 additions & 0 deletions LiteDB/Client/Storage/LiteFileStream.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using static LiteDB.Constants;
Expand All @@ -23,6 +24,7 @@ public partial class LiteFileStream<TFileId> : Stream
private byte[] _currentChunkData = null;
private int _positionInChunk = 0;
private MemoryStream _buffer;
private Dictionary<int, long> _chunkLengths = new Dictionary<int, long>();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not trying to force you change this, but are you sure sure separating fields from their main use is a good idea? I mean if it would be used by many different partials, this would imo the best place but you are only using it in the .Read partial.

What do you think? Does that make sense?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a big deal to me, whatever works best with the style for the repository.


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