Skip to content

Commit

Permalink
Merge pull request #2217 from Nexus-Mods/manifest-parse-error
Browse files Browse the repository at this point in the history
Fix SDV Manifest parse error
  • Loading branch information
Al12rs authored Oct 31, 2024
2 parents 4f9267e + 4f58913 commit e06a152
Showing 1 changed file with 14 additions and 5 deletions.
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

0 comments on commit e06a152

Please sign in to comment.