I am working with network buffers and streams, and Span and Memory would fit perfectly in the application requirements.
As per this question, I would like to get a Stream to accept Span as a parameter. I know that is implemented in .NET Core 2.1, but I was wondering if there's a way to get this functionality in .NET Framework as well? (I am using 4.7.1)
Something like:
Span<Byte> buffer = new Span<byte>();
stream.Read(buffer);
I managed to solve this by writing an extension method for the Stream class and implementing .NET Core's default behaviour for dealing with Span.
public static int Read(this Stream thisStream, Span<byte> buffer)
{
byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length);
try
{
int numRead = thisStream.Read(sharedBuffer, 0, buffer.Length);
if ((uint)numRead > (uint)buffer.Length)
{
throw new IOException(SR.IO_StreamTooLong);
}
new Span<byte>(sharedBuffer, 0, numRead).CopyTo(buffer);
return numRead;
}
finally { ArrayPool<byte>.Shared.Return(sharedBuffer); }
}
and
public static void Write(this Stream thisStream, ReadOnlySpan<byte> buffer)
{
byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length);
try
{
buffer.CopyTo(sharedBuffer);
thisStream.Write(sharedBuffer, 0, buffer.Length);
}
finally { ArrayPool<byte>.Shared.Return(sharedBuffer); }
}
Unfortunately, since this functionality is not yet implemented in .Net Standard it is not included in .Net Framework.
Edit: I remember that I read from somewhere that there is pre-release NuGet package which can be used with .Net Framework
Check NuGet with System.Memory
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With