Welcome to mirror list, hosted at ThFree Co, Russian Federation.

BufferedReadStream.cs « src « WebUtilities « Http « src - github.com/dotnet/aspnetcore.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: da5f3f9bbe2522e8520364ca4ab321629829d183 (plain)
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Buffers;
using System.Text;

namespace Microsoft.AspNetCore.WebUtilities;

/// <summary>
/// A Stream that wraps another stream and allows reading lines.
/// The data is buffered in memory.
/// </summary>
public class BufferedReadStream : Stream
{
    private const byte CR = (byte)'\r';
    private const byte LF = (byte)'\n';

    private readonly Stream _inner;
    private readonly byte[] _buffer;
    private readonly ArrayPool<byte> _bytePool;
    private int _bufferOffset;
    private int _bufferCount;
    private bool _disposed;

    /// <summary>
    /// Creates a new stream.
    /// </summary>
    /// <param name="inner">The stream to wrap.</param>
    /// <param name="bufferSize">Size of buffer in bytes.</param>
    public BufferedReadStream(Stream inner, int bufferSize)
        : this(inner, bufferSize, ArrayPool<byte>.Shared)
    {
    }

    /// <summary>
    /// Creates a new stream.
    /// </summary>
    /// <param name="inner">The stream to wrap.</param>
    /// <param name="bufferSize">Size of buffer in bytes.</param>
    /// <param name="bytePool">ArrayPool for the buffer.</param>
    public BufferedReadStream(Stream inner, int bufferSize, ArrayPool<byte> bytePool)
    {
        if (inner == null)
        {
            throw new ArgumentNullException(nameof(inner));
        }

        _inner = inner;
        _bytePool = bytePool;
        _buffer = bytePool.Rent(bufferSize);
    }

    /// <summary>
    /// The currently buffered data.
    /// </summary>
    public ArraySegment<byte> BufferedData
    {
        get { return new ArraySegment<byte>(_buffer, _bufferOffset, _bufferCount); }
    }

    /// <inheritdoc/>
    public override bool CanRead
    {
        get { return _inner.CanRead || _bufferCount > 0; }
    }

    /// <inheritdoc/>
    public override bool CanSeek
    {
        get { return _inner.CanSeek; }
    }

    /// <inheritdoc/>
    public override bool CanTimeout
    {
        get { return _inner.CanTimeout; }
    }

    /// <inheritdoc/>
    public override bool CanWrite
    {
        get { return _inner.CanWrite; }
    }

    /// <inheritdoc/>
    public override long Length
    {
        get { return _inner.Length; }
    }

