Skip to content
Open
Show file tree
Hide file tree
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
15 changes: 11 additions & 4 deletions src/Http/WebUtilities/src/FileBufferingWriteStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,20 +107,27 @@ public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken
public override void Write(byte[] buffer, int offset, int count)
{
ValidateBufferArguments(buffer, offset, count);

Write(buffer.AsSpan(offset, count));
}

/// <inheritdoc />
public override void Write(ReadOnlySpan<byte> buffer)
{
ThrowIfDisposed();

if (_bufferLimit.HasValue && _bufferLimit - Length < count)
if (_bufferLimit.HasValue && _bufferLimit - Length < buffer.Length)
{
Dispose();
throw new IOException("Buffer limit exceeded.");
}

// Allow buffering in memory if we're below the memory threshold once the current buffer is written.
var allowMemoryBuffer = (_memoryThreshold - count) >= PagedByteBuffer.Length;
var allowMemoryBuffer = (_memoryThreshold - buffer.Length) >= PagedByteBuffer.Length;
if (allowMemoryBuffer)
{
// Buffer content in the MemoryStream if it has capacity.
PagedByteBuffer.Add(buffer, offset, count);
PagedByteBuffer.Add(buffer);
Debug.Assert(PagedByteBuffer.Length <= _memoryThreshold);
}
else
Expand All @@ -132,7 +139,7 @@ public override void Write(byte[] buffer, int offset, int count)
// Spool memory content to disk.
PagedByteBuffer.MoveTo(FileStream);

FileStream.Write(buffer, offset, count);
FileStream.Write(buffer);
}
}

Expand Down
11 changes: 7 additions & 4 deletions src/Http/WebUtilities/src/PagedByteBuffer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,20 +44,23 @@ public void Add(byte[] buffer, int offset, int count)
=> Add(buffer.AsMemory(offset, count));

public void Add(ReadOnlyMemory<byte> memory)
=> Add(memory.Span);

public void Add(ReadOnlySpan<byte> span)
{
ThrowIfDisposed();

while (!memory.IsEmpty)
while (!span.IsEmpty)
{
var currentPage = CurrentPage;
var copyLength = Math.Min(memory.Length, currentPage.Length - _currentPageIndex);
var copyLength = Math.Min(span.Length, currentPage.Length - _currentPageIndex);

memory.Slice(0, copyLength).CopyTo(currentPage.AsMemory(_currentPageIndex, copyLength));
span.Slice(0, copyLength).CopyTo(currentPage.AsSpan(_currentPageIndex, copyLength));

Length += copyLength;
_currentPageIndex += copyLength;

memory = memory.Slice(copyLength);
span = span.Slice(copyLength);
}
}

Expand Down
1 change: 1 addition & 0 deletions src/Http/WebUtilities/src/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
#nullable enable
override Microsoft.AspNetCore.WebUtilities.FileBufferingWriteStream.Write(System.ReadOnlySpan<byte> buffer) -> void
Loading