/
StreamExtensions.cs
45 lines (36 loc) · 984 Bytes
/
StreamExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#if NET461 || NETSTANDARD2_0
using System.Buffers;
namespace System.IO
{
public static class StreamExtensions
{
public static int Read(this Stream stream, Span<byte> buffer)
{
byte[] temp = ArrayPool<byte>.Shared.Rent(buffer.Length);
try
{
int read = stream.Read(buffer);
temp.AsSpan(0, read).CopyTo(buffer);
return read;
}
finally
{
ArrayPool<byte>.Shared.Return(temp);
}
}
public static void Write(this Stream stream, ReadOnlySpan<byte> buffer)
{
byte[] temp = ArrayPool<byte>.Shared.Rent(buffer.Length);
buffer.CopyTo(temp);
try
{
stream.Write(temp, 0, buffer.Length);
}
finally
{
ArrayPool<byte>.Shared.Return(temp);
}
}
}
}
#endif