    /// <inheritdoc/>
    public override long Position
    {
        get { return _inner.Position - _bufferCount; }
        set
        {
            if (value < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(value), value, "Position must be positive.");
            }
            if (value == Position)
            {
                return;
            }

            // Backwards?
            if (value <= _inner.Position)
            {
                // Forward within the buffer?
                var innerOffset = (int)(_inner.Position - value);
                if (innerOffset <= _bufferCount)
                {
                    // Yes, just skip some of the buffered data
                    _bufferOffset += innerOffset;
                    _bufferCount -= innerOffset;
                }
                else
                {
                    // No, reset the buffer
                    _bufferOffset = 0;
                    _bufferCount = 0;
                    _inner.Position = value;
                }
            }
            else
            {
                // Forward, reset the buffer
                _bufferOffset = 0;
                _bufferCount = 0;
                _inner.Position = value;
            }
        }
    }

    /// <inheritdoc/>
    public override long Seek(long offset, SeekOrigin origin)
    {
        if (origin == SeekOrigin.Begin)
        {
            Position = offset;
        }
        else if (origin == SeekOrigin.Current)
        {
            Position = Position + offset;
        }
        else // if (origin == SeekOrigin.End)
        {
            Position = Length + offset;
        }
        return Position;
    }

    /// <inheritdoc/>
    public override void SetLength(long value)
    {
        _inner.SetLength(value);
    }

    /// <inheritdoc/>
    protected override void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            _disposed = true;
            _bytePool.Return(_buffer);

            if (disposing)
            {
                _inner.Dispose();
            }
        }
    }

    /// <inheritdoc/>
    public override void Flush()
    {
        _inner.Flush();
    }

    /// <inheritdoc/>
    public override Task FlushAsync(CancellationToken cancellationToken)
    {
        return _inner.FlushAsync(cancellationToken);
    }

    /// <inheritdoc/>
    public override void Write(byte[] buffer, int offset, int count)
    {
        _inner.Write(buffer, offset, count);
    }

    /// <inheritdoc/>
    public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
    {
        return _inner.WriteAsync(buffer, cancellationToken);
    }

    /// <inheritdoc/>
    public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
    {
        return _inner.WriteAsync(buffer, offset, count, cancellationToken);
    }

    /// <inheritdoc/>
    public override int Read(byte[] buffer, int offset, int count)
    {
        ValidateBufferArguments(buffer, offset, count);

        // Drain buffer
        if (_bufferCount > 0)
        {
            int toCopy = Math.Min(_bufferCount, count);
            Buffer.BlockCopy(_buffer, _bufferOffset, buffer, offset, toCopy);
            _bufferOffset += toCopy;
            _bufferCount -= toCopy;
            return toCopy;
        }

        return _inner.Read(buffer, offset, count);
    }

    /// <inheritdoc/>
    public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
    {
        return ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
    }

    /// <inheritdoc/>
    public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken)
    {
        // Drain buffer
        if (_bufferCount > 0)
        {
            int toCopy = Math.Min(_bufferCount, buffer.Length);
            _buffer.AsMemory(_bufferOffset, toCopy).CopyTo(buffer);
            _bufferOffset += toCopy;
            _bufferCount -= toCopy;
            return toCopy;
        }

        return await _inner.ReadAsync(buffer, cancellationToken);
    }

    /// <summary>
    /// Ensures that the buffer is not empty.
    /// </summary>
    /// <returns>Returns <c>true</c> if the buffer is not empty; <c>false</c> otherwise.</returns>
    public bool EnsureBuffered()
    {
        if (_bufferCount > 0)
        {
            return true;
        }
        // Downshift to make room
        _bufferOffset = 0;
        _bufferCount = _inner.Read(_buffer, 0, _buffer.Length);
        return _bufferCount > 0;
    }

    /// <summary>
    /// Ensures that the buffer is not empty.
    /// </summary>
    /// <param name="cancellationToken">Cancellation token.</param>
    /// <returns>Returns <c>true</c> if the buffer is not empty; <c>false</c> otherwise.</returns>
    public async Task<bool> EnsureBufferedAsync(CancellationToken cancellationToken)
    {
        if (_bufferCount > 0)
        {
            return true;
        }
        // Downshift to make room
        _bufferOffset = 0;
        _bufferCount = await _inner.ReadAsync(_buffer.AsMemory(), cancellationToken);
        return _bufferCount > 0;
    }

    /// <summary>
    /// Ensures that a minimum amount of buffered data is available.
    /// </summary>
    /// <param name="minCount">Minimum amount of buffered data.</param>
    /// <returns>Returns <c>true</c> if the minimum amount of buffered data is available; <c>false</c> otherwise.</returns>
    public bool EnsureBuffered(int minCount)
    {
        if (minCount > _buffer.Length)
        {
            throw new ArgumentOutOfRangeException(nameof(minCount), minCount, "The value must be smaller than the buffer size: " + _buffer.Length);
        }
        while (_bufferCount < minCount)
        {
            // Downshift to make room
            if (_bufferOffset > 0)
            {
                if (_bufferCount > 0)
                {
                    Buffer.BlockCopy(_buffer, _bufferOffset, _buffer, 0, _bufferCount);
                }
                _bufferOffset = 0;
            }
            int read = _inner.Read(_buffer, _bufferOffset + _bufferCount, _buffer.Length - _bufferCount - _bufferOffset);
            _bufferCount += read;
            if (read == 0)
            {
                return false;
            }
        }
        return true;
    }

    /// <summary>
    /// Ensures that a minimum amount of buffered data is available.
    /// </summary>
    /// <param name="minCount">Minimum amount of buffered data.</param>
    /// <param name="cancellationToken">Cancellation token.</param>
    /// <returns>Returns <c>true</c> if the minimum amount of buffered data is available; <c>false</c> otherwise.</returns>
    public async Task<bool> EnsureBufferedAsync(int minCount, CancellationToken cancellationToken)
    {
        if (minCount > _buffer.Length)
        {
            throw new ArgumentOutOfRangeException(nameof(minCount), minCount, "The value must be smaller than the buffer size: " + _buffer.Length);
        }
        while (_bufferCount < minCount)
        {
            // Downshift to make room
            if (_bufferOffset > 0)
            {
                if (_bufferCount > 0)
                {
                    Buffer.BlockCopy(_buffer, _bufferOffset, _buffer, 0, _bufferCount);
                }
                _bufferOffset = 0;
            }
            int read = await _inner.ReadAsync(_buffer.AsMemory(_bufferOffset + _bufferCount, _buffer.Length - _bufferCount - _bufferOffset), cancellationToken);
            _bufferCount += read;
            if (read == 0)
            {
                return false;
            }
        }
        return true;
    }

    /// <summary>
    /// Reads a line. A line is defined as a sequence of characters followed by
    /// a carriage return immediately followed by a line feed. The resulting string does not
    /// contain the terminating carriage return and line feed.
    /// </summary>
    /// <param name="lengthLimit">Maximum allowed line length.</param>
    /// <returns>A line.</returns>
    public string ReadLine(int lengthLimit)
    {
        CheckDisposed();
        using (var builder = new MemoryStream(200))
        {
            bool foundCR = false, foundCRLF = false;

            while (!foundCRLF && EnsureBuffered())
            {
                if (builder.Length > lengthLimit)
                {
                    throw new InvalidDataException($"Line length limit {lengthLimit} exceeded.");
                }
                ProcessLineChar(builder, ref foundCR, ref foundCRLF);
            }

            return DecodeLine(builder, foundCRLF);
        }
    }

    /// <summary>
    /// Reads a line. A line is defined as a sequence of characters followed by
    /// a carriage return immediately followed by a line feed. The resulting string does not
    /// contain the terminating carriage return and line feed.
    /// </summary>
    /// <param name="lengthLimit">Maximum allowed line length.</param>
    /// <param name="cancellationToken">Cancellation token.</param>
    /// <returns>A line.</returns>
    public async Task<string> ReadLineAsync(int lengthLimit, CancellationToken cancellationToken)
    {
        CheckDisposed();
        using (var builder = new MemoryStream(200))
        {
            bool foundCR = false, foundCRLF = false;

            while (!foundCRLF && await EnsureBufferedAsync(cancellationToken))
            {
                if (builder.Length > lengthLimit)
                {
                    throw new InvalidDataException($"Line length limit {lengthLimit} exceeded.");
                }

                ProcessLineChar(builder, ref foundCR, ref foundCRLF);
            }

            return DecodeLine(builder, foundCRLF);
        }
    }

    private void ProcessLineChar(MemoryStream builder, ref bool foundCR, ref bool foundCRLF)
    {
        var b = _buffer[_bufferOffset];
        builder.WriteByte(b);
        _bufferOffset++;
        _bufferCount--;
        if (b == LF && foundCR)
        {
            foundCRLF = true;
            return;
        }
        foundCR = b == CR;
    }

    private static string DecodeLine(MemoryStream builder, bool foundCRLF)
    {
        // Drop the final CRLF, if any
        var length = foundCRLF ? builder.Length - 2 : builder.Length;
        return Encoding.UTF8.GetString(builder.ToArray(), 0, (int)length);
    }

    private void CheckDisposed()
    {
        ObjectDisposedException.ThrowIf(_disposed, nameof(BufferedReadStream));
    }
}