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

@@ -80,18 +80,23 @@ namespace OpenRA.Primitives
}
public override int Read(byte[] buffer, int offset, int count)
{
return Read(buffer.AsSpan(offset, count));
}
public override int Read(Span<byte> buffer)
{
int bytesRead;
if (position >= Stream1.Length)
bytesRead = Stream2.Read(buffer, offset, count);
else if (count > Stream1.Length)
bytesRead = Stream2.Read(buffer);
else if (buffer.Length > Stream1.Length)
{
bytesRead = Stream1.Read(buffer, offset, (int)Stream1.Length);
bytesRead += Stream2.Read(buffer, (int)Stream1.Length, count - (int)Stream1.Length);
bytesRead = Stream1.Read(buffer[..(int)Stream1.Length]);
bytesRead += Stream2.Read(buffer[(int)Stream1.Length..]);
}
else
bytesRead = Stream1.Read(buffer, offset, count);
bytesRead = Stream1.Read(buffer);
position += bytesRead;
@@ -108,6 +113,11 @@ namespace OpenRA.Primitives
throw new NotSupportedException();
}
public override void Write(ReadOnlySpan<byte> buffer)
{
throw new NotSupportedException();
}
public override bool CanRead => Stream1.CanRead && Stream2.CanRead;
public override bool CanSeek => Stream1.CanSeek && Stream2.CanSeek;