Skip to content

Commit

Permalink
Fix bug in the sync version of ChunkedStream when we read a partial b…
Browse files Browse the repository at this point in the history
…lock
  • Loading branch information
halgari committed Oct 30, 2024
1 parent 3a23441 commit 39fcdfb
Showing 1 changed file with 8 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/NexusMods.DataModel/ChunkedStreams/ChunkedStream.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Buffers;
using System.Diagnostics;
using Reloaded.Memory.Extensions;

namespace NexusMods.DataModel.ChunkedStreams;
Expand Down Expand Up @@ -43,8 +44,11 @@ public override int Read(byte[] buffer, int offset, int count)
var chunkOffset = _position % _source.ChunkSize.Value;
var isLastChunk = chunkIdx == _source.ChunkCount - 1;
var chunk = GetChunk(chunkIdx);
var readToEnd = Math.Clamp(_source.Size.Value - _position, 0, Int32.MaxValue);

var toRead = Math.Min(count, (int)(_source.ChunkSize.Value - chunkOffset));
var toRead = Math.Min(buffer.Length, (int)(_source.ChunkSize.Value - chunkOffset));
toRead = Math.Min(toRead, (int)readToEnd);

if (isLastChunk)
{
var lastChunkExtraSize = _source.Size.Value % _source.ChunkSize.Value;
Expand All @@ -58,6 +62,8 @@ public override int Read(byte[] buffer, int offset, int count)
.Span
.CopyTo(buffer.AsSpan(offset, toRead));
_position += (ulong)toRead;

Debug.Assert(_position <= _source.Size.Value, "Read more than the size of the stream");
return toRead;
}

Expand Down Expand Up @@ -92,6 +98,7 @@ public override async ValueTask<int> ReadAsync(Memory<byte> buffer,
.Span
.CopyTo(buffer.Span.SliceFast(0, toRead));
_position += (ulong)toRead;
Debug.Assert(_position <= _source.Size.Value, "Read more than the size of the stream");
return toRead;
}

Expand Down

0 comments on commit 39fcdfb

Please sign in to comment.