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

@@ -332,18 +332,16 @@ namespace OpenRA.Mods.Cnc.AudioLoaders
}
}
int Read(byte[] buffer, int offset, int count)
int Read(Span<byte> buffer)
{
var bytesWritten = 0;
var samplesLeft = Math.Min(count, buffer.Length - offset);
while (samplesLeft > 0)
while (buffer.Length > 0)
{
var len = FillBuffer(samplesLeft);
var len = FillBuffer(buffer.Length);
if (len == 0)
break;
Buffer.BlockCopy(this.buffer, 0, buffer, offset, len);
samplesLeft -= len;
offset += len;
this.buffer.AsSpan(..len).CopyTo(buffer);
buffer = buffer[len..];
bytesWritten += len;
}
@@ -372,13 +370,19 @@ namespace OpenRA.Mods.Cnc.AudioLoaders
public override int Read(byte[] buffer, int offset, int count)
{
return format.Read(buffer, offset, count);
return Read(buffer.AsSpan(offset, count));
}
public override int Read(Span<byte> buffer)
{
return format.Read(buffer);
}
public override void Flush() { throw new NotImplementedException(); }
public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); }
public override void SetLength(long value) { throw new NotImplementedException(); }
public override void Write(byte[] buffer, int offset, int count) { throw new NotImplementedException(); }
public override void Write(ReadOnlySpan<byte> buffer) { throw new NotImplementedException(); }
protected override void Dispose(bool disposing)
{