forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamExtensions.cs
More file actions
38 lines (34 loc) · 1.15 KB
/
StreamExtensions.cs
File metadata and controls
38 lines (34 loc) · 1.15 KB
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
#if !NET7_0_OR_GREATER
using System.Threading;
using System.Threading.Tasks;
// ReSharper disable once CheckNamespace
namespace System.IO
{
// Helpers to read/write Span/Memory<byte> to Stream before netstandard 2.1
static class StreamExtensions
{
public static void ReadExactly(this Stream stream, Span<byte> buffer)
{
var totalRead = 0;
while (totalRead < buffer.Length)
{
var read = stream.Read(buffer.Slice(totalRead));
if (read is 0)
throw new EndOfStreamException();
totalRead += read;
}
}
public static async ValueTask ReadExactlyAsync(this Stream stream, Memory<byte> buffer, CancellationToken cancellationToken = default)
{
var totalRead = 0;
while (totalRead < buffer.Length)
{
var read = await stream.ReadAsync(buffer.Slice(totalRead), cancellationToken).ConfigureAwait(false);
if (read is 0)
throw new EndOfStreamException();
totalRead += read;
}
}
}
}
#endif