-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
StreamExtensions.cs
99 lines (94 loc) · 2.85 KB
/
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Azure.Storage
{
/// <summary>
/// Extension methods for working with Streams.
/// </summary>
internal static partial class StreamExtensions
{
public static async Task<int> ReadInternal(
this Stream stream,
byte[] buffer,
int offset,
int count,
bool async,
CancellationToken cancellationToken)
{
if (async)
{
return await stream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
}
else
{
return stream.Read(buffer, offset, count);
}
}
public static async Task WriteInternal(
this Stream stream,
byte[] buffer,
int offset,
int count,
bool async,
CancellationToken cancellationToken)
{
if (async)
{
await stream.WriteAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
}
else
{
stream.Write(buffer, offset, count);
}
}
public static Task CopyToInternal(
this Stream src,
Stream dest,
bool async,
CancellationToken cancellationToken)
=> CopyToInternal(
src,
dest,
bufferSize: 81920, // default from .NET documentation
async,
cancellationToken);
/// <summary>
/// Reads the bytes from the source stream and writes them to the destination stream.
/// </summary>
/// <param name="src">
/// Stream to copy from.
/// </param>
/// <param name="dest">
/// Stream to copy to.
/// </param>
/// <param name="bufferSize">
/// The size, in bytes, of the buffer. This value must be greater than zero.
/// </param>
/// <param name="async">
/// Whether to perform the operation asynchronously.
/// </param>
/// <param name="cancellationToken">
/// Cancellation token for the operation.
/// </param>
/// <returns></returns>
public static async Task CopyToInternal(
this Stream src,
Stream dest,
int bufferSize,
bool async,
CancellationToken cancellationToken)
{
if (async)
{
await src.CopyToAsync(dest, bufferSize, cancellationToken).ConfigureAwait(false);
}
else
{
src.CopyTo(dest, bufferSize);
}
}
}
}