using System.Buffers;
namespace System.IO;
///
/// A polyfill type with extensions for .
///
internal static class StreamExtensions
{
///
/// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
///
/// The input instance.
/// A region of memory. When this method returns, the contents of this region are replaced by the bytes read from the current source.
/// The total number of bytes read into the buffer.
public static int Read(this Stream stream, Span span)
{
if (span.IsEmpty)
{
return 0;
}
byte[] array = ArrayPool.Shared.Rent(span.Length);
int bytesRead = stream.Read(array, 0, span.Length);
array.AsSpan(0, bytesRead).CopyTo(span);
ArrayPool.Shared.Return(array);
return bytesRead;
}
///
/// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
///
/// The input instance.
/// A region of memory. This method copies the contents of this region to the current stream.
public static void Write(this Stream stream, ReadOnlySpan span)
{
if (span.IsEmpty)
{
return;
}
byte[] array = ArrayPool.Shared.Rent(span.Length);
span.CopyTo(array);
stream.Write(array, 0, span.Length);
ArrayPool.Shared.Return(array);
}
}