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 SDV Manifest parse error #2217

Merged
merged 2 commits into from
Oct 31, 2024
Merged
Changes from all 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
19 changes: 14 additions & 5 deletions 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 @@ -29,10 +30,12 @@ public ChunkedStream(T source, int capacity = 16)

/// <inheritdoc />
public override void Flush() { }


/// <inheritdoc />
public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count));

/// <inheritdoc />
public override int Read(byte[] buffer, int offset, int count)
public override int Read(Span<byte> buffer)
{
if (_position >= _source.Size.Value)
{
Expand All @@ -43,8 +46,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 @@ -56,15 +62,17 @@ public override int Read(byte[] buffer, int offset, int count)

chunk.Slice((int)chunkOffset, toRead)
.Span
.CopyTo(buffer.AsSpan(offset, toRead));
.CopyTo(buffer.SliceFast(0, toRead));
_position += (ulong)toRead;

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


/// <inheritdoc />
public override async ValueTask<int> ReadAsync(Memory<byte> buffer,
CancellationToken cancellationToken = new CancellationToken())
CancellationToken cancellationToken = new())
{
if (_position >= _source.Size.Value)
{
Expand Down Expand Up @@ -92,6 +100,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
Loading