This repository has been archived by the owner on Nov 20, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 199
/
StreamHelperExtensions.cs
51 lines (46 loc) · 1.9 KB
/
StreamHelperExtensions.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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Buffers;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.WebUtilities
{
public static class StreamHelperExtensions
{
private const int _maxReadBufferSize = 1024 * 4;
public static Task DrainAsync(this Stream stream, CancellationToken cancellationToken)
{
return stream.DrainAsync(ArrayPool<byte>.Shared, null, cancellationToken);
}
public static Task DrainAsync(this Stream stream, long? limit, CancellationToken cancellationToken)
{
return stream.DrainAsync(ArrayPool<byte>.Shared, limit, cancellationToken);
}
public static async Task DrainAsync(this Stream stream, ArrayPool<byte> bytePool, long? limit, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var buffer = bytePool.Rent(_maxReadBufferSize);
long total = 0;
try
{
var read = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken);
while (read > 0)
{
// Not all streams support cancellation directly.
cancellationToken.ThrowIfCancellationRequested();
if (limit.HasValue && limit.Value - total < read)
{
throw new InvalidDataException($"The stream exceeded the data limit {limit.Value}.");
}
total += read;
read = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken);
}
}
finally
{
bytePool.Return(buffer);
}
}
}
}