| | | 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.Diagnostics.CodeAnalysis; |
| | | 7 | | using System.IO; |
| | | 8 | | using System.Runtime.InteropServices; |
| | | 9 | | using System.Threading; |
| | | 10 | | using System.Threading.Tasks; |
| | | 11 | | |
| | | 12 | | namespace System.Text |
| | | 13 | | { |
| | | 14 | | internal sealed class TranscodingStream : Stream |
| | | 15 | | { |
| | | 16 | | private const int DefaultReadByteBufferSize = 4 * 1024; // lifted from StreamReader.cs (FileStream) |
| | | 17 | | |
| | | 18 | | // We optimistically assume 1 byte ~ 1 char during transcoding. This is a good rule of thumb |
| | | 19 | | // but isn't always appropriate: transcoding between single-byte and multi-byte encodings |
| | | 20 | | // will violate this, as will any invalid data fixups performed by the transcoder itself. |
| | | 21 | | // To account for these unknowns we have a minimum scratch buffer size we use during the |
| | | 22 | | // transcoding process. This should be generous enough to account for even the largest |
| | | 23 | | // fallback mechanism we're likely to see in the real world. |
| | | 24 | | |
| | | 25 | | private const int MinWriteRentedArraySize = 4 * 1024; |
| | | 26 | | private const int MaxWriteRentedArraySize = 1024 * 1024; |
| | | 27 | | |
| | | 28 | | private readonly Encoding _innerEncoding; |
| | | 29 | | private readonly Encoding _thisEncoding; |
| | | 30 | | private Stream _innerStream; // null if the wrapper has been disposed |
| | | 31 | | private readonly bool _leaveOpen; |
| | | 32 | | |
| | | 33 | | /* |
| | | 34 | | * Fields used for writing bytes [this] -> chars -> bytes [inner] |
| | | 35 | | * Lazily initialized the first time we need to write |
| | | 36 | | */ |
| | | 37 | | |
| | | 38 | | private Encoder? _innerEncoder; |
| | | 39 | | private Decoder? _thisDecoder; |
| | | 40 | | |
| | | 41 | | /* |
| | | 42 | | * Fields used for reading bytes [inner] -> chars -> bytes [this] |
| | | 43 | | * Lazily initialized the first time we need to read |
| | | 44 | | */ |
| | | 45 | | |
| | | 46 | | private Encoder? _thisEncoder; |
| | | 47 | | private Decoder? _innerDecoder; |
| | | 48 | | private int _readCharBufferMaxSize; // the maximum number of characters _innerDecoder.ReadChars can return |
| | | 49 | | private byte[]? _readBuffer; // contains the data that Read() should return |
| | | 50 | | private int _readBufferOffset; |
| | | 51 | | private int _readBufferCount; |
| | | 52 | | |
| | 0 | 53 | | internal TranscodingStream(Stream innerStream, Encoding innerEncoding, Encoding thisEncoding, bool leaveOpen) |
| | | 54 | | { |
| | 0 | 55 | | Debug.Assert(innerStream != null); |
| | 0 | 56 | | Debug.Assert(innerEncoding != null); |
| | 0 | 57 | | Debug.Assert(thisEncoding != null); |
| | | 58 | | |
| | 0 | 59 | | _innerStream = innerStream; |
| | 0 | 60 | | _leaveOpen = leaveOpen; |
| | | 61 | | |
| | 0 | 62 | | _innerEncoding = innerEncoding; |
| | 0 | 63 | | _thisEncoding = thisEncoding; |
| | 0 | 64 | | } |
| | | 65 | | |
| | | 66 | | /* |
| | | 67 | | * Most CanXyz methods delegate to the inner stream, returning false |
| | | 68 | | * if this instance has been disposed. CanSeek is always false. |
| | | 69 | | */ |
| | | 70 | | |
| | 0 | 71 | | public override bool CanRead => _innerStream?.CanRead ?? false; |
| | | 72 | | |
| | 0 | 73 | | public override bool CanSeek => false; |
| | | 74 | | |
| | 0 | 75 | | public override bool CanWrite => _innerStream?.CanWrite ?? false; |
| | | 76 | | |
| | 0 | 77 | | public override long Length => throw new NotSupportedException(SR.NotSupported_UnseekableStream); |
| | | 78 | | |
| | | 79 | | public override long Position |
| | | 80 | | { |
| | 0 | 81 | | get => throw new NotSupportedException(SR.NotSupported_UnseekableStream); |
| | 0 | 82 | | set => ThrowHelper.ThrowNotSupportedException_UnseekableStream(); |
| | | 83 | | } |
| | | 84 | | |
| | | 85 | | public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? st |
| | 0 | 86 | | => TaskToAsyncResult.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), callback, state); |
| | | 87 | | |
| | | 88 | | public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? s |
| | 0 | 89 | | => TaskToAsyncResult.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), callback, state); |
| | | 90 | | |
| | | 91 | | protected override void Dispose(bool disposing) |
| | | 92 | | { |
| | 0 | 93 | | Debug.Assert(disposing, "This type isn't finalizable."); |
| | | 94 | | |
| | 0 | 95 | | if (_innerStream is null) |
| | | 96 | | { |
| | 0 | 97 | | return; // dispose called multiple times, ignore |
| | | 98 | | } |
| | | 99 | | |
| | | 100 | | // First, flush any pending data to the inner stream. |
| | | 101 | | |
| | 0 | 102 | | ArraySegment<byte> pendingData = FinalFlushWriteBuffers(); |
| | 0 | 103 | | if (pendingData.Count != 0) |
| | | 104 | | { |
| | 0 | 105 | | _innerStream.Write(pendingData); |
| | | 106 | | } |
| | | 107 | | |
| | | 108 | | // Mark our object as disposed |
| | | 109 | | |
| | 0 | 110 | | Stream innerStream = _innerStream; |
| | 0 | 111 | | _innerStream = null!; |
| | | 112 | | |
| | | 113 | | // And dispose the inner stream if needed |
| | | 114 | | |
| | 0 | 115 | | if (!_leaveOpen) |
| | | 116 | | { |
| | 0 | 117 | | innerStream.Dispose(); |
| | | 118 | | } |
| | 0 | 119 | | } |
| | | 120 | | |
| | | 121 | | public override ValueTask DisposeAsync() |
| | | 122 | | { |
| | 0 | 123 | | if (_innerStream is null) |
| | | 124 | | { |
| | 0 | 125 | | return default; // dispose called multiple times, ignore |
| | | 126 | | } |
| | | 127 | | |
| | | 128 | | // First, get any pending data destined for the inner stream. |
| | | 129 | | |
| | 0 | 130 | | ArraySegment<byte> pendingData = FinalFlushWriteBuffers(); |
| | | 131 | | |
| | 0 | 132 | | if (pendingData.Count == 0) |
| | | 133 | | { |
| | | 134 | | // Fast path: just dispose of the object graph. |
| | | 135 | | // No need to write anything to the stream first. |
| | | 136 | | |
| | 0 | 137 | | Stream innerStream = _innerStream; |
| | 0 | 138 | | _innerStream = null!; |
| | | 139 | | |
| | 0 | 140 | | return (_leaveOpen) |
| | 0 | 141 | | ? default /* no work to do */ |
| | 0 | 142 | | : innerStream.DisposeAsync(); |
| | | 143 | | } |
| | | 144 | | |
| | | 145 | | // Slower path; need to perform an async write followed by an async dispose. |
| | | 146 | | |
| | 0 | 147 | | return DisposeAsyncCore(pendingData); |
| | | 148 | | async ValueTask DisposeAsyncCore(ArraySegment<byte> pendingData) |
| | | 149 | | { |
| | 0 | 150 | | Debug.Assert(pendingData.Count != 0); |
| | | 151 | | |
| | 0 | 152 | | Stream innerStream = _innerStream; |
| | 0 | 153 | | _innerStream = null!; |
| | | 154 | | |
| | 0 | 155 | | await innerStream.WriteAsync(pendingData.AsMemory()).ConfigureAwait(false); |
| | | 156 | | |
| | 0 | 157 | | if (!_leaveOpen) |
| | | 158 | | { |
| | 0 | 159 | | await innerStream.DisposeAsync().ConfigureAwait(false); |
| | | 160 | | } |
| | 0 | 161 | | } |
| | | 162 | | } |
| | | 163 | | |
| | | 164 | | public override int EndRead(IAsyncResult asyncResult) |
| | 0 | 165 | | => TaskToAsyncResult.End<int>(asyncResult); |
| | | 166 | | |
| | | 167 | | public override void EndWrite(IAsyncResult asyncResult) |
| | 0 | 168 | | => TaskToAsyncResult.End(asyncResult); |
| | | 169 | | |
| | | 170 | | #pragma warning disable CS3016 // Arrays as attribute arguments is not CLS-compliant |
| | | 171 | | #pragma warning disable CS8774 // Member must have a non-null value when exiting. |
| | | 172 | | |
| | | 173 | | // Sets up the data structures that are necessary before any read operation takes place, |
| | | 174 | | // throwing if the object is in a state where reads are not possible. |
| | | 175 | | [MemberNotNull(nameof(_innerDecoder), nameof(_thisEncoder), nameof(_readBuffer))] |
| | | 176 | | private void EnsurePreReadConditions() |
| | | 177 | | { |
| | 0 | 178 | | ThrowIfDisposed(); |
| | 0 | 179 | | if (_innerDecoder is null) |
| | | 180 | | { |
| | 0 | 181 | | InitializeReadDataStructures(); |
| | | 182 | | } |
| | | 183 | | |
| | | 184 | | void InitializeReadDataStructures() |
| | | 185 | | { |
| | 0 | 186 | | if (!CanRead) |
| | | 187 | | { |
| | 0 | 188 | | ThrowHelper.ThrowNotSupportedException_UnreadableStream(); |
| | | 189 | | } |
| | | 190 | | |
| | 0 | 191 | | _innerDecoder = _innerEncoding.GetDecoder(); |
| | 0 | 192 | | _thisEncoder = _thisEncoding.GetEncoder(); |
| | 0 | 193 | | _readCharBufferMaxSize = _innerEncoding.GetMaxCharCount(DefaultReadByteBufferSize); |
| | | 194 | | |
| | | 195 | | // Can't use ArrayPool for the below array since it's an instance field of this object. |
| | | 196 | | // But since we never expose the raw array contents to our callers we can get away |
| | | 197 | | // with skipping the array zero-init during allocation. The segment points to the |
| | | 198 | | // data which we haven't yet read; however, we own the entire backing array and can |
| | | 199 | | // re-create the segment as needed once the array is repopulated. |
| | | 200 | | |
| | 0 | 201 | | _readBuffer = GC.AllocateUninitializedArray<byte>(_thisEncoding.GetMaxByteCount(_readCharBufferMaxSize)) |
| | 0 | 202 | | } |
| | 0 | 203 | | } |
| | | 204 | | |
| | | 205 | | // Sets up the data structures that are necessary before any write operation takes place, |
| | | 206 | | // throwing if the object is in a state where writes are not possible. |
| | | 207 | | [MemberNotNull(nameof(_thisDecoder), nameof(_innerEncoder))] |
| | | 208 | | private void EnsurePreWriteConditions() |
| | | 209 | | { |
| | 0 | 210 | | ThrowIfDisposed(); |
| | 0 | 211 | | if (_innerEncoder is null) |
| | | 212 | | { |
| | 0 | 213 | | InitializeReadDataStructures(); |
| | | 214 | | } |
| | | 215 | | |
| | | 216 | | void InitializeReadDataStructures() |
| | | 217 | | { |
| | 0 | 218 | | if (!CanWrite) |
| | | 219 | | { |
| | 0 | 220 | | ThrowHelper.ThrowNotSupportedException_UnwritableStream(); |
| | | 221 | | } |
| | | 222 | | |
| | 0 | 223 | | _innerEncoder = _innerEncoding.GetEncoder(); |
| | 0 | 224 | | _thisDecoder = _thisEncoding.GetDecoder(); |
| | 0 | 225 | | } |
| | 0 | 226 | | } |
| | | 227 | | |
| | | 228 | | #pragma warning restore CS8774 // Member must have a non-null value when exiting. |
| | | 229 | | #pragma warning restore CS3016 // Arrays as attribute arguments is not CLS-compliant |
| | | 230 | | |
| | | 231 | | // returns any pending data that needs to be flushed to the inner stream before disposal |
| | | 232 | | private ArraySegment<byte> FinalFlushWriteBuffers() |
| | | 233 | | { |
| | | 234 | | // If this stream was never used for writing, no-op. |
| | | 235 | | |
| | 0 | 236 | | if (_thisDecoder is null || _innerEncoder is null) |
| | | 237 | | { |
| | 0 | 238 | | return default; |
| | | 239 | | } |
| | | 240 | | |
| | | 241 | | // convert bytes [this] -> chars |
| | | 242 | | // Having leftover data in our buffers should be very rare since it should only |
| | | 243 | | // occur if the end of the stream contains an incomplete multi-byte sequence. |
| | | 244 | | // Let's not bother complicating this logic with array pool rentals or allocation- |
| | | 245 | | // avoiding loops. |
| | | 246 | | |
| | | 247 | | |
| | 0 | 248 | | char[] chars = []; |
| | 0 | 249 | | int charCount = _thisDecoder.GetCharCount([], 0, 0, flush: true); |
| | 0 | 250 | | if (charCount > 0) |
| | | 251 | | { |
| | 0 | 252 | | chars = new char[charCount]; |
| | 0 | 253 | | charCount = _thisDecoder.GetChars([], 0, 0, chars, 0, flush: true); |
| | | 254 | | } |
| | | 255 | | |
| | | 256 | | // convert chars -> bytes [inner] |
| | | 257 | | // It's possible that _innerEncoder might need to perform some end-of-text fixup |
| | | 258 | | // (due to flush: true), even if _thisDecoder didn't need to do so. |
| | | 259 | | |
| | 0 | 260 | | byte[] bytes = []; |
| | 0 | 261 | | int byteCount = _innerEncoder.GetByteCount(chars, 0, charCount, flush: true); |
| | 0 | 262 | | if (byteCount > 0) |
| | | 263 | | { |
| | 0 | 264 | | bytes = new byte[byteCount]; |
| | 0 | 265 | | byteCount = _innerEncoder.GetBytes(chars, 0, charCount, bytes, 0, flush: true); |
| | | 266 | | } |
| | | 267 | | |
| | 0 | 268 | | return new ArraySegment<byte>(bytes, 0, byteCount); |
| | | 269 | | } |
| | | 270 | | |
| | | 271 | | public override void Flush() |
| | | 272 | | { |
| | | 273 | | // Don't pass flush: true to our inner decoder + encoder here, since it could cause data |
| | | 274 | | // corruption if a flush occurs mid-stream. Wait until the stream is being closed. |
| | | 275 | | |
| | 0 | 276 | | ThrowIfDisposed(); |
| | 0 | 277 | | _innerStream.Flush(); |
| | 0 | 278 | | } |
| | | 279 | | |
| | | 280 | | public override Task FlushAsync(CancellationToken cancellationToken) |
| | | 281 | | { |
| | | 282 | | // Don't pass flush: true to our inner decoder + encoder here, since it could cause data |
| | | 283 | | // corruption if a flush occurs mid-stream. Wait until the stream is being closed. |
| | | 284 | | |
| | 0 | 285 | | ThrowIfDisposed(); |
| | 0 | 286 | | return _innerStream.FlushAsync(cancellationToken); |
| | | 287 | | } |
| | | 288 | | |
| | | 289 | | public override int Read(byte[] buffer, int offset, int count) |
| | | 290 | | { |
| | 0 | 291 | | ValidateBufferArguments(buffer, offset, count); |
| | | 292 | | |
| | 0 | 293 | | return Read(new Span<byte>(buffer, offset, count)); |
| | | 294 | | } |
| | | 295 | | |
| | | 296 | | public override int Read(Span<byte> buffer) |
| | | 297 | | { |
| | 0 | 298 | | EnsurePreReadConditions(); |
| | | 299 | | |
| | | 300 | | // If there's no data in our pending read buffer, we'll need to populate it from |
| | | 301 | | // the inner stream. We read the inner stream's bytes, decode that to chars using |
| | | 302 | | // the 'inner' encoding, then re-encode those chars under the 'this' encoding. |
| | | 303 | | // We've already calculated the worst-case expansions for the intermediate buffers, |
| | | 304 | | // so we use GetChars / GetBytes instead of Convert to simplify the below code |
| | | 305 | | // and to ensure an exception is thrown if the Encoding reported an incorrect |
| | | 306 | | // worst-case expansion. |
| | | 307 | | |
| | 0 | 308 | | if (_readBufferCount == 0) |
| | | 309 | | { |
| | 0 | 310 | | byte[] rentedBytes = ArrayPool<byte>.Shared.Rent(DefaultReadByteBufferSize); |
| | 0 | 311 | | char[] rentedChars = ArrayPool<char>.Shared.Rent(_readCharBufferMaxSize); |
| | | 312 | | |
| | | 313 | | try |
| | | 314 | | { |
| | | 315 | | int pendingReadDataPopulatedJustNow; |
| | | 316 | | bool isEofReached; |
| | | 317 | | |
| | | 318 | | do |
| | | 319 | | { |
| | | 320 | | // Beware: Use our constant value instead of 'rentedBytes.Length' for the count |
| | | 321 | | // parameter below. The reason for this is that the array pool could've returned |
| | | 322 | | // a larger-than-expected array, but our worst-case expansion calculations |
| | | 323 | | // performed earlier didn't take that into account. |
| | | 324 | | |
| | 0 | 325 | | int innerBytesReadJustNow = _innerStream.Read(rentedBytes, 0, DefaultReadByteBufferSize); |
| | 0 | 326 | | isEofReached = (innerBytesReadJustNow == 0); |
| | | 327 | | |
| | | 328 | | // Convert bytes [inner] -> chars, then convert chars -> bytes [this]. |
| | | 329 | | // We can't return 0 to our caller until inner stream EOF has been reached. But if the |
| | | 330 | | // inner stream returns a non-empty but incomplete buffer, GetBytes may return 0 anyway |
| | | 331 | | // since it can't yet make forward progress on the input data. If this happens, we'll |
| | | 332 | | // loop so that we don't return 0 to our caller until we truly see inner stream EOF. |
| | | 333 | | |
| | 0 | 334 | | int charsDecodedJustNow = _innerDecoder.GetChars(rentedBytes, 0, innerBytesReadJustNow, rentedCh |
| | 0 | 335 | | pendingReadDataPopulatedJustNow = _thisEncoder.GetBytes(rentedChars, 0, charsDecodedJustNow, _re |
| | 0 | 336 | | } while (!isEofReached && pendingReadDataPopulatedJustNow == 0); |
| | | 337 | | |
| | 0 | 338 | | _readBufferOffset = 0; |
| | 0 | 339 | | _readBufferCount = pendingReadDataPopulatedJustNow; |
| | 0 | 340 | | } |
| | | 341 | | finally |
| | | 342 | | { |
| | 0 | 343 | | ArrayPool<byte>.Shared.Return(rentedBytes); |
| | 0 | 344 | | ArrayPool<char>.Shared.Return(rentedChars); |
| | 0 | 345 | | } |
| | | 346 | | } |
| | | 347 | | |
| | | 348 | | // At this point: (a) we've populated our pending read buffer and there's |
| | | 349 | | // useful data to return to our caller; or (b) the pending read buffer is |
| | | 350 | | // empty because the inner stream has reached EOF and all pending read data |
| | | 351 | | // has already been flushed, and we should return 0. |
| | | 352 | | |
| | 0 | 353 | | int bytesToReturn = Math.Min(_readBufferCount, buffer.Length); |
| | 0 | 354 | | _readBuffer.AsSpan(_readBufferOffset, bytesToReturn).CopyTo(buffer); |
| | 0 | 355 | | _readBufferOffset += bytesToReturn; |
| | 0 | 356 | | _readBufferCount -= bytesToReturn; |
| | 0 | 357 | | return bytesToReturn; |
| | | 358 | | } |
| | | 359 | | |
| | | 360 | | public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) |
| | | 361 | | { |
| | 0 | 362 | | ValidateBufferArguments(buffer, offset, count); |
| | | 363 | | |
| | 0 | 364 | | return ReadAsync(new Memory<byte>(buffer, offset, count), cancellationToken).AsTask(); |
| | | 365 | | } |
| | | 366 | | |
| | | 367 | | public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken) |
| | | 368 | | { |
| | 0 | 369 | | EnsurePreReadConditions(); |
| | | 370 | | |
| | 0 | 371 | | if (cancellationToken.IsCancellationRequested) |
| | | 372 | | { |
| | 0 | 373 | | return ValueTask.FromCanceled<int>(cancellationToken); |
| | | 374 | | } |
| | | 375 | | |
| | 0 | 376 | | return ReadAsyncCore(buffer, cancellationToken); |
| | | 377 | | async ValueTask<int> ReadAsyncCore(Memory<byte> buffer, CancellationToken cancellationToken) |
| | | 378 | | { |
| | | 379 | | // If there's no data in our pending read buffer, we'll need to populate it from |
| | | 380 | | // the inner stream. We read the inner stream's bytes, decode that to chars using |
| | | 381 | | // the 'inner' encoding, then re-encode those chars under the 'this' encoding. |
| | | 382 | | // We've already calculated the worst-case expansions for the intermediate buffers, |
| | | 383 | | // so we use GetChars / GetBytes instead of Convert to simplify the below code |
| | | 384 | | // and to ensure an exception is thrown if the Encoding reported an incorrect |
| | | 385 | | // worst-case expansion. |
| | | 386 | | |
| | 0 | 387 | | if (_readBufferCount == 0) |
| | | 388 | | { |
| | 0 | 389 | | byte[] rentedBytes = ArrayPool<byte>.Shared.Rent(DefaultReadByteBufferSize); |
| | 0 | 390 | | char[] rentedChars = ArrayPool<char>.Shared.Rent(_readCharBufferMaxSize); |
| | | 391 | | |
| | | 392 | | try |
| | | 393 | | { |
| | | 394 | | int pendingReadDataPopulatedJustNow; |
| | | 395 | | bool isEofReached; |
| | | 396 | | |
| | | 397 | | do |
| | | 398 | | { |
| | | 399 | | // Beware: Use our constant value instead of 'rentedBytes.Length' when creating |
| | | 400 | | // the Mem<byte> struct. The reason for this is that the array pool could've returned |
| | | 401 | | // a larger-than-expected array, but our worst-case expansion calculations |
| | | 402 | | // performed earlier didn't take that into account. |
| | | 403 | | |
| | 0 | 404 | | int innerBytesReadJustNow = await _innerStream.ReadAsync(rentedBytes.AsMemory(0, DefaultRead |
| | 0 | 405 | | isEofReached = (innerBytesReadJustNow == 0); |
| | | 406 | | |
| | | 407 | | // Convert bytes [inner] -> chars, then convert chars -> bytes [this]. |
| | | 408 | | // We can't return 0 to our caller until inner stream EOF has been reached. But if the |
| | | 409 | | // inner stream returns a non-empty but incomplete buffer, GetBytes may return 0 anyway |
| | | 410 | | // since it can't yet make forward progress on the input data. If this happens, we'll |
| | | 411 | | // loop so that we don't return 0 to our caller until we truly see inner stream EOF. |
| | | 412 | | |
| | 0 | 413 | | int charsDecodedJustNow = _innerDecoder.GetChars(rentedBytes, 0, innerBytesReadJustNow, rent |
| | 0 | 414 | | pendingReadDataPopulatedJustNow = _thisEncoder.GetBytes(rentedChars, 0, charsDecodedJustNow, |
| | 0 | 415 | | } while (!isEofReached && pendingReadDataPopulatedJustNow == 0); |
| | | 416 | | |
| | 0 | 417 | | _readBufferOffset = 0; |
| | 0 | 418 | | _readBufferCount = pendingReadDataPopulatedJustNow; |
| | 0 | 419 | | } |
| | | 420 | | finally |
| | | 421 | | { |
| | 0 | 422 | | ArrayPool<byte>.Shared.Return(rentedBytes); |
| | 0 | 423 | | ArrayPool<char>.Shared.Return(rentedChars); |
| | 0 | 424 | | } |
| | | 425 | | } |
| | | 426 | | |
| | | 427 | | // At this point: (a) we've populated our pending read buffer and there's |
| | | 428 | | // useful data to return to our caller; or (b) the pending read buffer is |
| | | 429 | | // empty because the inner stream has reached EOF and all pending read data |
| | | 430 | | // has already been flushed, and we should return 0. |
| | | 431 | | |
| | 0 | 432 | | int bytesToReturn = Math.Min(_readBufferCount, buffer.Length); |
| | 0 | 433 | | _readBuffer.AsSpan(_readBufferOffset, bytesToReturn).CopyTo(buffer.Span); |
| | 0 | 434 | | _readBufferOffset += bytesToReturn; |
| | 0 | 435 | | _readBufferCount -= bytesToReturn; |
| | 0 | 436 | | return bytesToReturn; |
| | | 437 | | } |
| | | 438 | | } |
| | | 439 | | |
| | | 440 | | public override int ReadByte() |
| | | 441 | | { |
| | 0 | 442 | | byte b = 0; |
| | 0 | 443 | | return Read(new Span<byte>(ref b)) != 0 ? b : -1; |
| | | 444 | | } |
| | | 445 | | |
| | | 446 | | public override long Seek(long offset, SeekOrigin origin) |
| | 0 | 447 | | => throw new NotSupportedException(SR.NotSupported_UnseekableStream); |
| | | 448 | | |
| | | 449 | | public override void SetLength(long value) |
| | 0 | 450 | | => ThrowHelper.ThrowNotSupportedException_UnseekableStream(); |
| | | 451 | | |
| | | 452 | | [StackTraceHidden] |
| | | 453 | | private void ThrowIfDisposed() |
| | | 454 | | { |
| | 0 | 455 | | if (_innerStream is null) |
| | | 456 | | { |
| | 0 | 457 | | ThrowObjectDisposedException(); |
| | | 458 | | } |
| | 0 | 459 | | } |
| | | 460 | | |
| | | 461 | | [DoesNotReturn] |
| | | 462 | | [StackTraceHidden] |
| | | 463 | | private void ThrowObjectDisposedException() |
| | | 464 | | { |
| | 0 | 465 | | ThrowHelper.ThrowObjectDisposedException_StreamClosed(GetType().Name); |
| | | 466 | | } |
| | | 467 | | |
| | | 468 | | public override void Write(byte[] buffer, int offset, int count) |
| | | 469 | | { |
| | 0 | 470 | | ValidateBufferArguments(buffer, offset, count); |
| | | 471 | | |
| | 0 | 472 | | Write(new ReadOnlySpan<byte>(buffer, offset, count)); |
| | 0 | 473 | | } |
| | | 474 | | |
| | | 475 | | public override void Write(ReadOnlySpan<byte> buffer) |
| | | 476 | | { |
| | 0 | 477 | | EnsurePreWriteConditions(); |
| | | 478 | | |
| | 0 | 479 | | if (buffer.IsEmpty) |
| | | 480 | | { |
| | 0 | 481 | | return; |
| | | 482 | | } |
| | | 483 | | |
| | 0 | 484 | | int rentalLength = Math.Clamp(buffer.Length, MinWriteRentedArraySize, MaxWriteRentedArraySize); |
| | | 485 | | |
| | 0 | 486 | | char[] scratchChars = ArrayPool<char>.Shared.Rent(rentalLength); |
| | 0 | 487 | | byte[] scratchBytes = ArrayPool<byte>.Shared.Rent(rentalLength); |
| | | 488 | | |
| | | 489 | | try |
| | | 490 | | { |
| | | 491 | | bool decoderFinished, encoderFinished; |
| | | 492 | | do |
| | | 493 | | { |
| | | 494 | | // convert bytes [this] -> chars |
| | | 495 | | |
| | 0 | 496 | | _thisDecoder.Convert( |
| | 0 | 497 | | bytes: buffer, |
| | 0 | 498 | | chars: scratchChars, |
| | 0 | 499 | | flush: false, |
| | 0 | 500 | | out int bytesConsumed, |
| | 0 | 501 | | out int charsWritten, |
| | 0 | 502 | | out decoderFinished); |
| | | 503 | | |
| | 0 | 504 | | buffer = buffer.Slice(bytesConsumed); |
| | | 505 | | |
| | | 506 | | // convert chars -> bytes [inner] |
| | | 507 | | |
| | 0 | 508 | | Span<char> decodedChars = scratchChars.AsSpan(0, charsWritten); |
| | | 509 | | |
| | | 510 | | do |
| | | 511 | | { |
| | 0 | 512 | | _innerEncoder.Convert( |
| | 0 | 513 | | chars: decodedChars, |
| | 0 | 514 | | bytes: scratchBytes, |
| | 0 | 515 | | flush: false, |
| | 0 | 516 | | out int charsConsumed, |
| | 0 | 517 | | out int bytesWritten, |
| | 0 | 518 | | out encoderFinished); |
| | | 519 | | |
| | 0 | 520 | | decodedChars = decodedChars.Slice(charsConsumed); |
| | | 521 | | |
| | | 522 | | // It's more likely that the inner stream provides an optimized implementation of |
| | | 523 | | // Write(byte[], ...) over Write(ROS<byte>), so we'll prefer the byte[]-based overloads. |
| | | 524 | | |
| | 0 | 525 | | _innerStream.Write(scratchBytes, 0, bytesWritten); |
| | 0 | 526 | | } while (!encoderFinished); |
| | 0 | 527 | | } while (!decoderFinished); |
| | 0 | 528 | | } |
| | | 529 | | finally |
| | | 530 | | { |
| | 0 | 531 | | ArrayPool<char>.Shared.Return(scratchChars); |
| | 0 | 532 | | ArrayPool<byte>.Shared.Return(scratchBytes); |
| | 0 | 533 | | } |
| | 0 | 534 | | } |
| | | 535 | | |
| | | 536 | | public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) |
| | | 537 | | { |
| | 0 | 538 | | ValidateBufferArguments(buffer, offset, count); |
| | | 539 | | |
| | 0 | 540 | | return WriteAsync(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken).AsTask(); |
| | | 541 | | } |
| | | 542 | | |
| | | 543 | | public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken) |
| | | 544 | | { |
| | 0 | 545 | | EnsurePreWriteConditions(); |
| | | 546 | | |
| | 0 | 547 | | if (cancellationToken.IsCancellationRequested) |
| | | 548 | | { |
| | 0 | 549 | | return ValueTask.FromCanceled(cancellationToken); |
| | | 550 | | } |
| | | 551 | | |
| | 0 | 552 | | if (buffer.IsEmpty) |
| | | 553 | | { |
| | 0 | 554 | | return ValueTask.CompletedTask; |
| | | 555 | | } |
| | | 556 | | |
| | 0 | 557 | | return WriteAsyncCore(buffer, cancellationToken); |
| | | 558 | | async ValueTask WriteAsyncCore(ReadOnlyMemory<byte> remainingOuterEncodedBytes, CancellationToken cancellati |
| | | 559 | | { |
| | 0 | 560 | | int rentalLength = Math.Clamp(remainingOuterEncodedBytes.Length, MinWriteRentedArraySize, MaxWriteRented |
| | | 561 | | |
| | 0 | 562 | | char[] scratchChars = ArrayPool<char>.Shared.Rent(rentalLength); |
| | 0 | 563 | | byte[] scratchBytes = ArrayPool<byte>.Shared.Rent(rentalLength); |
| | | 564 | | |
| | | 565 | | try |
| | | 566 | | { |
| | | 567 | | bool decoderFinished, encoderFinished; |
| | | 568 | | do |
| | | 569 | | { |
| | | 570 | | // convert bytes [this] -> chars |
| | | 571 | | |
| | 0 | 572 | | _thisDecoder.Convert( |
| | 0 | 573 | | bytes: remainingOuterEncodedBytes.Span, |
| | 0 | 574 | | chars: scratchChars, |
| | 0 | 575 | | flush: false, |
| | 0 | 576 | | out int bytesConsumed, |
| | 0 | 577 | | out int charsWritten, |
| | 0 | 578 | | out decoderFinished); |
| | | 579 | | |
| | 0 | 580 | | remainingOuterEncodedBytes = remainingOuterEncodedBytes.Slice(bytesConsumed); |
| | | 581 | | |
| | | 582 | | // convert chars -> bytes [inner] |
| | | 583 | | |
| | 0 | 584 | | ArraySegment<char> decodedChars = new ArraySegment<char>(scratchChars, 0, charsWritten); |
| | | 585 | | |
| | | 586 | | do |
| | | 587 | | { |
| | 0 | 588 | | _innerEncoder.Convert( |
| | 0 | 589 | | chars: decodedChars, |
| | 0 | 590 | | bytes: scratchBytes, |
| | 0 | 591 | | flush: false, |
| | 0 | 592 | | out int charsConsumed, |
| | 0 | 593 | | out int bytesWritten, |
| | 0 | 594 | | out encoderFinished); |
| | | 595 | | |
| | 0 | 596 | | decodedChars = decodedChars.Slice(charsConsumed); |
| | 0 | 597 | | await _innerStream.WriteAsync(new ReadOnlyMemory<byte>(scratchBytes, 0, bytesWritten), cance |
| | 0 | 598 | | } while (!encoderFinished); |
| | 0 | 599 | | } while (!decoderFinished); |
| | 0 | 600 | | } |
| | | 601 | | finally |
| | | 602 | | { |
| | 0 | 603 | | ArrayPool<char>.Shared.Return(scratchChars); |
| | 0 | 604 | | ArrayPool<byte>.Shared.Return(scratchBytes); |
| | 0 | 605 | | } |
| | 0 | 606 | | } |
| | | 607 | | } |
| | | 608 | | |
| | | 609 | | public override void WriteByte(byte value) |
| | 0 | 610 | | => Write(new ReadOnlySpan<byte>(in value)); |
| | | 611 | | } |
| | | 612 | | } |
| | | 613 | | |