| | | 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.Threading; |
| | | 8 | | using System.Threading.Tasks; |
| | | 9 | | |
| | | 10 | | namespace System.IO.Compression |
| | | 11 | | { |
| | | 12 | | public sealed partial class ZstandardStream |
| | | 13 | | { |
| | | 14 | | private ZstandardDecoder? _decoder; |
| | | 15 | | private bool _nonEmptyInput; |
| | | 16 | | private bool _endOfStream; |
| | | 17 | | |
| | | 18 | | // Length of a Zstandard frame magic number, in bytes. |
| | | 19 | | private const int ZstdFrameMagicLength = 4; |
| | | 20 | | |
| | | 21 | | /// <summary>Initializes a new instance of the <see cref="ZstandardStream" /> class by using the specified strea |
| | | 22 | | /// <param name="stream">The stream from which data to decompress is read.</param> |
| | | 23 | | /// <param name="decoder">The decoder instance to use for decompression. The stream will not dispose this decode |
| | | 24 | | /// <param name="leaveOpen"><see langword="true" /> to leave the stream open after the <see cref="ZstandardStrea |
| | | 25 | | /// <exception cref="ArgumentNullException"><paramref name="stream"/> is <see langword="null"/>.</exception> |
| | | 26 | | /// <exception cref="ArgumentException"><paramref name="stream"/> does not support reading.</exception> |
| | 0 | 27 | | public ZstandardStream(Stream stream, ZstandardDecoder decoder, bool leaveOpen = false) |
| | 0 | 28 | | { |
| | 0 | 29 | | ArgumentNullException.ThrowIfNull(decoder); |
| | | 30 | | |
| | 0 | 31 | | Init(stream, CompressionMode.Decompress); |
| | 0 | 32 | | _mode = CompressionMode.Decompress; |
| | 0 | 33 | | _leaveOpen = leaveOpen; |
| | | 34 | | |
| | 0 | 35 | | _decoder = decoder; |
| | 0 | 36 | | _encoderOwned = false; |
| | 0 | 37 | | } |
| | | 38 | | |
| | | 39 | | /// <summary>Initializes a new instance of the <see cref="ZstandardStream" /> class by using the specified strea |
| | | 40 | | /// <param name="stream">The stream from which data to decompress is read.</param> |
| | | 41 | | /// <param name="decompressionOptions">The options to use for Zstandard decompression.</param> |
| | | 42 | | /// <param name="leaveOpen"><see langword="true" /> to leave the stream open after the <see cref="ZstandardStrea |
| | | 43 | | /// <exception cref="ArgumentNullException"><paramref name="stream"/> or <paramref name="decompressionOptions"/> |
| | | 44 | | /// <exception cref="ArgumentException"><paramref name="stream"/> does not support reading.</exception> |
| | 0 | 45 | | public ZstandardStream(Stream stream, ZstandardDecompressionOptions decompressionOptions, bool leaveOpen = false |
| | 0 | 46 | | { |
| | 0 | 47 | | ArgumentNullException.ThrowIfNull(decompressionOptions); |
| | | 48 | | |
| | 0 | 49 | | Init(stream, CompressionMode.Decompress); |
| | 0 | 50 | | _mode = CompressionMode.Decompress; |
| | 0 | 51 | | _leaveOpen = leaveOpen; |
| | | 52 | | |
| | 0 | 53 | | _decoder = new ZstandardDecoder(decompressionOptions); |
| | 0 | 54 | | } |
| | | 55 | | |
| | | 56 | | // Decompresses buffered input for the current frame only. Returns true when there is a result for |
| | | 57 | | // the caller to act on (output was produced, the frame finished, or a zero-byte read should |
| | | 58 | | // return), and false when more input is needed to make progress on the current frame. Crossing a |
| | | 59 | | // frame boundary into the next concatenated frame is handled by Read/ReadAsync once this reports |
| | | 60 | | // OperationStatus.Done. |
| | | 61 | | private bool TryDecompress(Span<byte> destination, out int bytesWritten, out OperationStatus lastResult) |
| | 0 | 62 | | { |
| | 0 | 63 | | Debug.Assert(_decoder != null); |
| | | 64 | | |
| | 0 | 65 | | OperationStatus status = _decoder.Decompress(_buffer.ActiveSpan, destination, out int bytesConsumed, out byt |
| | 0 | 66 | | _buffer.Discard(bytesConsumed); |
| | 0 | 67 | | lastResult = status; |
| | | 68 | | |
| | 0 | 69 | | if (status == OperationStatus.InvalidData) |
| | 0 | 70 | | { |
| | 0 | 71 | | throw new InvalidDataException(SR.ZstandardStream_Decompress_InvalidData); |
| | | 72 | | } |
| | | 73 | | |
| | 0 | 74 | | if (status == OperationStatus.Done) |
| | 0 | 75 | | { |
| | | 76 | | // Reached the end of a frame. ZSTD_decompressStream reports end-of-frame, not end-of-stream: |
| | | 77 | | // a zstd stream may be frames concatenated back-to-back (RFC 8878 section 3), so Read/ReadAsync |
| | | 78 | | // decide whether another frame follows. This may be a zero-output frame (bytesWritten == 0). |
| | 0 | 79 | | return true; |
| | | 80 | | } |
| | | 81 | | |
| | 0 | 82 | | if (bytesWritten != 0) |
| | 0 | 83 | | { |
| | 0 | 84 | | return true; |
| | | 85 | | } |
| | | 86 | | |
| | 0 | 87 | | if (destination.IsEmpty) |
| | 0 | 88 | | { |
| | | 89 | | // The caller provided a zero-byte buffer. This is typically done in order to avoid allocating/renting |
| | | 90 | | // a buffer until data is known to be available. We don't have perfect knowledge here, as _decoder.Deco |
| | | 91 | | // will return DestinationTooSmall whether or not more data is required. As such, we assume that if the |
| | | 92 | | // any data in our input buffer, it would have been decompressible into at least one byte of output, and |
| | | 93 | | // otherwise we need to do a read on the underlying stream. This isn't perfect, because having input da |
| | | 94 | | // doesn't necessarily mean it'll decompress into at least one byte of output, but it's a reasonable app |
| | | 95 | | // for the 99% case. If it's wrong, it just means that a caller using zero-byte reads as a way to delay |
| | | 96 | | // getting a buffer to use for a subsequent call may end up getting one earlier than otherwise preferred |
| | 0 | 97 | | Debug.Assert(status == OperationStatus.DestinationTooSmall); |
| | 0 | 98 | | if (_buffer.ActiveLength != 0) |
| | 0 | 99 | | { |
| | 0 | 100 | | return true; |
| | | 101 | | } |
| | 0 | 102 | | } |
| | | 103 | | |
| | 0 | 104 | | Debug.Assert( |
| | 0 | 105 | | status == OperationStatus.NeedMoreData || |
| | 0 | 106 | | (status == OperationStatus.DestinationTooSmall && destination.IsEmpty && _buffer.ActiveLength == 0), $"{ |
| | | 107 | | |
| | 0 | 108 | | return false; |
| | 0 | 109 | | } |
| | | 110 | | |
| | | 111 | | /// <summary>Reads decompressed bytes from the underlying stream and places them in the specified array.</summar |
| | | 112 | | /// <param name="buffer">The byte array to contain the decompressed bytes.</param> |
| | | 113 | | /// <param name="offset">The byte offset in <paramref name="buffer" /> at which the read bytes will be placed.</ |
| | | 114 | | /// <param name="count">The maximum number of decompressed bytes to read.</param> |
| | | 115 | | /// <returns>The number of bytes that were read into the byte array.</returns> |
| | | 116 | | /// <exception cref="ArgumentNullException"><paramref name="buffer" /> is <see langword="null" />.</exception> |
| | | 117 | | /// <exception cref="InvalidOperationException">The <see cref="CompressionMode" /> value was <see cref="Compress |
| | | 118 | | /// <exception cref="ArgumentOutOfRangeException"><paramref name="offset" /> or <paramref name="count" /> is les |
| | | 119 | | /// <exception cref="ArgumentException">The <paramref name="buffer" /> length minus the index starting point is |
| | | 120 | | /// <exception cref="InvalidDataException">The data is in an invalid format.</exception> |
| | | 121 | | /// <exception cref="ObjectDisposedException">The stream is disposed.</exception> |
| | | 122 | | /// <exception cref="IOException">Failed to decompress data from the underlying stream.</exception> |
| | | 123 | | public override int Read(byte[] buffer, int offset, int count) |
| | 0 | 124 | | { |
| | 0 | 125 | | ValidateBufferArguments(buffer, offset, count); |
| | 0 | 126 | | return Read(new Span<byte>(buffer, offset, count)); |
| | 0 | 127 | | } |
| | | 128 | | |
| | | 129 | | /// <summary>Reads decompressed bytes from the underlying stream and places them in the specified span.</summary |
| | | 130 | | /// <param name="buffer">The span to contain the decompressed bytes.</param> |
| | | 131 | | /// <returns>The number of bytes that were read into the span.</returns> |
| | | 132 | | /// <exception cref="InvalidOperationException">The <see cref="CompressionMode" /> value was <see cref="Compress |
| | | 133 | | /// <exception cref="InvalidDataException">The data is in an invalid format.</exception> |
| | | 134 | | /// <exception cref="ObjectDisposedException">The stream is disposed.</exception> |
| | | 135 | | /// <exception cref="IOException">Failed to decompress data from the underlying stream.</exception> |
| | | 136 | | public override int Read(Span<byte> buffer) |
| | 0 | 137 | | { |
| | 0 | 138 | | if (_mode != CompressionMode.Decompress) |
| | 0 | 139 | | { |
| | 0 | 140 | | throw new InvalidOperationException(SR.CannotReadFromCompressionStream); |
| | | 141 | | } |
| | | 142 | | |
| | 0 | 143 | | EnsureNotDisposed(); |
| | 0 | 144 | | BeginRWOperation(); |
| | | 145 | | |
| | | 146 | | try |
| | 0 | 147 | | { |
| | 0 | 148 | | if (_endOfStream) |
| | 0 | 149 | | { |
| | | 150 | | // A previous read reached the end of the final frame (or rejected trailing data). The |
| | | 151 | | // boundary probe may have left the decoder non-resumable, so never re-enter the decode |
| | | 152 | | // loop; report end-of-stream to all subsequent reads. |
| | 0 | 153 | | return 0; |
| | | 154 | | } |
| | | 155 | | |
| | 0 | 156 | | while (true) |
| | 0 | 157 | | { |
| | | 158 | | int bytesWritten; |
| | | 159 | | OperationStatus lastResult; |
| | 0 | 160 | | while (!TryDecompress(buffer, out bytesWritten, out lastResult)) |
| | 0 | 161 | | { |
| | 0 | 162 | | _buffer.EnsureAvailableSpace(1); |
| | | 163 | | |
| | 0 | 164 | | int bytesRead = _stream.Read(_buffer.AvailableSpan); |
| | 0 | 165 | | if (bytesRead <= 0) |
| | 0 | 166 | | { |
| | | 167 | | // The underlying stream ended in the middle of a frame, so the data is truncated. |
| | | 168 | | // A clean end after a completed frame is reported as Done by TryDecompress and is |
| | | 169 | | // resolved by the frame-boundary logic below, not here. |
| | 0 | 170 | | if (_nonEmptyInput && !buffer.IsEmpty) |
| | 0 | 171 | | { |
| | 0 | 172 | | ThrowTruncatedInvalidData(); |
| | | 173 | | } |
| | | 174 | | |
| | 0 | 175 | | return 0; |
| | | 176 | | } |
| | | 177 | | |
| | 0 | 178 | | _nonEmptyInput = true; |
| | | 179 | | |
| | 0 | 180 | | if (bytesRead > _buffer.AvailableLength) |
| | 0 | 181 | | { |
| | 0 | 182 | | ThrowInvalidStream(); |
| | | 183 | | } |
| | | 184 | | |
| | 0 | 185 | | _buffer.Commit(bytesRead); |
| | 0 | 186 | | } |
| | | 187 | | |
| | 0 | 188 | | if (lastResult != OperationStatus.Done || bytesWritten != 0) |
| | 0 | 189 | | { |
| | | 190 | | // Output to hand back, or not at a finished-frame boundary: return to the caller. |
| | 0 | 191 | | return bytesWritten; |
| | | 192 | | } |
| | | 193 | | |
| | | 194 | | // A frame finished with no pending output. A zstd stream may be frames concatenated |
| | | 195 | | // back-to-back (RFC 8878 section 3), so decide whether another frame follows before |
| | | 196 | | // reporting end-of-stream. async: false completes synchronously (it only ever takes the |
| | | 197 | | // synchronous read path). |
| | 0 | 198 | | ValueTask<bool> advanceTask = AdvanceToNextFrame(async: false, cancellationToken: default); |
| | 0 | 199 | | Debug.Assert(advanceTask.IsCompleted, "AdvanceToNextFrame should complete synchronously when async: |
| | 0 | 200 | | if (!advanceTask.GetAwaiter().GetResult()) |
| | 0 | 201 | | { |
| | 0 | 202 | | return bytesWritten; |
| | | 203 | | } |
| | 0 | 204 | | } |
| | | 205 | | } |
| | | 206 | | finally |
| | 0 | 207 | | { |
| | 0 | 208 | | EndRWOperation(); |
| | 0 | 209 | | } |
| | 0 | 210 | | } |
| | | 211 | | |
| | | 212 | | // Called after TryDecompress reports OperationStatus.Done with no pending output (a finished frame). |
| | | 213 | | // Decides whether another concatenated frame follows by reading up to a frame magic and feeding just |
| | | 214 | | // those bytes to the decoder: a valid magic is accepted (NeedMoreData) so decoding continues, while |
| | | 215 | | // bytes that are not a frame magic identify trailing data after the final frame. Returns true (decoder |
| | | 216 | | // reset and ready) so the caller loops to decode the next frame, or false (stream complete; _endOfStream |
| | | 217 | | // is set and a seekable base stream is rewound to the end of the compressed data) so the caller returns. |
| | | 218 | | // Shared by Read (async: false) and ReadAsync (async: true). |
| | | 219 | | private async ValueTask<bool> AdvanceToNextFrame(bool async, CancellationToken cancellationToken) |
| | 0 | 220 | | { |
| | 0 | 221 | | Debug.Assert(_decoder != null); |
| | | 222 | | |
| | 0 | 223 | | if (_buffer.ActiveLength < ZstdFrameMagicLength) |
| | 0 | 224 | | { |
| | | 225 | | // Not enough buffered to tell a split next-frame magic from end-of-stream; read just enough |
| | | 226 | | // to complete the magic. Limiting the read to exactly the missing bytes (rather than filling |
| | | 227 | | // the available buffer) avoids consuming and hiding trailing bytes past the magic on a |
| | | 228 | | // non-seekable stream, where they can't be rewound; any following frame's body is read by the |
| | | 229 | | // Read/ReadAsync loop afterwards. |
| | 0 | 230 | | int needed = ZstdFrameMagicLength - _buffer.ActiveLength; |
| | 0 | 231 | | _buffer.EnsureAvailableSpace(needed); |
| | 0 | 232 | | int peeked = async |
| | 0 | 233 | | ? await _stream.ReadAtLeastAsync(_buffer.AvailableMemory.Slice(0, needed), needed, throwOnEndOfStrea |
| | 0 | 234 | | : _stream.ReadAtLeast(_buffer.AvailableSpan.Slice(0, needed), needed, throwOnEndOfStream: false); |
| | 0 | 235 | | if (peeked > 0) |
| | 0 | 236 | | { |
| | 0 | 237 | | _nonEmptyInput = true; |
| | 0 | 238 | | _buffer.Commit(peeked); |
| | 0 | 239 | | } |
| | 0 | 240 | | } |
| | | 241 | | |
| | 0 | 242 | | if (_buffer.ActiveLength >= ZstdFrameMagicLength) |
| | 0 | 243 | | { |
| | | 244 | | // Determine whether another concatenated frame follows by feeding the decoder exactly the next |
| | | 245 | | // frame magic number. The decoder validates the magic against both standard and skippable |
| | | 246 | | // frames: a valid magic leaves it asking for more input (NeedMoreData), so decoding continues, |
| | | 247 | | // while bytes that are not a frame magic produce InvalidData, identifying trailing data after |
| | | 248 | | // the final frame. Feeding only the magic (not the whole buffer) means a frame whose magic is |
| | | 249 | | // valid but whose body is corrupt is not mistaken for trailing data here: the magic is accepted |
| | | 250 | | // and the corrupt body is rejected by the subsequent decode in the Read/ReadAsync loop. |
| | 0 | 251 | | _decoder.Reset(); |
| | | 252 | | |
| | | 253 | | // The magic alone never decodes into output, so the decoder needs no real output space; a single |
| | | 254 | | // scratch byte borrowed from the buffer's free region (which the decoder won't write to) satisfies |
| | | 255 | | // the non-empty-destination requirement. A Span local / stackalloc can't be used here because this |
| | | 256 | | // method is async. |
| | 0 | 257 | | _buffer.EnsureAvailableSpace(1); |
| | 0 | 258 | | if (_decoder.Decompress(_buffer.ActiveSpan.Slice(0, ZstdFrameMagicLength), _buffer.AvailableSpan.Slice(0 |
| | 0 | 259 | | { |
| | | 260 | | // A valid magic; the decoder has taken the magic bytes into its session to continue decoding |
| | | 261 | | // the rest of the frame. Drop them from the buffer and keep decoding. |
| | 0 | 262 | | _buffer.Discard(bytesConsumed); |
| | 0 | 263 | | return true; |
| | | 264 | | } |
| | | 265 | | |
| | | 266 | | // Not a frame: leave the magic bytes buffered so they are included in the trailing-data rewind |
| | | 267 | | // below (on a non-seekable stream they simply remain unconsumed). |
| | 0 | 268 | | } |
| | | 269 | | |
| | | 270 | | // Trailing non-zstd data or end of input after the final frame: the stream is complete. Mark the |
| | | 271 | | // stream ended so subsequent reads short-circuit to 0 without re-entering the (now non-resumable) |
| | | 272 | | // decoder, and leave any trailing bytes on a seekable base stream by rewinding to the end of the |
| | | 273 | | // compressed data, mirroring how DeflateStream handles data after the last gzip member. |
| | 0 | 274 | | _endOfStream = true; |
| | 0 | 275 | | if (_stream.CanSeek) |
| | 0 | 276 | | { |
| | 0 | 277 | | TryRewindStream(_stream); |
| | 0 | 278 | | } |
| | | 279 | | |
| | 0 | 280 | | return false; |
| | 0 | 281 | | } |
| | | 282 | | |
| | | 283 | | /// <summary>Asynchronously reads decompressed bytes from the underlying stream and places them in the specified |
| | | 284 | | /// <param name="buffer">The byte array to contain the decompressed bytes.</param> |
| | | 285 | | /// <param name="offset">The byte offset in <paramref name="buffer" /> at which the read bytes will be placed.</ |
| | | 286 | | /// <param name="count">The maximum number of decompressed bytes to read.</param> |
| | | 287 | | /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> |
| | | 288 | | /// <returns>A task that represents the asynchronous read operation, which wraps the number of bytes read from t |
| | | 289 | | /// <exception cref="ArgumentNullException"><paramref name="buffer" /> is <see langword="null" />.</exception> |
| | | 290 | | /// <exception cref="ArgumentOutOfRangeException"><paramref name="offset" /> or <paramref name="count" /> is les |
| | | 291 | | /// <exception cref="ArgumentException">The <paramref name="buffer" /> length minus the index starting point is |
| | | 292 | | /// <exception cref="InvalidOperationException">The <see cref="CompressionMode" /> value was <see cref="Compress |
| | | 293 | | /// <exception cref="InvalidDataException">The data is in an invalid format.</exception> |
| | | 294 | | /// <exception cref="ObjectDisposedException">The stream is disposed.</exception> |
| | | 295 | | /// <exception cref="IOException">Failed to decompress data from the underlying stream.</exception> |
| | | 296 | | public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) |
| | 0 | 297 | | { |
| | 0 | 298 | | ValidateBufferArguments(buffer, offset, count); |
| | 0 | 299 | | return ReadAsync(new Memory<byte>(buffer, offset, count), cancellationToken).AsTask(); |
| | 0 | 300 | | } |
| | | 301 | | |
| | | 302 | | /// <summary>Asynchronously reads decompressed bytes from the underlying stream and places them in the specified |
| | | 303 | | /// <param name="buffer">The memory to contain the decompressed bytes.</param> |
| | | 304 | | /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> |
| | | 305 | | /// <returns>A task that represents the asynchronous read operation, which wraps the number of bytes read from t |
| | | 306 | | /// <exception cref="InvalidOperationException">The <see cref="CompressionMode" /> value was <see cref="Compress |
| | | 307 | | /// <exception cref="InvalidDataException">The data is in an invalid format.</exception> |
| | | 308 | | /// <exception cref="ObjectDisposedException">The stream is disposed.</exception> |
| | | 309 | | /// <exception cref="IOException">Failed to decompress data from the underlying stream.</exception> |
| | | 310 | | public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = defaul |
| | 0 | 311 | | { |
| | 0 | 312 | | if (_mode != CompressionMode.Decompress) |
| | 0 | 313 | | { |
| | 0 | 314 | | throw new InvalidOperationException(SR.CannotReadFromCompressionStream); |
| | | 315 | | } |
| | | 316 | | |
| | 0 | 317 | | EnsureNotDisposed(); |
| | 0 | 318 | | BeginRWOperation(); |
| | | 319 | | |
| | | 320 | | try |
| | 0 | 321 | | { |
| | 0 | 322 | | if (_endOfStream) |
| | 0 | 323 | | { |
| | | 324 | | // A previous read reached the end of the final frame (or rejected trailing data). The |
| | | 325 | | // boundary probe may have left the decoder non-resumable, so never re-enter the decode |
| | | 326 | | // loop; report end-of-stream to all subsequent reads. |
| | 0 | 327 | | return 0; |
| | | 328 | | } |
| | | 329 | | |
| | 0 | 330 | | while (true) |
| | 0 | 331 | | { |
| | | 332 | | int bytesWritten; |
| | | 333 | | OperationStatus lastResult; |
| | 0 | 334 | | while (!TryDecompress(buffer.Span, out bytesWritten, out lastResult)) |
| | 0 | 335 | | { |
| | 0 | 336 | | _buffer.EnsureAvailableSpace(1); |
| | | 337 | | |
| | 0 | 338 | | int bytesRead = await _stream.ReadAsync(_buffer.AvailableMemory, cancellationToken).ConfigureAwa |
| | 0 | 339 | | if (bytesRead <= 0) |
| | 0 | 340 | | { |
| | | 341 | | // The underlying stream ended in the middle of a frame, so the data is truncated. |
| | | 342 | | // A clean end after a completed frame is reported as Done by TryDecompress and is |
| | | 343 | | // resolved by the frame-boundary logic below, not here. |
| | 0 | 344 | | if (_nonEmptyInput && !buffer.IsEmpty) |
| | 0 | 345 | | { |
| | 0 | 346 | | ThrowTruncatedInvalidData(); |
| | | 347 | | } |
| | | 348 | | |
| | 0 | 349 | | return 0; |
| | | 350 | | } |
| | | 351 | | |
| | 0 | 352 | | _nonEmptyInput = true; |
| | | 353 | | |
| | 0 | 354 | | if (bytesRead > _buffer.AvailableLength) |
| | 0 | 355 | | { |
| | 0 | 356 | | ThrowInvalidStream(); |
| | | 357 | | } |
| | | 358 | | |
| | 0 | 359 | | _buffer.Commit(bytesRead); |
| | 0 | 360 | | } |
| | | 361 | | |
| | 0 | 362 | | if (lastResult != OperationStatus.Done || bytesWritten != 0) |
| | 0 | 363 | | { |
| | | 364 | | // Output to hand back, or not at a finished-frame boundary: return to the caller. |
| | 0 | 365 | | return bytesWritten; |
| | | 366 | | } |
| | | 367 | | |
| | | 368 | | // A frame finished with no pending output. A zstd stream may be frames concatenated |
| | | 369 | | // back-to-back (RFC 8878 section 3), so decide whether another frame follows before |
| | | 370 | | // reporting end-of-stream. |
| | 0 | 371 | | if (!await AdvanceToNextFrame(async: true, cancellationToken: cancellationToken).ConfigureAwait(fals |
| | 0 | 372 | | { |
| | 0 | 373 | | return bytesWritten; |
| | | 374 | | } |
| | 0 | 375 | | } |
| | | 376 | | } |
| | | 377 | | finally |
| | 0 | 378 | | { |
| | 0 | 379 | | EndRWOperation(); |
| | 0 | 380 | | } |
| | 0 | 381 | | } |
| | | 382 | | |
| | | 383 | | /// <summary>Begins an asynchronous read operation.</summary> |
| | | 384 | | /// <param name="buffer">The buffer to read the data into.</param> |
| | | 385 | | /// <param name="offset">The byte offset in <paramref name="buffer"/> at which to begin writing data read from t |
| | | 386 | | /// <param name="count">The maximum number of bytes to read.</param> |
| | | 387 | | /// <param name="callback">An optional asynchronous callback, to be called when the read is complete.</param> |
| | | 388 | | /// <param name="state">A user-provided object that distinguishes this particular asynchronous read request from |
| | | 389 | | /// <returns>An object that represents the asynchronous read, which could still be pending.</returns> |
| | | 390 | | /// <exception cref="ArgumentNullException"><paramref name="buffer" /> is <see langword="null" />.</exception> |
| | | 391 | | /// <exception cref="ArgumentOutOfRangeException"><paramref name="offset" /> or <paramref name="count" /> is les |
| | | 392 | | /// <exception cref="ArgumentException">The <paramref name="buffer" /> length minus the index starting point is |
| | | 393 | | /// <exception cref="InvalidOperationException">The <see cref="CompressionMode" /> value was <see cref="Compress |
| | | 394 | | /// <exception cref="InvalidDataException">The data is in an invalid format.</exception> |
| | | 395 | | /// <exception cref="ObjectDisposedException">The stream is disposed.</exception> |
| | | 396 | | /// <exception cref="IOException">Failed to decompress data from the underlying stream.</exception> |
| | | 397 | | public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? st |
| | 0 | 398 | | { |
| | 0 | 399 | | return TaskToAsyncResult.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), callback, state); |
| | 0 | 400 | | } |
| | | 401 | | |
| | | 402 | | /// <summary>Waits for the pending asynchronous read to complete.</summary> |
| | | 403 | | /// <param name="asyncResult">The reference to the pending asynchronous request to finish.</param> |
| | | 404 | | /// <returns>The number of bytes read from the stream, between zero (0) and the number of bytes you requested. S |
| | | 405 | | public override int EndRead(IAsyncResult asyncResult) |
| | 0 | 406 | | { |
| | 0 | 407 | | return TaskToAsyncResult.End<int>(asyncResult); |
| | 0 | 408 | | } |
| | | 409 | | |
| | | 410 | | /// <summary>Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 |
| | | 411 | | /// <returns>The unsigned byte cast to an <see cref="int"/>, or -1 if at the end of the stream.</returns> |
| | | 412 | | /// <exception cref="InvalidOperationException">The <see cref="CompressionMode" /> value was <see cref="Compress |
| | | 413 | | /// <exception cref="InvalidDataException">The data is in an invalid format.</exception> |
| | | 414 | | /// <exception cref="ObjectDisposedException">The stream is disposed.</exception> |
| | | 415 | | /// <exception cref="IOException">Failed to decompress data from the underlying stream.</exception> |
| | | 416 | | public override int ReadByte() |
| | 0 | 417 | | { |
| | 0 | 418 | | Span<byte> singleByte = [0]; |
| | 0 | 419 | | int bytesRead = Read(singleByte); |
| | 0 | 420 | | return bytesRead > 0 ? singleByte[0] : -1; |
| | 0 | 421 | | } |
| | | 422 | | |
| | | 423 | | /// <summary> |
| | | 424 | | /// Rewinds the underlying stream to the exact end of the compressed data if there are unconsumed bytes. |
| | | 425 | | /// This is called when decompression finishes to reset the stream position. |
| | | 426 | | /// </summary> |
| | | 427 | | private void TryRewindStream(Stream stream) |
| | 0 | 428 | | { |
| | 0 | 429 | | Debug.Assert(stream != null); |
| | 0 | 430 | | Debug.Assert(_mode == CompressionMode.Decompress); |
| | 0 | 431 | | Debug.Assert(stream.CanSeek); |
| | | 432 | | |
| | | 433 | | // Check if there are unconsumed bytes in the buffer |
| | 0 | 434 | | int unconsumedBytes = _buffer.ActiveLength; |
| | 0 | 435 | | if (unconsumedBytes > 0) |
| | 0 | 436 | | { |
| | | 437 | | // Rewind the stream to the exact end of the compressed data |
| | 0 | 438 | | stream.Seek(-unconsumedBytes, SeekOrigin.Current); |
| | 0 | 439 | | _buffer.Discard(unconsumedBytes); |
| | 0 | 440 | | } |
| | 0 | 441 | | } |
| | | 442 | | |
| | | 443 | | [DoesNotReturn] |
| | | 444 | | private static void ThrowInvalidStream() => |
| | | 445 | | // The stream is either malicious or poorly implemented and returned a number of |
| | | 446 | | // bytes larger than the buffer supplied to it. |
| | 0 | 447 | | throw new InvalidDataException(SR.ZstandardStream_Decompress_InvalidStream); |
| | | 448 | | |
| | | 449 | | [DoesNotReturn] |
| | | 450 | | private static void ThrowTruncatedInvalidData() => |
| | 0 | 451 | | throw new InvalidDataException(SR.ZstandardStream_Decompress_TruncatedData); |
| | | 452 | | } |
| | | 453 | | } |