| | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | 2 | | // Licensed under the MIT License. |
| | 3 | |
|
| | 4 | | // Copied from https://github.com/aspnet/AspNetCore/tree/master/src/Http/WebUtilities/src |
| | 5 | |
|
| | 6 | | using System.Buffers; |
| | 7 | | using System.IO; |
| | 8 | | using System.Threading; |
| | 9 | | using System.Threading.Tasks; |
| | 10 | |
|
| | 11 | | #pragma warning disable IDE1006 // Prefix _ unexpected |
| | 12 | |
|
| | 13 | | namespace Azure.Core.Http |
| | 14 | | { |
| | 15 | | internal static class StreamHelperExtensions |
| | 16 | | { |
| | 17 | | private const int _maxReadBufferSize = 1024 * 4; |
| | 18 | |
|
| | 19 | | public static Task DrainAsync(this Stream stream, CancellationToken cancellationToken) |
| | 20 | | { |
| 1360 | 21 | | return stream.DrainAsync(ArrayPool<byte>.Shared, null, cancellationToken); |
| | 22 | | } |
| | 23 | |
|
| | 24 | | public static Task DrainAsync(this Stream stream, long? limit, CancellationToken cancellationToken) |
| | 25 | | { |
| 88 | 26 | | return stream.DrainAsync(ArrayPool<byte>.Shared, limit, cancellationToken); |
| | 27 | | } |
| | 28 | |
|
| | 29 | | public static async Task DrainAsync(this Stream stream, ArrayPool<byte> bytePool, long? limit, CancellationToken |
| | 30 | | { |
| 1448 | 31 | | cancellationToken.ThrowIfCancellationRequested(); |
| 1448 | 32 | | var buffer = bytePool.Rent(_maxReadBufferSize); |
| 1448 | 33 | | long total = 0; |
| | 34 | | try |
| | 35 | | { |
| 1448 | 36 | | var read = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); |
| 1448 | 37 | | while (read > 0) |
| | 38 | | { |
| | 39 | | // Not all streams support cancellation directly. |
| 0 | 40 | | cancellationToken.ThrowIfCancellationRequested(); |
| 0 | 41 | | if (limit.HasValue && limit.GetValueOrDefault() - total < read) |
| | 42 | | { |
| 0 | 43 | | throw new InvalidDataException($"The stream exceeded the data limit {limit.GetValueOrDefault()}. |
| | 44 | | } |
| 0 | 45 | | total += read; |
| 0 | 46 | | read = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); |
| | 47 | | } |
| 1448 | 48 | | } |
| | 49 | | finally |
| | 50 | | { |
| 1448 | 51 | | bytePool.Return(buffer); |
| | 52 | | } |
| 1448 | 53 | | } |
| | 54 | | } |
| | 55 | | } |