Implement Stream.Read(Span<byte>) overloads.

The default Stream implementation of this method has to rent an array so it can call the overload that accepts an array, and then copy the output over. This is because the array overload is required and the span overload was only added more recently.

We can avoid the overhead of this by implementing the span overload and working with the destination span directly. Do so for all classes we have that derive from Stream, and redirect their array overload to the span overload for code reuse.
This commit is contained in:
RoosterDragon
2023-11-10 20:09:29 +00:00
committed by Paul Chote
parent d05b07a5b0
commit b313f47660
5 changed files with 64 additions and 28 deletions

View File

@@ -51,6 +51,7 @@ namespace OpenRA.Primitives
public sealed override void SetLength(long value) { throw new NotSupportedException(); }
public sealed override void WriteByte(byte value) { throw new NotSupportedException(); }
public sealed override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); }
public override void Write(ReadOnlySpan<byte> buffer) { throw new NotSupportedException(); }
public sealed override void Flush() { throw new NotSupportedException(); }
public sealed override int ReadByte()
@@ -70,31 +71,36 @@ namespace OpenRA.Primitives
public sealed override int Read(byte[] buffer, int offset, int count)
{
var copied = 0;
ConsumeData(buffer, offset, count, ref copied);
return Read(buffer.AsSpan(offset, count));
}
while (copied < count && !baseStreamEmpty)
public override int Read(Span<byte> buffer)
{
var copied = 0;
ConsumeData(buffer, ref copied);
while (copied < buffer.Length && !baseStreamEmpty)
{
baseStreamEmpty = BufferData(baseStream, data);
ConsumeData(buffer, offset, count, ref copied);
ConsumeData(buffer, ref copied);
}
return copied;
}
/// <summary>
/// Reads data into a buffer, which will be used to satisfy <see cref="ReadByte()"/> and
/// <see cref="Read(byte[], int, int)"/> calls.
/// Reads data into a buffer, which will be used to satisfy <see cref="ReadByte()"/>,
/// <see cref="Read(byte[], int, int)"/> and <see cref="Read(Span{byte})"/> calls.
/// </summary>
/// <param name="baseStream">The source stream from which bytes should be read.</param>
/// <param name="data">The queue where bytes should be enqueued. Do not dequeue from this buffer.</param>
/// <returns>Return true if all data has been read; otherwise, false.</returns>
protected abstract bool BufferData(Stream baseStream, Queue<byte> data);
void ConsumeData(byte[] buffer, int offset, int count, ref int copied)
void ConsumeData(Span<byte> buffer, ref int copied)
{
while (copied < count && data.Count > 0)
buffer[offset + copied++] = data.Dequeue();
while (copied < buffer.Length && data.Count > 0)
buffer[copied++] = data.Dequeue();
}
protected override void Dispose(bool disposing)