| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Buffers; |
| | | 5 | | using System.Diagnostics; |
| | | 6 | | using System.IO; |
| | | 7 | | using System.Runtime.InteropServices; |
| | | 8 | | using System.Threading; |
| | | 9 | | using System.Threading.Tasks; |
| | | 10 | | |
| | | 11 | | namespace System.Text.Json.Serialization |
| | | 12 | | { |
| | | 13 | | [StructLayout(LayoutKind.Auto)] |
| | | 14 | | internal struct StreamReadBufferState : IReadBufferState<StreamReadBufferState, Stream> |
| | | 15 | | { |
| | | 16 | | private byte[] _buffer; |
| | | 17 | | private byte _offset; // Read bytes offset typically used when skipping the UTF-8 BOM. |
| | | 18 | | private int _count; // Number of read bytes yet to be consumed by the serializer. |
| | | 19 | | private int _maxCount; // Number of bytes we need to clear before returning the buffer. |
| | | 20 | | private bool _isFirstBlock; |
| | | 21 | | private bool _isFinalBlock; |
| | | 22 | | |
| | | 23 | | // An "unsuccessful read" in this context refers to a buffer read operation that |
| | | 24 | | // wasn't sufficient to advance the reader to the next token. This occurs primarily |
| | | 25 | | // when consuming large JSON strings (which don't support streaming today) but is |
| | | 26 | | // also possible with other token types such as numbers, booleans, or nulls. |
| | | 27 | | // |
| | | 28 | | // The JsonSerializer.DeserializeAsyncEnumerable methods employ a special buffering |
| | | 29 | | // strategy where rather than attempting to fill the entire buffer, the deserializer |
| | | 30 | | // will be invoked as soon as the first chunk of data is read from the stream. |
| | | 31 | | // This is to ensure liveness: data should be surfaced on the IAE as soon as they |
| | | 32 | | // are streamed from the server. On the other hand, this can create performance |
| | | 33 | | // problems in cases where the underlying stream uses extremely fine-grained buffering. |
| | | 34 | | // For this reason, we employ a threshold that will revert to buffer filling once crossed. |
| | | 35 | | // The counter is reset to zero whenever the JSON reader has been advanced successfully. |
| | | 36 | | // |
| | | 37 | | // The threshold is set to 5 unsuccessful reads. This is a relatively conservative threshold |
| | | 38 | | // but should still make fallback unlikely in most scenarios. It should ensure that fallback |
| | | 39 | | // isn't triggered in null or boolean tokens even in the worst-case scenario where they are |
| | | 40 | | // streamed one byte at a time. |
| | | 41 | | private const int UnsuccessfulReadCountThreshold = 5; |
| | | 42 | | private int _unsuccessfulReadCount; |
| | | 43 | | |
| | | 44 | | public StreamReadBufferState(int initialBufferSize) |
| | 27962 | 45 | | { |
| | 27962 | 46 | | _buffer = ArrayPool<byte>.Shared.Rent(Math.Max(initialBufferSize, JsonConstants.Utf8Bom.Length)); |
| | 27962 | 47 | | _maxCount = _count = _offset = 0; |
| | 27962 | 48 | | _isFirstBlock = true; |
| | 27962 | 49 | | _isFinalBlock = false; |
| | 27962 | 50 | | } |
| | | 51 | | |
| | 28049 | 52 | | public readonly bool IsFinalBlock => _isFinalBlock; |
| | | 53 | | |
| | | 54 | | #if DEBUG |
| | 174 | 55 | | public readonly ReadOnlySequence<byte> Bytes => new(_buffer.AsMemory(_offset, _count)); |
| | | 56 | | #endif |
| | | 57 | | |
| | | 58 | | /// <summary> |
| | | 59 | | /// Read from the stream until either our buffer is filled or we hit EOF. |
| | | 60 | | /// Calling ReadCore is relatively expensive, so we minimize the number of times |
| | | 61 | | /// we need to call it. |
| | | 62 | | /// </summary> |
| | | 63 | | public readonly async ValueTask<StreamReadBufferState> ReadAsync(Stream stream, |
| | | 64 | | CancellationToken cancellationToken, |
| | | 65 | | bool fillBuffer = true) |
| | 27962 | 66 | | { |
| | | 67 | | // Since mutable structs don't work well with async state machines, |
| | | 68 | | // make all updates on a copy which is returned once complete. |
| | 27962 | 69 | | StreamReadBufferState bufferState = this; |
| | | 70 | | |
| | 27962 | 71 | | int minBufferCount = fillBuffer || _unsuccessfulReadCount > UnsuccessfulReadCountThreshold ? bufferState._bu |
| | | 72 | | do |
| | 55924 | 73 | | { |
| | 55924 | 74 | | int bytesRead = await stream.ReadAsync(bufferState._buffer.AsMemory(bufferState._count), cancellationTok |
| | | 75 | | |
| | 55924 | 76 | | if (bytesRead == 0) |
| | 27962 | 77 | | { |
| | 27962 | 78 | | bufferState._isFinalBlock = true; |
| | 27962 | 79 | | break; |
| | | 80 | | } |
| | | 81 | | |
| | 27962 | 82 | | bufferState._count += bytesRead; |
| | 27962 | 83 | | } |
| | 27962 | 84 | | while (bufferState._count < minBufferCount); |
| | | 85 | | |
| | 27962 | 86 | | bufferState.ProcessReadBytes(); |
| | 27962 | 87 | | return bufferState; |
| | 27962 | 88 | | } |
| | | 89 | | |
| | | 90 | | /// <summary> |
| | | 91 | | /// Read from the stream until either our buffer is filled or we hit EOF. |
| | | 92 | | /// Calling ReadCore is relatively expensive, so we minimize the number of times |
| | | 93 | | /// we need to call it. |
| | | 94 | | /// </summary> |
| | | 95 | | public void Read(Stream stream) |
| | 0 | 96 | | { |
| | | 97 | | do |
| | 0 | 98 | | { |
| | 0 | 99 | | int bytesRead = stream.Read( |
| | 0 | 100 | | #if NET |
| | 0 | 101 | | _buffer.AsSpan(_count)); |
| | | 102 | | #else |
| | | 103 | | _buffer, _count, _buffer.Length - _count); |
| | | 104 | | #endif |
| | | 105 | | |
| | 0 | 106 | | if (bytesRead == 0) |
| | 0 | 107 | | { |
| | 0 | 108 | | _isFinalBlock = true; |
| | 0 | 109 | | break; |
| | | 110 | | } |
| | | 111 | | |
| | 0 | 112 | | _count += bytesRead; |
| | 0 | 113 | | } |
| | 0 | 114 | | while (_count < _buffer.Length); |
| | | 115 | | |
| | 0 | 116 | | ProcessReadBytes(); |
| | 0 | 117 | | } |
| | | 118 | | |
| | | 119 | | /// <summary> |
| | | 120 | | /// Advances the buffer in anticipation of a subsequent read operation. |
| | | 121 | | /// </summary> |
| | | 122 | | public void Advance(long bytesConsumed) |
| | 27962 | 123 | | { |
| | 27962 | 124 | | Debug.Assert(bytesConsumed <= _count); |
| | | 125 | | |
| | 27962 | 126 | | int bytesConsumedInt = (int)bytesConsumed; |
| | | 127 | | |
| | 27962 | 128 | | _unsuccessfulReadCount = bytesConsumedInt == 0 ? _unsuccessfulReadCount + 1 : 0; |
| | 27962 | 129 | | _count -= bytesConsumedInt; |
| | | 130 | | |
| | 27962 | 131 | | if (!_isFinalBlock) |
| | 0 | 132 | | { |
| | | 133 | | // Check if we need to shift or expand the buffer because there wasn't enough data to complete deseriali |
| | 0 | 134 | | if ((uint)_count > ((uint)_buffer.Length / 2)) |
| | 0 | 135 | | { |
| | | 136 | | // We have less than half the buffer available, double the buffer size. |
| | 0 | 137 | | byte[] oldBuffer = _buffer; |
| | 0 | 138 | | int oldMaxCount = _maxCount; |
| | 0 | 139 | | byte[] newBuffer = ArrayPool<byte>.Shared.Rent((_buffer.Length < (int.MaxValue / 2)) ? _buffer.Lengt |
| | | 140 | | |
| | | 141 | | // Copy the unprocessed data to the new buffer while shifting the processed bytes. |
| | 0 | 142 | | Buffer.BlockCopy(oldBuffer, _offset + bytesConsumedInt, newBuffer, 0, _count); |
| | 0 | 143 | | _buffer = newBuffer; |
| | 0 | 144 | | _maxCount = _count; |
| | | 145 | | |
| | | 146 | | // Clear and return the old buffer |
| | 0 | 147 | | new Span<byte>(oldBuffer, 0, oldMaxCount).Clear(); |
| | 0 | 148 | | ArrayPool<byte>.Shared.Return(oldBuffer); |
| | 0 | 149 | | } |
| | 0 | 150 | | else if (_count != 0) |
| | 0 | 151 | | { |
| | | 152 | | // Shift the processed bytes to the beginning of buffer to make more room. |
| | 0 | 153 | | Buffer.BlockCopy(_buffer, _offset + bytesConsumedInt, _buffer, 0, _count); |
| | 0 | 154 | | } |
| | 0 | 155 | | } |
| | | 156 | | |
| | 27962 | 157 | | _offset = 0; |
| | 27962 | 158 | | } |
| | | 159 | | |
| | | 160 | | public void GetReader(JsonReaderState jsonReaderState, out Utf8JsonReader reader) |
| | 27962 | 161 | | { |
| | 27962 | 162 | | reader = new Utf8JsonReader( |
| | 27962 | 163 | | _buffer.AsSpan(_offset, _count), |
| | 27962 | 164 | | IsFinalBlock, |
| | 27962 | 165 | | jsonReaderState); |
| | 27962 | 166 | | } |
| | | 167 | | |
| | | 168 | | private void ProcessReadBytes() |
| | 27962 | 169 | | { |
| | 27962 | 170 | | if (_count > _maxCount) |
| | 27962 | 171 | | { |
| | 27962 | 172 | | _maxCount = _count; |
| | 27962 | 173 | | } |
| | | 174 | | |
| | 27962 | 175 | | if (_isFirstBlock) |
| | 27962 | 176 | | { |
| | 27962 | 177 | | _isFirstBlock = false; |
| | | 178 | | |
| | | 179 | | // Handle the UTF-8 BOM if present |
| | 27962 | 180 | | Debug.Assert(_buffer.Length >= JsonConstants.Utf8Bom.Length); |
| | 27962 | 181 | | if (_buffer.AsSpan(0, _count).StartsWith(JsonConstants.Utf8Bom)) |
| | 0 | 182 | | { |
| | 0 | 183 | | _offset = (byte)JsonConstants.Utf8Bom.Length; |
| | 0 | 184 | | _count -= JsonConstants.Utf8Bom.Length; |
| | 0 | 185 | | } |
| | 27962 | 186 | | } |
| | 27962 | 187 | | } |
| | | 188 | | |
| | | 189 | | public void Dispose() |
| | 27962 | 190 | | { |
| | | 191 | | // Clear only what we used and return the buffer to the pool |
| | 27962 | 192 | | new Span<byte>(_buffer, 0, _maxCount).Clear(); |
| | | 193 | | |
| | 27962 | 194 | | byte[] toReturn = _buffer; |
| | 27962 | 195 | | _buffer = null!; |
| | | 196 | | |
| | 27962 | 197 | | ArrayPool<byte>.Shared.Return(toReturn); |
| | 27962 | 198 | | } |
| | | 199 | | } |
| | | 200 | | } |