From 39fcdfbf0b5fc703cf2ea9841e179afce7053622 Mon Sep 17 00:00:00 2001 From: halgari Date: Wed, 30 Oct 2024 13:49:05 -0600 Subject: [PATCH] Fix bug in the sync version of ChunkedStream when we read a partial block --- src/NexusMods.DataModel/ChunkedStreams/ChunkedStream.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/NexusMods.DataModel/ChunkedStreams/ChunkedStream.cs b/src/NexusMods.DataModel/ChunkedStreams/ChunkedStream.cs index d99d38b5f4..34f016704c 100644 --- a/src/NexusMods.DataModel/ChunkedStreams/ChunkedStream.cs +++ b/src/NexusMods.DataModel/ChunkedStreams/ChunkedStream.cs @@ -1,4 +1,5 @@ using System.Buffers; +using System.Diagnostics; using Reloaded.Memory.Extensions; namespace NexusMods.DataModel.ChunkedStreams; @@ -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; @@ -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; } @@ -92,6 +98,7 @@ public override async ValueTask ReadAsync(Memory 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; }