| | | 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.Runtime.InteropServices; |
| | | 8 | | using System.Threading; |
| | | 9 | | using System.Threading.Tasks; |
| | | 10 | | using static System.IO.Compression.ZLibNative; |
| | | 11 | | |
| | | 12 | | namespace System.IO.Compression |
| | | 13 | | { |
| | | 14 | | public partial class DeflateStream : Stream |
| | | 15 | | { |
| | | 16 | | private const int DefaultBufferSize = 8192; |
| | | 17 | | |
| | | 18 | | private Stream _stream; |
| | | 19 | | private CompressionMode _mode; |
| | | 20 | | private bool _leaveOpen; |
| | | 21 | | private Inflater? _inflater; |
| | | 22 | | private Deflater? _deflater; |
| | | 23 | | private byte[]? _buffer; |
| | | 24 | | private volatile bool _activeAsyncOperation; |
| | | 25 | | private volatile bool _decompressionFinished; |
| | | 26 | | |
| | 0 | 27 | | internal DeflateStream(Stream stream, CompressionMode mode, long uncompressedSize) : this(stream, mode, leaveOpe |
| | 0 | 28 | | { |
| | 0 | 29 | | } |
| | | 30 | | |
| | 0 | 31 | | public DeflateStream(Stream stream, CompressionMode mode) : this(stream, mode, leaveOpen: false) |
| | 0 | 32 | | { |
| | 0 | 33 | | } |
| | | 34 | | |
| | 0 | 35 | | public DeflateStream(Stream stream, CompressionMode mode, bool leaveOpen) : this(stream, mode, leaveOpen, ZLibNa |
| | 0 | 36 | | { |
| | 0 | 37 | | } |
| | | 38 | | |
| | | 39 | | // Implies mode = Compress |
| | 0 | 40 | | public DeflateStream(Stream stream, CompressionLevel compressionLevel) : this(stream, compressionLevel, leaveOpe |
| | 0 | 41 | | { |
| | 0 | 42 | | } |
| | | 43 | | |
| | | 44 | | // Implies mode = Compress |
| | 0 | 45 | | public DeflateStream(Stream stream, CompressionLevel compressionLevel, bool leaveOpen) : this(stream, compressio |
| | 0 | 46 | | { |
| | 0 | 47 | | } |
| | | 48 | | |
| | | 49 | | /// <summary> |
| | | 50 | | /// Initializes a new instance of the <see cref="DeflateStream"/> class by using the specified stream, compressi |
| | | 51 | | /// </summary> |
| | | 52 | | /// <param name="stream">The stream to which compressed data is written.</param> |
| | | 53 | | /// <param name="compressionOptions">The options for fine tuning the compression stream.</param> |
| | | 54 | | /// <param name="leaveOpen"><see langword="true" /> to leave the stream object open after disposing the <see cre |
| | | 55 | | /// <exception cref="ArgumentNullException"><paramref name="stream"/> or <paramref name="compressionOptions"/> i |
| | 0 | 56 | | public DeflateStream(Stream stream, ZLibCompressionOptions compressionOptions, bool leaveOpen = false) |
| | 0 | 57 | | { |
| | 0 | 58 | | ArgumentNullException.ThrowIfNull(stream); |
| | 0 | 59 | | ArgumentNullException.ThrowIfNull(compressionOptions); |
| | | 60 | | |
| | 0 | 61 | | int windowBits = CompressionFormatHelper.ResolveWindowBits(compressionOptions.WindowLog2, CompressionFormat. |
| | | 62 | | |
| | 0 | 63 | | InitializeDeflater(stream, (ZLibNative.CompressionLevel)compressionOptions.CompressionLevel, (CompressionStr |
| | 0 | 64 | | } |
| | | 65 | | |
| | 0 | 66 | | internal DeflateStream(Stream stream, ZLibCompressionOptions compressionOptions, bool leaveOpen, int windowBits) |
| | 0 | 67 | | { |
| | 0 | 68 | | ArgumentNullException.ThrowIfNull(stream); |
| | 0 | 69 | | ArgumentNullException.ThrowIfNull(compressionOptions); |
| | | 70 | | |
| | 0 | 71 | | InitializeDeflater(stream, (ZLibNative.CompressionLevel)compressionOptions.CompressionLevel, (CompressionStr |
| | 0 | 72 | | } |
| | | 73 | | |
| | | 74 | | /// <summary> |
| | | 75 | | /// Internal constructor to check stream validity and call the correct initialization function depending on |
| | | 76 | | /// the value of the CompressionMode given. |
| | | 77 | | /// </summary> |
| | 0 | 78 | | internal DeflateStream(Stream stream, CompressionMode mode, bool leaveOpen, int windowBits, long uncompressedSiz |
| | 0 | 79 | | { |
| | 0 | 80 | | ArgumentNullException.ThrowIfNull(stream); |
| | | 81 | | |
| | 0 | 82 | | switch (mode) |
| | | 83 | | { |
| | | 84 | | case CompressionMode.Decompress: |
| | 0 | 85 | | if (!stream.CanRead) |
| | 0 | 86 | | throw new ArgumentException(SR.NotSupported_UnreadableStream, nameof(stream)); |
| | | 87 | | |
| | 0 | 88 | | _inflater = Inflater.CreateInflater(windowBits, uncompressedSize); |
| | 0 | 89 | | _stream = stream; |
| | 0 | 90 | | _mode = CompressionMode.Decompress; |
| | 0 | 91 | | _leaveOpen = leaveOpen; |
| | 0 | 92 | | break; |
| | | 93 | | |
| | | 94 | | case CompressionMode.Compress: |
| | 0 | 95 | | InitializeDeflater(stream, ZLibNative.CompressionLevel.DefaultCompression, CompressionStrategy.Defau |
| | 0 | 96 | | break; |
| | | 97 | | |
| | | 98 | | default: |
| | 0 | 99 | | throw new ArgumentException(SR.ArgumentOutOfRange_Enum, nameof(mode)); |
| | | 100 | | } |
| | 0 | 101 | | } |
| | | 102 | | |
| | | 103 | | /// <summary> |
| | | 104 | | /// Internal constructor to specify the compressionLevel as well as the windowBits |
| | | 105 | | /// </summary> |
| | 0 | 106 | | internal DeflateStream(Stream stream, CompressionLevel compressionLevel, bool leaveOpen, int windowBits) |
| | 0 | 107 | | { |
| | 0 | 108 | | ArgumentNullException.ThrowIfNull(stream); |
| | | 109 | | |
| | 0 | 110 | | InitializeDeflater(stream, GetZLibNativeCompressionLevel(compressionLevel), CompressionStrategy.DefaultStrat |
| | 0 | 111 | | } |
| | | 112 | | |
| | | 113 | | /// <summary> |
| | | 114 | | /// Sets up this DeflateStream to be used for Zlib Deflation/Compression |
| | | 115 | | /// </summary> |
| | | 116 | | [MemberNotNull(nameof(_stream))] |
| | | 117 | | internal void InitializeDeflater(Stream stream, ZLibNative.CompressionLevel compressionLevel, CompressionStrateg |
| | 0 | 118 | | { |
| | 0 | 119 | | Debug.Assert(stream != null); |
| | 0 | 120 | | if (!stream.CanWrite) |
| | 0 | 121 | | throw new ArgumentException(SR.NotSupported_UnwritableStream, nameof(stream)); |
| | | 122 | | |
| | 0 | 123 | | _deflater = Deflater.CreateDeflater(compressionLevel, strategy, windowBits, GetMemLevel(compressionLevel)); |
| | | 124 | | |
| | 0 | 125 | | _stream = stream; |
| | 0 | 126 | | _mode = CompressionMode.Compress; |
| | 0 | 127 | | _leaveOpen = leaveOpen; |
| | 0 | 128 | | InitializeBuffer(); |
| | 0 | 129 | | } |
| | | 130 | | |
| | | 131 | | private static ZLibNative.CompressionLevel GetZLibNativeCompressionLevel(CompressionLevel compressionLevel) => |
| | 0 | 132 | | compressionLevel switch |
| | 0 | 133 | | { |
| | 0 | 134 | | CompressionLevel.Optimal => ZLibNative.CompressionLevel.DefaultCompression, |
| | 0 | 135 | | CompressionLevel.Fastest => ZLibNative.CompressionLevel.BestSpeed, |
| | 0 | 136 | | CompressionLevel.NoCompression => ZLibNative.CompressionLevel.NoCompression, |
| | 0 | 137 | | CompressionLevel.SmallestSize => ZLibNative.CompressionLevel.BestCompression, |
| | 0 | 138 | | _ => throw new ArgumentOutOfRangeException(nameof(compressionLevel)), |
| | 0 | 139 | | }; |
| | | 140 | | |
| | | 141 | | private static int GetMemLevel(ZLibNative.CompressionLevel level) => |
| | 0 | 142 | | level == ZLibNative.CompressionLevel.NoCompression ? |
| | 0 | 143 | | Deflate_NoCompressionMemLevel : |
| | 0 | 144 | | Deflate_DefaultMemLevel; |
| | | 145 | | |
| | | 146 | | [MemberNotNull(nameof(_buffer))] |
| | | 147 | | private void InitializeBuffer() |
| | 0 | 148 | | { |
| | 0 | 149 | | Debug.Assert(_buffer == null); |
| | 0 | 150 | | _buffer = ArrayPool<byte>.Shared.Rent(DefaultBufferSize); |
| | 0 | 151 | | } |
| | | 152 | | |
| | | 153 | | [MemberNotNull(nameof(_buffer))] |
| | | 154 | | private void EnsureBufferInitialized() |
| | 0 | 155 | | { |
| | 0 | 156 | | if (_buffer == null) |
| | 0 | 157 | | { |
| | 0 | 158 | | InitializeBuffer(); |
| | 0 | 159 | | } |
| | 0 | 160 | | } |
| | | 161 | | |
| | | 162 | | public Stream BaseStream |
| | | 163 | | { |
| | | 164 | | get |
| | 0 | 165 | | { |
| | 0 | 166 | | EnsureNotDisposed(); |
| | 0 | 167 | | return _stream; |
| | 0 | 168 | | } |
| | | 169 | | } |
| | | 170 | | |
| | | 171 | | public override bool CanRead |
| | | 172 | | { |
| | | 173 | | get |
| | 0 | 174 | | { |
| | 0 | 175 | | if (_stream == null) |
| | 0 | 176 | | { |
| | 0 | 177 | | return false; |
| | | 178 | | } |
| | | 179 | | |
| | 0 | 180 | | return (_mode == CompressionMode.Decompress && _stream.CanRead); |
| | 0 | 181 | | } |
| | | 182 | | } |
| | | 183 | | |
| | | 184 | | public override bool CanWrite |
| | | 185 | | { |
| | | 186 | | get |
| | 0 | 187 | | { |
| | 0 | 188 | | if (_stream == null) |
| | 0 | 189 | | { |
| | 0 | 190 | | return false; |
| | | 191 | | } |
| | | 192 | | |
| | 0 | 193 | | return (_mode == CompressionMode.Compress && _stream.CanWrite); |
| | 0 | 194 | | } |
| | | 195 | | } |
| | | 196 | | |
| | 0 | 197 | | public override bool CanSeek => false; |
| | | 198 | | |
| | | 199 | | public override long Length |
| | | 200 | | { |
| | 0 | 201 | | get { throw new NotSupportedException(SR.NotSupported); } |
| | | 202 | | } |
| | | 203 | | |
| | | 204 | | public override long Position |
| | | 205 | | { |
| | 0 | 206 | | get { throw new NotSupportedException(SR.NotSupported); } |
| | 0 | 207 | | set { throw new NotSupportedException(SR.NotSupported); } |
| | | 208 | | } |
| | | 209 | | |
| | | 210 | | public override void Flush() |
| | 0 | 211 | | { |
| | 0 | 212 | | EnsureNotDisposed(); |
| | 0 | 213 | | if (_mode == CompressionMode.Compress) |
| | 0 | 214 | | FlushBuffers(); |
| | 0 | 215 | | } |
| | | 216 | | |
| | | 217 | | public override Task FlushAsync(CancellationToken cancellationToken) |
| | 0 | 218 | | { |
| | 0 | 219 | | EnsureNoActiveAsyncOperation(); |
| | 0 | 220 | | EnsureNotDisposed(); |
| | | 221 | | |
| | 0 | 222 | | if (cancellationToken.IsCancellationRequested) |
| | 0 | 223 | | return Task.FromCanceled(cancellationToken); |
| | | 224 | | |
| | 0 | 225 | | return _mode != CompressionMode.Compress ? |
| | 0 | 226 | | Task.CompletedTask : |
| | 0 | 227 | | Core(cancellationToken); |
| | | 228 | | |
| | | 229 | | async Task Core(CancellationToken cancellationToken) |
| | 0 | 230 | | { |
| | 0 | 231 | | AsyncOperationStarting(); |
| | | 232 | | try |
| | 0 | 233 | | { |
| | 0 | 234 | | Debug.Assert(_deflater != null && _buffer != null); |
| | | 235 | | |
| | | 236 | | // Compress any bytes left: |
| | 0 | 237 | | await WriteDeflaterOutputAsync(cancellationToken).ConfigureAwait(false); |
| | | 238 | | |
| | | 239 | | // Pull out any bytes left inside deflater: |
| | | 240 | | bool flushSuccessful; |
| | | 241 | | do |
| | 0 | 242 | | { |
| | | 243 | | int compressedBytes; |
| | 0 | 244 | | flushSuccessful = _deflater.Flush(_buffer, out compressedBytes); |
| | 0 | 245 | | if (flushSuccessful) |
| | 0 | 246 | | { |
| | 0 | 247 | | await _stream.WriteAsync(new ReadOnlyMemory<byte>(_buffer, 0, compressedBytes), cancellation |
| | 0 | 248 | | } |
| | 0 | 249 | | Debug.Assert(flushSuccessful == (compressedBytes > 0)); |
| | 0 | 250 | | } while (flushSuccessful); |
| | | 251 | | |
| | | 252 | | // Always flush on the underlying stream |
| | 0 | 253 | | await _stream.FlushAsync(cancellationToken).ConfigureAwait(false); |
| | 0 | 254 | | } |
| | | 255 | | finally |
| | 0 | 256 | | { |
| | 0 | 257 | | AsyncOperationCompleting(); |
| | 0 | 258 | | } |
| | 0 | 259 | | } |
| | 0 | 260 | | } |
| | | 261 | | |
| | | 262 | | public override long Seek(long offset, SeekOrigin origin) |
| | 0 | 263 | | { |
| | 0 | 264 | | throw new NotSupportedException(SR.NotSupported); |
| | | 265 | | } |
| | | 266 | | |
| | | 267 | | public override void SetLength(long value) |
| | 0 | 268 | | { |
| | 0 | 269 | | throw new NotSupportedException(SR.NotSupported); |
| | | 270 | | } |
| | | 271 | | |
| | | 272 | | public override int ReadByte() |
| | 0 | 273 | | { |
| | 0 | 274 | | EnsureDecompressionMode(); |
| | 0 | 275 | | EnsureNotDisposed(); |
| | | 276 | | |
| | | 277 | | // Try to read a single byte from zlib without allocating an array, pinning an array, etc. |
| | | 278 | | // If zlib doesn't have any data, fall back to the base stream implementation, which will do that. |
| | | 279 | | byte b; |
| | 0 | 280 | | Debug.Assert(_inflater != null); |
| | 0 | 281 | | return _inflater.Inflate(out b) ? b : base.ReadByte(); |
| | 0 | 282 | | } |
| | | 283 | | |
| | | 284 | | public override int Read(byte[] buffer, int offset, int count) |
| | 0 | 285 | | { |
| | 0 | 286 | | ValidateBufferArguments(buffer, offset, count); |
| | 0 | 287 | | return ReadCore(new Span<byte>(buffer, offset, count)); |
| | 0 | 288 | | } |
| | | 289 | | |
| | | 290 | | public override int Read(Span<byte> buffer) |
| | 0 | 291 | | { |
| | 0 | 292 | | if (GetType() != typeof(DeflateStream)) |
| | 0 | 293 | | { |
| | | 294 | | // DeflateStream is not sealed, and a derived type may have overridden Read(byte[], int, int) prior |
| | | 295 | | // to this Read(Span<byte>) overload being introduced. In that case, this Read(Span<byte>) overload |
| | | 296 | | // should use the behavior of Read(byte[],int,int) overload. |
| | 0 | 297 | | return base.Read(buffer); |
| | | 298 | | } |
| | | 299 | | else |
| | 0 | 300 | | { |
| | 0 | 301 | | return ReadCore(buffer); |
| | | 302 | | } |
| | 0 | 303 | | } |
| | | 304 | | |
| | | 305 | | internal int ReadCore(Span<byte> buffer) |
| | 0 | 306 | | { |
| | 0 | 307 | | EnsureDecompressionMode(); |
| | 0 | 308 | | EnsureNotDisposed(); |
| | 0 | 309 | | EnsureBufferInitialized(); |
| | 0 | 310 | | Debug.Assert(_inflater != null); |
| | | 311 | | |
| | | 312 | | int bytesRead; |
| | 0 | 313 | | while (true) |
| | 0 | 314 | | { |
| | | 315 | | // Try to decompress any data from the inflater into the caller's buffer. |
| | | 316 | | // If we're able to decompress any bytes, or if decompression is completed, we're done. |
| | 0 | 317 | | bytesRead = _inflater.Inflate(buffer); |
| | 0 | 318 | | if (bytesRead != 0 || InflatorIsFinished) |
| | 0 | 319 | | { |
| | 0 | 320 | | break; |
| | | 321 | | } |
| | | 322 | | |
| | | 323 | | // We were unable to decompress any data. If the inflater needs additional input |
| | | 324 | | // data to proceed, read some to populate it. |
| | 0 | 325 | | if (_inflater.NeedsInput()) |
| | 0 | 326 | | { |
| | 0 | 327 | | int n = _stream.Read(_buffer, 0, _buffer.Length); |
| | 0 | 328 | | if (n <= 0) |
| | 0 | 329 | | { |
| | | 330 | | // - Inflater didn't return any data although a non-empty output buffer was passed by the caller |
| | | 331 | | // - More input is needed but there is no more input available. |
| | | 332 | | // - Inflation is not finished yet. |
| | | 333 | | // - Provided input wasn't completely empty |
| | | 334 | | // In such case, we are dealing with a truncated input stream. |
| | 0 | 335 | | if (s_useStrictValidation && !buffer.IsEmpty && !_inflater.Finished() && _inflater.NonEmptyInput |
| | 0 | 336 | | { |
| | 0 | 337 | | ThrowTruncatedInvalidData(); |
| | 0 | 338 | | } |
| | 0 | 339 | | break; |
| | | 340 | | } |
| | 0 | 341 | | else if (n > _buffer.Length) |
| | 0 | 342 | | { |
| | 0 | 343 | | ThrowGenericInvalidData(); |
| | 0 | 344 | | } |
| | | 345 | | else |
| | 0 | 346 | | { |
| | 0 | 347 | | _inflater.SetInput(_buffer, 0, n); |
| | 0 | 348 | | } |
| | 0 | 349 | | } |
| | | 350 | | |
| | 0 | 351 | | if (buffer.IsEmpty) |
| | 0 | 352 | | { |
| | | 353 | | // The caller provided a zero-byte buffer. This is typically done in order to avoid allocating/rent |
| | | 354 | | // a buffer until data is known to be available. We don't have perfect knowledge here, as _inflater |
| | | 355 | | // will return 0 whether or not more data is required, and having input data doesn't necessarily mea |
| | | 356 | | // decompress into at least one byte of output, but it's a reasonable approximation for the 99% case |
| | | 357 | | // wrong, it just means that a caller using zero-byte reads as a way to delay getting a buffer to us |
| | | 358 | | // subsequent call may end up getting one earlier than otherwise preferred. |
| | 0 | 359 | | Debug.Assert(bytesRead == 0); |
| | 0 | 360 | | break; |
| | | 361 | | } |
| | 0 | 362 | | } |
| | | 363 | | |
| | | 364 | | // When decompression finishes, rewind the stream to the exact end of compressed data |
| | 0 | 365 | | if (bytesRead == 0 && InflatorIsFinished && !_decompressionFinished && _stream.CanSeek) |
| | 0 | 366 | | { |
| | 0 | 367 | | TryRewindStream(_stream); |
| | 0 | 368 | | _decompressionFinished = true; |
| | 0 | 369 | | } |
| | | 370 | | |
| | 0 | 371 | | return bytesRead; |
| | 0 | 372 | | } |
| | | 373 | | |
| | | 374 | | private bool InflatorIsFinished => |
| | | 375 | | // If the stream is finished then we have a few potential cases here: |
| | | 376 | | // 1. DeflateStream => return |
| | | 377 | | // 2. GZipStream that is finished but may have an additional GZipStream appended => feed more input |
| | | 378 | | // 3. GZipStream that is finished and appended with garbage => return |
| | 0 | 379 | | _inflater!.Finished() && |
| | 0 | 380 | | (!_inflater.IsGzipStream() || !_inflater.NeedsInput()); |
| | | 381 | | |
| | | 382 | | private void EnsureNotDisposed() |
| | 0 | 383 | | { |
| | 0 | 384 | | ObjectDisposedException.ThrowIf(_stream is null, this); |
| | 0 | 385 | | } |
| | | 386 | | |
| | | 387 | | private void EnsureDecompressionMode() |
| | 0 | 388 | | { |
| | 0 | 389 | | if (_mode != CompressionMode.Decompress) |
| | 0 | 390 | | ThrowCannotReadFromDeflateStreamException(); |
| | | 391 | | |
| | | 392 | | static void ThrowCannotReadFromDeflateStreamException() => |
| | 0 | 393 | | throw new InvalidOperationException(SR.CannotReadFromDeflateStream); |
| | 0 | 394 | | } |
| | | 395 | | |
| | | 396 | | private void EnsureCompressionMode() |
| | 0 | 397 | | { |
| | 0 | 398 | | if (_mode != CompressionMode.Compress) |
| | 0 | 399 | | ThrowCannotWriteToDeflateStreamException(); |
| | | 400 | | |
| | | 401 | | static void ThrowCannotWriteToDeflateStreamException() => |
| | 0 | 402 | | throw new InvalidOperationException(SR.CannotWriteToDeflateStream); |
| | 0 | 403 | | } |
| | | 404 | | |
| | | 405 | | private static void ThrowGenericInvalidData() => |
| | | 406 | | // The stream is either malicious or poorly implemented and returned a number of |
| | | 407 | | // bytes < 0 || > than the buffer supplied to it. |
| | 0 | 408 | | throw new InvalidDataException(SR.GenericInvalidData); |
| | | 409 | | |
| | | 410 | | private static void ThrowTruncatedInvalidData() => |
| | 0 | 411 | | throw new InvalidDataException(SR.TruncatedData); |
| | | 412 | | |
| | | 413 | | public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, objec |
| | 0 | 414 | | TaskToAsyncResult.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState) |
| | | 415 | | |
| | | 416 | | public override int EndRead(IAsyncResult asyncResult) |
| | 0 | 417 | | { |
| | 0 | 418 | | EnsureDecompressionMode(); |
| | 0 | 419 | | EnsureNotDisposed(); |
| | 0 | 420 | | return TaskToAsyncResult.End<int>(asyncResult); |
| | 0 | 421 | | } |
| | | 422 | | |
| | | 423 | | public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) |
| | 0 | 424 | | { |
| | 0 | 425 | | ValidateBufferArguments(buffer, offset, count); |
| | 0 | 426 | | return ReadAsyncMemory(new Memory<byte>(buffer, offset, count), cancellationToken).AsTask(); |
| | 0 | 427 | | } |
| | | 428 | | |
| | | 429 | | public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) |
| | 0 | 430 | | { |
| | 0 | 431 | | if (GetType() != typeof(DeflateStream)) |
| | 0 | 432 | | { |
| | | 433 | | // Ensure that existing streams derived from DeflateStream and that override ReadAsync(byte[],...) |
| | | 434 | | // get their existing behaviors when the newer Memory-based overload is used. |
| | 0 | 435 | | return base.ReadAsync(buffer, cancellationToken); |
| | | 436 | | } |
| | | 437 | | else |
| | 0 | 438 | | { |
| | 0 | 439 | | return ReadAsyncMemory(buffer, cancellationToken); |
| | | 440 | | } |
| | 0 | 441 | | } |
| | | 442 | | |
| | | 443 | | internal ValueTask<int> ReadAsyncMemory(Memory<byte> buffer, CancellationToken cancellationToken) |
| | 0 | 444 | | { |
| | 0 | 445 | | EnsureDecompressionMode(); |
| | 0 | 446 | | EnsureNoActiveAsyncOperation(); |
| | 0 | 447 | | EnsureNotDisposed(); |
| | | 448 | | |
| | 0 | 449 | | if (cancellationToken.IsCancellationRequested) |
| | 0 | 450 | | { |
| | 0 | 451 | | return ValueTask.FromCanceled<int>(cancellationToken); |
| | | 452 | | } |
| | | 453 | | |
| | 0 | 454 | | EnsureBufferInitialized(); |
| | 0 | 455 | | Debug.Assert(_inflater != null); |
| | | 456 | | |
| | 0 | 457 | | return Core(buffer, cancellationToken); |
| | | 458 | | |
| | | 459 | | async ValueTask<int> Core(Memory<byte> buffer, CancellationToken cancellationToken) |
| | 0 | 460 | | { |
| | 0 | 461 | | AsyncOperationStarting(); |
| | | 462 | | try |
| | 0 | 463 | | { |
| | | 464 | | int bytesRead; |
| | 0 | 465 | | while (true) |
| | 0 | 466 | | { |
| | | 467 | | // Try to decompress any data from the inflater into the caller's buffer. |
| | | 468 | | // If we're able to decompress any bytes, or if decompression is completed, we're done. |
| | 0 | 469 | | bytesRead = _inflater.Inflate(buffer.Span); |
| | 0 | 470 | | if (bytesRead != 0 || InflatorIsFinished) |
| | 0 | 471 | | { |
| | 0 | 472 | | break; |
| | | 473 | | } |
| | | 474 | | |
| | | 475 | | // We were unable to decompress any data. If the inflater needs additional input |
| | | 476 | | // data to proceed, read some to populate it. |
| | 0 | 477 | | if (_inflater.NeedsInput()) |
| | 0 | 478 | | { |
| | 0 | 479 | | int n = await _stream.ReadAsync(new Memory<byte>(_buffer, 0, _buffer.Length), cancellationTo |
| | 0 | 480 | | if (n <= 0) |
| | 0 | 481 | | { |
| | | 482 | | // - Inflater didn't return any data although a non-empty output buffer was passed by th |
| | | 483 | | // - More input is needed but there is no more input available. |
| | | 484 | | // - Inflation is not finished yet. |
| | | 485 | | // - Provided input wasn't completely empty |
| | | 486 | | // In such case, we are dealing with a truncated input stream. |
| | 0 | 487 | | if (s_useStrictValidation && !_inflater.Finished() && _inflater.NonEmptyInput() && !buff |
| | 0 | 488 | | { |
| | 0 | 489 | | ThrowTruncatedInvalidData(); |
| | 0 | 490 | | } |
| | 0 | 491 | | break; |
| | | 492 | | } |
| | 0 | 493 | | else if (n > _buffer.Length) |
| | 0 | 494 | | { |
| | 0 | 495 | | ThrowGenericInvalidData(); |
| | 0 | 496 | | } |
| | | 497 | | else |
| | 0 | 498 | | { |
| | 0 | 499 | | _inflater.SetInput(_buffer, 0, n); |
| | 0 | 500 | | } |
| | 0 | 501 | | } |
| | | 502 | | |
| | 0 | 503 | | if (buffer.IsEmpty) |
| | 0 | 504 | | { |
| | | 505 | | // The caller provided a zero-byte buffer. This is typically done in order to avoid allocat |
| | | 506 | | // a buffer until data is known to be available. We don't have perfect knowledge here, as _ |
| | | 507 | | // will return 0 whether or not more data is required, and having input data doesn't necessa |
| | | 508 | | // decompress into at least one byte of output, but it's a reasonable approximation for the |
| | | 509 | | // wrong, it just means that a caller using zero-byte reads as a way to delay getting a buff |
| | | 510 | | // subsequent call may end up getting one earlier than otherwise preferred. |
| | 0 | 511 | | break; |
| | | 512 | | } |
| | 0 | 513 | | } |
| | | 514 | | |
| | | 515 | | // When decompression finishes, rewind the stream to the exact end of compressed data |
| | 0 | 516 | | if (bytesRead == 0 && InflatorIsFinished && !_decompressionFinished && _stream.CanSeek) |
| | 0 | 517 | | { |
| | 0 | 518 | | TryRewindStream(_stream); |
| | 0 | 519 | | _decompressionFinished = true; |
| | 0 | 520 | | } |
| | | 521 | | |
| | 0 | 522 | | return bytesRead; |
| | | 523 | | } |
| | | 524 | | finally |
| | 0 | 525 | | { |
| | 0 | 526 | | AsyncOperationCompleting(); |
| | 0 | 527 | | } |
| | 0 | 528 | | } |
| | 0 | 529 | | } |
| | | 530 | | |
| | | 531 | | public override void Write(byte[] buffer, int offset, int count) |
| | 0 | 532 | | { |
| | 0 | 533 | | ValidateBufferArguments(buffer, offset, count); |
| | 0 | 534 | | WriteCore(new ReadOnlySpan<byte>(buffer, offset, count)); |
| | 0 | 535 | | } |
| | | 536 | | |
| | | 537 | | public override void WriteByte(byte value) |
| | 0 | 538 | | { |
| | 0 | 539 | | if (GetType() != typeof(DeflateStream)) |
| | 0 | 540 | | { |
| | | 541 | | // DeflateStream is not sealed, and a derived type may have overridden Write(byte[], int, int) prior |
| | | 542 | | // to this WriteByte override being introduced. In that case, this WriteByte override |
| | | 543 | | // should use the behavior of the Write(byte[],int,int) overload. |
| | 0 | 544 | | base.WriteByte(value); |
| | 0 | 545 | | } |
| | | 546 | | else |
| | 0 | 547 | | { |
| | 0 | 548 | | WriteCore(new ReadOnlySpan<byte>(in value)); |
| | 0 | 549 | | } |
| | 0 | 550 | | } |
| | | 551 | | |
| | | 552 | | public override void Write(ReadOnlySpan<byte> buffer) |
| | 0 | 553 | | { |
| | 0 | 554 | | if (GetType() != typeof(DeflateStream)) |
| | 0 | 555 | | { |
| | | 556 | | // DeflateStream is not sealed, and a derived type may have overridden Write(byte[], int, int) prior |
| | | 557 | | // to this Write(ReadOnlySpan<byte>) overload being introduced. In that case, this Write(ReadOnlySpan<b |
| | | 558 | | // should use the behavior of Write(byte[],int,int) overload. |
| | 0 | 559 | | base.Write(buffer); |
| | 0 | 560 | | } |
| | | 561 | | else |
| | 0 | 562 | | { |
| | 0 | 563 | | WriteCore(buffer); |
| | 0 | 564 | | } |
| | 0 | 565 | | } |
| | | 566 | | |
| | | 567 | | internal void WriteCore(ReadOnlySpan<byte> buffer) |
| | 0 | 568 | | { |
| | 0 | 569 | | EnsureCompressionMode(); |
| | 0 | 570 | | EnsureNotDisposed(); |
| | | 571 | | |
| | 0 | 572 | | if (buffer.IsEmpty) |
| | 0 | 573 | | { |
| | 0 | 574 | | return; |
| | | 575 | | } |
| | | 576 | | |
| | | 577 | | // Write compressed the bytes we already passed to the deflater: |
| | 0 | 578 | | Debug.Assert(_deflater != null); |
| | 0 | 579 | | WriteDeflaterOutput(); |
| | | 580 | | |
| | | 581 | | unsafe |
| | 0 | 582 | | { |
| | | 583 | | // Pass new bytes through deflater and write them too: |
| | 0 | 584 | | fixed (byte* bufferPtr = &MemoryMarshal.GetReference(buffer)) |
| | 0 | 585 | | { |
| | 0 | 586 | | _deflater.SetInput(bufferPtr, buffer.Length); |
| | 0 | 587 | | WriteDeflaterOutput(); |
| | 0 | 588 | | } |
| | 0 | 589 | | } |
| | 0 | 590 | | } |
| | | 591 | | |
| | | 592 | | private void WriteDeflaterOutput() |
| | 0 | 593 | | { |
| | 0 | 594 | | Debug.Assert(_deflater != null && _buffer != null); |
| | 0 | 595 | | while (!_deflater.NeedsInput()) |
| | 0 | 596 | | { |
| | 0 | 597 | | int compressedBytes = _deflater.GetDeflateOutput(_buffer); |
| | 0 | 598 | | if (compressedBytes > 0) |
| | 0 | 599 | | { |
| | 0 | 600 | | _stream.Write(_buffer, 0, compressedBytes); |
| | 0 | 601 | | } |
| | 0 | 602 | | } |
| | 0 | 603 | | } |
| | | 604 | | |
| | | 605 | | // This is called by Flush: |
| | | 606 | | private void FlushBuffers() |
| | 0 | 607 | | { |
| | | 608 | | // Compress any bytes left: |
| | 0 | 609 | | WriteDeflaterOutput(); |
| | | 610 | | |
| | 0 | 611 | | Debug.Assert(_deflater != null && _buffer != null); |
| | | 612 | | // Pull out any bytes left inside deflater: |
| | | 613 | | bool flushSuccessful; |
| | | 614 | | do |
| | 0 | 615 | | { |
| | | 616 | | int compressedBytes; |
| | 0 | 617 | | flushSuccessful = _deflater.Flush(_buffer, out compressedBytes); |
| | 0 | 618 | | if (flushSuccessful) |
| | 0 | 619 | | { |
| | 0 | 620 | | _stream.Write(_buffer, 0, compressedBytes); |
| | 0 | 621 | | } |
| | 0 | 622 | | Debug.Assert(flushSuccessful == (compressedBytes > 0)); |
| | 0 | 623 | | } while (flushSuccessful); |
| | | 624 | | |
| | | 625 | | // Always flush on the underlying stream |
| | 0 | 626 | | _stream.Flush(); |
| | 0 | 627 | | } |
| | | 628 | | |
| | | 629 | | // This is called by Dispose: |
| | | 630 | | private void PurgeBuffers(bool disposing) |
| | 0 | 631 | | { |
| | 0 | 632 | | if (!disposing) |
| | 0 | 633 | | return; |
| | | 634 | | |
| | 0 | 635 | | if (_stream == null) |
| | 0 | 636 | | return; |
| | | 637 | | |
| | 0 | 638 | | if (_mode != CompressionMode.Compress) |
| | 0 | 639 | | return; |
| | | 640 | | |
| | 0 | 641 | | Debug.Assert(_deflater != null && _buffer != null); |
| | | 642 | | // Compress any bytes left |
| | 0 | 643 | | WriteDeflaterOutput(); |
| | | 644 | | |
| | | 645 | | // Pull out any bytes left inside deflater: |
| | | 646 | | bool finished; |
| | | 647 | | do |
| | 0 | 648 | | { |
| | | 649 | | int compressedBytes; |
| | 0 | 650 | | finished = _deflater.Finish(_buffer, out compressedBytes); |
| | | 651 | | |
| | 0 | 652 | | if (compressedBytes > 0) |
| | 0 | 653 | | _stream.Write(_buffer, 0, compressedBytes); |
| | 0 | 654 | | } while (!finished); |
| | 0 | 655 | | } |
| | | 656 | | |
| | | 657 | | private async ValueTask PurgeBuffersAsync() |
| | 0 | 658 | | { |
| | | 659 | | // Same logic as PurgeBuffers, except with async counterparts. |
| | | 660 | | |
| | 0 | 661 | | if (_stream == null) |
| | 0 | 662 | | return; |
| | | 663 | | |
| | 0 | 664 | | if (_mode != CompressionMode.Compress) |
| | 0 | 665 | | return; |
| | | 666 | | |
| | 0 | 667 | | Debug.Assert(_deflater != null && _buffer != null); |
| | | 668 | | // Compress any bytes left |
| | 0 | 669 | | await WriteDeflaterOutputAsync(default).ConfigureAwait(false); |
| | | 670 | | |
| | | 671 | | // Pull out any bytes left inside deflater: |
| | | 672 | | bool finished; |
| | | 673 | | do |
| | 0 | 674 | | { |
| | | 675 | | int compressedBytes; |
| | 0 | 676 | | finished = _deflater.Finish(_buffer, out compressedBytes); |
| | | 677 | | |
| | 0 | 678 | | if (compressedBytes > 0) |
| | 0 | 679 | | await _stream.WriteAsync(new ReadOnlyMemory<byte>(_buffer, 0, compressedBytes)).ConfigureAwait(false |
| | 0 | 680 | | } while (!finished); |
| | 0 | 681 | | } |
| | | 682 | | |
| | | 683 | | /// <summary> |
| | | 684 | | /// Rewinds the underlying stream to the exact end of the compressed data if there are unconsumed bytes. |
| | | 685 | | /// This is called when decompression finishes to reset the stream position. |
| | | 686 | | /// </summary> |
| | | 687 | | private void TryRewindStream(Stream stream) |
| | 0 | 688 | | { |
| | 0 | 689 | | Debug.Assert(stream != null); |
| | 0 | 690 | | Debug.Assert(_mode == CompressionMode.Decompress); |
| | 0 | 691 | | Debug.Assert(stream.CanSeek); |
| | 0 | 692 | | Debug.Assert(_inflater != null); |
| | | 693 | | |
| | | 694 | | // Check if there are unconsumed bytes in the inflater's input buffer |
| | 0 | 695 | | int unconsumedBytes = _inflater.GetAvailableInput(); |
| | 0 | 696 | | if (unconsumedBytes > 0) |
| | 0 | 697 | | { |
| | | 698 | | try |
| | 0 | 699 | | { |
| | | 700 | | // Rewind the stream to the exact end of the compressed data |
| | 0 | 701 | | stream.Seek(-unconsumedBytes, SeekOrigin.Current); |
| | 0 | 702 | | } |
| | 0 | 703 | | catch |
| | 0 | 704 | | { |
| | | 705 | | // If seeking fails, we don't want to throw during disposal |
| | 0 | 706 | | } |
| | 0 | 707 | | } |
| | 0 | 708 | | } |
| | | 709 | | |
| | | 710 | | protected override void Dispose(bool disposing) |
| | 0 | 711 | | { |
| | | 712 | | try |
| | 0 | 713 | | { |
| | 0 | 714 | | PurgeBuffers(disposing); |
| | 0 | 715 | | } |
| | | 716 | | finally |
| | 0 | 717 | | { |
| | | 718 | | // Close the underlying stream even if PurgeBuffers threw. |
| | | 719 | | // Stream.Close() may throw here (may or may not be due to the same error). |
| | | 720 | | // In this case, we still need to clean up internal resources, hence the inner finally blocks. |
| | | 721 | | try |
| | 0 | 722 | | { |
| | 0 | 723 | | if (disposing && !_leaveOpen) |
| | 0 | 724 | | { |
| | 0 | 725 | | _stream?.Dispose(); |
| | 0 | 726 | | } |
| | 0 | 727 | | } |
| | | 728 | | finally |
| | 0 | 729 | | { |
| | 0 | 730 | | _stream = null!; |
| | | 731 | | |
| | | 732 | | try |
| | 0 | 733 | | { |
| | 0 | 734 | | _deflater?.Dispose(); |
| | 0 | 735 | | _inflater?.Dispose(); |
| | 0 | 736 | | } |
| | | 737 | | finally |
| | 0 | 738 | | { |
| | 0 | 739 | | _deflater = null; |
| | 0 | 740 | | _inflater = null; |
| | | 741 | | |
| | 0 | 742 | | byte[]? buffer = _buffer; |
| | 0 | 743 | | if (buffer != null) |
| | 0 | 744 | | { |
| | 0 | 745 | | _buffer = null; |
| | 0 | 746 | | if (!_activeAsyncOperation) |
| | 0 | 747 | | { |
| | 0 | 748 | | ArrayPool<byte>.Shared.Return(buffer); |
| | 0 | 749 | | } |
| | 0 | 750 | | } |
| | | 751 | | |
| | 0 | 752 | | base.Dispose(disposing); |
| | 0 | 753 | | } |
| | 0 | 754 | | } |
| | 0 | 755 | | } |
| | 0 | 756 | | } |
| | | 757 | | |
| | | 758 | | public override ValueTask DisposeAsync() |
| | 0 | 759 | | { |
| | 0 | 760 | | return GetType() == typeof(DeflateStream) ? |
| | 0 | 761 | | Core() : |
| | 0 | 762 | | base.DisposeAsync(); |
| | | 763 | | |
| | | 764 | | async ValueTask Core() |
| | 0 | 765 | | { |
| | | 766 | | // Same logic as Dispose(true), except with async counterparts. |
| | | 767 | | try |
| | 0 | 768 | | { |
| | 0 | 769 | | await PurgeBuffersAsync().ConfigureAwait(false); |
| | 0 | 770 | | } |
| | | 771 | | finally |
| | 0 | 772 | | { |
| | | 773 | | // Close the underlying stream even if PurgeBuffers threw. |
| | | 774 | | // Stream.Close() may throw here (may or may not be due to the same error). |
| | | 775 | | // In this case, we still need to clean up internal resources, hence the inner finally blocks. |
| | 0 | 776 | | Stream stream = _stream; |
| | 0 | 777 | | _stream = null!; |
| | | 778 | | try |
| | 0 | 779 | | { |
| | 0 | 780 | | if (!_leaveOpen && stream != null) |
| | 0 | 781 | | { |
| | 0 | 782 | | await stream.DisposeAsync().ConfigureAwait(false); |
| | 0 | 783 | | } |
| | 0 | 784 | | } |
| | | 785 | | finally |
| | 0 | 786 | | { |
| | | 787 | | try |
| | 0 | 788 | | { |
| | 0 | 789 | | _deflater?.Dispose(); |
| | 0 | 790 | | _inflater?.Dispose(); |
| | 0 | 791 | | } |
| | | 792 | | finally |
| | 0 | 793 | | { |
| | 0 | 794 | | _deflater = null; |
| | 0 | 795 | | _inflater = null; |
| | | 796 | | |
| | 0 | 797 | | byte[]? buffer = _buffer; |
| | 0 | 798 | | if (buffer != null) |
| | 0 | 799 | | { |
| | 0 | 800 | | _buffer = null; |
| | 0 | 801 | | if (!_activeAsyncOperation) |
| | 0 | 802 | | { |
| | 0 | 803 | | ArrayPool<byte>.Shared.Return(buffer); |
| | 0 | 804 | | } |
| | 0 | 805 | | } |
| | 0 | 806 | | } |
| | 0 | 807 | | } |
| | 0 | 808 | | } |
| | | 809 | | } |
| | 0 | 810 | | } |
| | | 811 | | |
| | | 812 | | public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, obje |
| | 0 | 813 | | TaskToAsyncResult.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState |
| | | 814 | | |
| | | 815 | | public override void EndWrite(IAsyncResult asyncResult) |
| | 0 | 816 | | { |
| | 0 | 817 | | EnsureCompressionMode(); |
| | 0 | 818 | | EnsureNotDisposed(); |
| | 0 | 819 | | TaskToAsyncResult.End(asyncResult); |
| | 0 | 820 | | } |
| | | 821 | | |
| | | 822 | | public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) |
| | 0 | 823 | | { |
| | 0 | 824 | | ValidateBufferArguments(buffer, offset, count); |
| | 0 | 825 | | return WriteAsyncMemory(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken).AsTask(); |
| | 0 | 826 | | } |
| | | 827 | | |
| | | 828 | | public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) |
| | 0 | 829 | | { |
| | 0 | 830 | | if (GetType() != typeof(DeflateStream)) |
| | 0 | 831 | | { |
| | | 832 | | // Ensure that existing streams derived from DeflateStream and that override WriteAsync(byte[],...) |
| | | 833 | | // get their existing behaviors when the newer Memory-based overload is used. |
| | 0 | 834 | | return base.WriteAsync(buffer, cancellationToken); |
| | | 835 | | } |
| | | 836 | | else |
| | 0 | 837 | | { |
| | 0 | 838 | | return WriteAsyncMemory(buffer, cancellationToken); |
| | | 839 | | } |
| | 0 | 840 | | } |
| | | 841 | | |
| | | 842 | | internal ValueTask WriteAsyncMemory(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken) |
| | 0 | 843 | | { |
| | 0 | 844 | | EnsureCompressionMode(); |
| | 0 | 845 | | EnsureNoActiveAsyncOperation(); |
| | 0 | 846 | | EnsureNotDisposed(); |
| | | 847 | | |
| | 0 | 848 | | return |
| | 0 | 849 | | cancellationToken.IsCancellationRequested ? ValueTask.FromCanceled(cancellationToken) : |
| | 0 | 850 | | buffer.IsEmpty ? default : |
| | 0 | 851 | | Core(buffer, cancellationToken); |
| | | 852 | | |
| | | 853 | | async ValueTask Core(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken) |
| | 0 | 854 | | { |
| | 0 | 855 | | AsyncOperationStarting(); |
| | | 856 | | try |
| | 0 | 857 | | { |
| | 0 | 858 | | await WriteDeflaterOutputAsync(cancellationToken).ConfigureAwait(false); |
| | | 859 | | |
| | | 860 | | // Pass new bytes through deflater |
| | 0 | 861 | | Debug.Assert(_deflater != null); |
| | 0 | 862 | | _deflater.SetInput(buffer); |
| | | 863 | | |
| | 0 | 864 | | await WriteDeflaterOutputAsync(cancellationToken).ConfigureAwait(false); |
| | 0 | 865 | | } |
| | | 866 | | finally |
| | 0 | 867 | | { |
| | 0 | 868 | | AsyncOperationCompleting(); |
| | 0 | 869 | | } |
| | 0 | 870 | | } |
| | 0 | 871 | | } |
| | | 872 | | |
| | | 873 | | /// <summary> |
| | | 874 | | /// Writes the bytes that have already been deflated |
| | | 875 | | /// </summary> |
| | | 876 | | private async ValueTask WriteDeflaterOutputAsync(CancellationToken cancellationToken) |
| | 0 | 877 | | { |
| | 0 | 878 | | Debug.Assert(_deflater != null && _buffer != null); |
| | 0 | 879 | | while (!_deflater.NeedsInput()) |
| | 0 | 880 | | { |
| | 0 | 881 | | int compressedBytes = _deflater.GetDeflateOutput(_buffer); |
| | 0 | 882 | | if (compressedBytes > 0) |
| | 0 | 883 | | { |
| | 0 | 884 | | await _stream.WriteAsync(new ReadOnlyMemory<byte>(_buffer, 0, compressedBytes), cancellationToken).C |
| | 0 | 885 | | } |
| | 0 | 886 | | } |
| | 0 | 887 | | } |
| | | 888 | | |
| | | 889 | | public override void CopyTo(Stream destination, int bufferSize) |
| | 0 | 890 | | { |
| | 0 | 891 | | ValidateCopyToArguments(destination, bufferSize); |
| | | 892 | | |
| | 0 | 893 | | EnsureNotDisposed(); |
| | 0 | 894 | | if (!CanRead) throw new NotSupportedException(); |
| | | 895 | | |
| | 0 | 896 | | new CopyToStream(this, destination, bufferSize).CopyFromSourceToDestination(); |
| | 0 | 897 | | } |
| | | 898 | | |
| | | 899 | | public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) |
| | 0 | 900 | | { |
| | 0 | 901 | | ValidateCopyToArguments(destination, bufferSize); |
| | | 902 | | |
| | 0 | 903 | | EnsureNotDisposed(); |
| | 0 | 904 | | if (!CanRead) throw new NotSupportedException(); |
| | 0 | 905 | | EnsureNoActiveAsyncOperation(); |
| | | 906 | | |
| | | 907 | | // Early check for cancellation |
| | 0 | 908 | | if (cancellationToken.IsCancellationRequested) |
| | 0 | 909 | | { |
| | 0 | 910 | | return Task.FromCanceled<int>(cancellationToken); |
| | | 911 | | } |
| | | 912 | | |
| | | 913 | | // Do the copy |
| | 0 | 914 | | return new CopyToStream(this, destination, bufferSize, cancellationToken).CopyFromSourceToDestinationAsync() |
| | 0 | 915 | | } |
| | | 916 | | |
| | | 917 | | private sealed class CopyToStream : Stream |
| | | 918 | | { |
| | | 919 | | private readonly DeflateStream _deflateStream; |
| | | 920 | | private readonly Stream _destination; |
| | | 921 | | private readonly CancellationToken _cancellationToken; |
| | | 922 | | private byte[] _arrayPoolBuffer; |
| | | 923 | | |
| | | 924 | | public CopyToStream(DeflateStream deflateStream, Stream destination, int bufferSize) : |
| | 0 | 925 | | this(deflateStream, destination, bufferSize, CancellationToken.None) |
| | 0 | 926 | | { |
| | 0 | 927 | | } |
| | | 928 | | |
| | 0 | 929 | | public CopyToStream(DeflateStream deflateStream, Stream destination, int bufferSize, CancellationToken cance |
| | 0 | 930 | | { |
| | 0 | 931 | | Debug.Assert(deflateStream != null); |
| | 0 | 932 | | Debug.Assert(destination != null); |
| | 0 | 933 | | Debug.Assert(bufferSize > 0); |
| | | 934 | | |
| | 0 | 935 | | _deflateStream = deflateStream; |
| | 0 | 936 | | _destination = destination; |
| | 0 | 937 | | _cancellationToken = cancellationToken; |
| | 0 | 938 | | _arrayPoolBuffer = ArrayPool<byte>.Shared.Rent(bufferSize); |
| | 0 | 939 | | } |
| | | 940 | | |
| | | 941 | | public async Task CopyFromSourceToDestinationAsync() |
| | 0 | 942 | | { |
| | 0 | 943 | | _deflateStream.AsyncOperationStarting(); |
| | | 944 | | try |
| | 0 | 945 | | { |
| | 0 | 946 | | Debug.Assert(_deflateStream._inflater != null); |
| | | 947 | | // Flush any existing data in the inflater to the destination stream. |
| | 0 | 948 | | while (!_deflateStream._inflater.Finished()) |
| | 0 | 949 | | { |
| | 0 | 950 | | int bytesRead = _deflateStream._inflater.Inflate(_arrayPoolBuffer, 0, _arrayPoolBuffer.Length); |
| | 0 | 951 | | if (bytesRead > 0) |
| | 0 | 952 | | { |
| | 0 | 953 | | await _destination.WriteAsync(new ReadOnlyMemory<byte>(_arrayPoolBuffer, 0, bytesRead), _can |
| | 0 | 954 | | } |
| | 0 | 955 | | else if (_deflateStream._inflater.NeedsInput()) |
| | 0 | 956 | | { |
| | | 957 | | // only break if we read 0 and ran out of input, if input is still available it may be anoth |
| | 0 | 958 | | break; |
| | | 959 | | } |
| | 0 | 960 | | } |
| | | 961 | | |
| | | 962 | | // Now, use the source stream's CopyToAsync to push directly to our inflater via this helper stream |
| | 0 | 963 | | await _deflateStream._stream.CopyToAsync(this, _arrayPoolBuffer.Length, _cancellationToken).Configur |
| | 0 | 964 | | if (s_useStrictValidation && !_deflateStream._inflater.Finished()) |
| | 0 | 965 | | { |
| | 0 | 966 | | ThrowTruncatedInvalidData(); |
| | 0 | 967 | | } |
| | | 968 | | |
| | | 969 | | // Rewind the stream if decompression has finished and the stream supports seeking |
| | 0 | 970 | | if (_deflateStream._inflater.Finished() && !_deflateStream._decompressionFinished && _deflateStream. |
| | 0 | 971 | | { |
| | 0 | 972 | | _deflateStream.TryRewindStream(_deflateStream._stream); |
| | 0 | 973 | | _deflateStream._decompressionFinished = true; |
| | 0 | 974 | | } |
| | 0 | 975 | | } |
| | | 976 | | finally |
| | 0 | 977 | | { |
| | 0 | 978 | | _deflateStream.AsyncOperationCompleting(); |
| | | 979 | | |
| | 0 | 980 | | ArrayPool<byte>.Shared.Return(_arrayPoolBuffer); |
| | 0 | 981 | | _arrayPoolBuffer = null!; |
| | 0 | 982 | | } |
| | 0 | 983 | | } |
| | | 984 | | |
| | | 985 | | public void CopyFromSourceToDestination() |
| | 0 | 986 | | { |
| | | 987 | | try |
| | 0 | 988 | | { |
| | 0 | 989 | | Debug.Assert(_deflateStream._inflater != null); |
| | | 990 | | // Flush any existing data in the inflater to the destination stream. |
| | 0 | 991 | | while (!_deflateStream._inflater.Finished()) |
| | 0 | 992 | | { |
| | 0 | 993 | | int bytesRead = _deflateStream._inflater.Inflate(_arrayPoolBuffer, 0, _arrayPoolBuffer.Length); |
| | 0 | 994 | | if (bytesRead > 0) |
| | 0 | 995 | | { |
| | 0 | 996 | | _destination.Write(_arrayPoolBuffer, 0, bytesRead); |
| | 0 | 997 | | } |
| | 0 | 998 | | else if (_deflateStream._inflater.NeedsInput()) |
| | 0 | 999 | | { |
| | | 1000 | | // only break if we read 0 and ran out of input, if input is still available it may be anoth |
| | 0 | 1001 | | break; |
| | | 1002 | | } |
| | 0 | 1003 | | } |
| | | 1004 | | |
| | | 1005 | | // Now, use the source stream's CopyToAsync to push directly to our inflater via this helper stream |
| | 0 | 1006 | | _deflateStream._stream.CopyTo(this, _arrayPoolBuffer.Length); |
| | 0 | 1007 | | if (s_useStrictValidation && !_deflateStream._inflater.Finished()) |
| | 0 | 1008 | | { |
| | 0 | 1009 | | ThrowTruncatedInvalidData(); |
| | 0 | 1010 | | } |
| | | 1011 | | |
| | | 1012 | | // Rewind the stream if decompression has finished and the stream supports seeking |
| | 0 | 1013 | | if (_deflateStream._inflater.Finished() && !_deflateStream._decompressionFinished && _deflateStream. |
| | 0 | 1014 | | { |
| | 0 | 1015 | | _deflateStream.TryRewindStream(_deflateStream._stream); |
| | 0 | 1016 | | _deflateStream._decompressionFinished = true; |
| | 0 | 1017 | | } |
| | 0 | 1018 | | } |
| | | 1019 | | finally |
| | 0 | 1020 | | { |
| | 0 | 1021 | | ArrayPool<byte>.Shared.Return(_arrayPoolBuffer); |
| | 0 | 1022 | | _arrayPoolBuffer = null!; |
| | 0 | 1023 | | } |
| | 0 | 1024 | | } |
| | | 1025 | | |
| | | 1026 | | public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) |
| | 0 | 1027 | | { |
| | 0 | 1028 | | Debug.Assert(buffer != _arrayPoolBuffer); |
| | 0 | 1029 | | _deflateStream.EnsureNotDisposed(); |
| | 0 | 1030 | | if (count <= 0) |
| | 0 | 1031 | | { |
| | 0 | 1032 | | return Task.CompletedTask; |
| | | 1033 | | } |
| | 0 | 1034 | | else if (count > buffer.Length - offset) |
| | 0 | 1035 | | { |
| | | 1036 | | // The buffer stream is either malicious or poorly implemented and returned a number of |
| | | 1037 | | // bytes larger than the buffer supplied to it. |
| | 0 | 1038 | | return Task.FromException(new InvalidDataException(SR.GenericInvalidData)); |
| | | 1039 | | } |
| | | 1040 | | |
| | 0 | 1041 | | return WriteAsyncCore(buffer.AsMemory(offset, count), cancellationToken).AsTask(); |
| | 0 | 1042 | | } |
| | | 1043 | | |
| | | 1044 | | public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = defa |
| | 0 | 1045 | | { |
| | 0 | 1046 | | _deflateStream.EnsureNotDisposed(); |
| | | 1047 | | |
| | 0 | 1048 | | return WriteAsyncCore(buffer, cancellationToken); |
| | 0 | 1049 | | } |
| | | 1050 | | |
| | | 1051 | | private async ValueTask WriteAsyncCore(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken) |
| | 0 | 1052 | | { |
| | 0 | 1053 | | Debug.Assert(_deflateStream._inflater is not null); |
| | | 1054 | | |
| | | 1055 | | // Feed the data from base stream into decompression engine. |
| | 0 | 1056 | | _deflateStream._inflater.SetInput(buffer); |
| | | 1057 | | |
| | | 1058 | | // While there's more decompressed data available, forward it to the buffer stream. |
| | 0 | 1059 | | while (!_deflateStream._inflater.Finished()) |
| | 0 | 1060 | | { |
| | 0 | 1061 | | int bytesRead = _deflateStream._inflater.Inflate(new Span<byte>(_arrayPoolBuffer)); |
| | 0 | 1062 | | if (bytesRead > 0) |
| | 0 | 1063 | | { |
| | 0 | 1064 | | await _destination.WriteAsync(new ReadOnlyMemory<byte>(_arrayPoolBuffer, 0, bytesRead), cancella |
| | 0 | 1065 | | } |
| | 0 | 1066 | | else if (_deflateStream._inflater.NeedsInput()) |
| | 0 | 1067 | | { |
| | | 1068 | | // only break if we read 0 and ran out of input, if input is still available it may be another G |
| | 0 | 1069 | | break; |
| | | 1070 | | } |
| | 0 | 1071 | | } |
| | 0 | 1072 | | } |
| | | 1073 | | |
| | | 1074 | | public override void Write(byte[] buffer, int offset, int count) |
| | 0 | 1075 | | { |
| | 0 | 1076 | | Debug.Assert(buffer != _arrayPoolBuffer); |
| | 0 | 1077 | | _deflateStream.EnsureNotDisposed(); |
| | | 1078 | | |
| | 0 | 1079 | | if (count <= 0) |
| | 0 | 1080 | | { |
| | 0 | 1081 | | return; |
| | | 1082 | | } |
| | 0 | 1083 | | else if (count > buffer.Length - offset) |
| | 0 | 1084 | | { |
| | | 1085 | | // The buffer stream is either malicious or poorly implemented and returned a number of |
| | | 1086 | | // bytes larger than the buffer supplied to it. |
| | 0 | 1087 | | throw new InvalidDataException(SR.GenericInvalidData); |
| | | 1088 | | } |
| | | 1089 | | |
| | 0 | 1090 | | Debug.Assert(_deflateStream._inflater != null); |
| | | 1091 | | // Feed the data from base stream into the decompression engine. |
| | 0 | 1092 | | _deflateStream._inflater.SetInput(buffer, offset, count); |
| | | 1093 | | |
| | | 1094 | | // While there's more decompressed data available, forward it to the buffer stream. |
| | 0 | 1095 | | while (!_deflateStream._inflater.Finished()) |
| | 0 | 1096 | | { |
| | 0 | 1097 | | int bytesRead = _deflateStream._inflater.Inflate(new Span<byte>(_arrayPoolBuffer)); |
| | 0 | 1098 | | if (bytesRead > 0) |
| | 0 | 1099 | | { |
| | 0 | 1100 | | _destination.Write(_arrayPoolBuffer, 0, bytesRead); |
| | 0 | 1101 | | } |
| | 0 | 1102 | | else if (_deflateStream._inflater.NeedsInput()) |
| | 0 | 1103 | | { |
| | | 1104 | | // only break if we read 0 and ran out of input, if input is still available it may be another G |
| | 0 | 1105 | | break; |
| | | 1106 | | } |
| | 0 | 1107 | | } |
| | 0 | 1108 | | } |
| | | 1109 | | |
| | 0 | 1110 | | public override bool CanWrite => true; |
| | 0 | 1111 | | public override void Flush() { } |
| | 0 | 1112 | | public override bool CanRead => false; |
| | 0 | 1113 | | public override bool CanSeek => false; |
| | 0 | 1114 | | public override long Length { get { throw new NotSupportedException(); } } |
| | 0 | 1115 | | public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedExcep |
| | 0 | 1116 | | public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } |
| | 0 | 1117 | | public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } |
| | 0 | 1118 | | public override void SetLength(long value) { throw new NotSupportedException(); } |
| | | 1119 | | } |
| | | 1120 | | |
| | | 1121 | | private void EnsureNoActiveAsyncOperation() |
| | 0 | 1122 | | { |
| | 0 | 1123 | | if (_activeAsyncOperation) |
| | 0 | 1124 | | { |
| | 0 | 1125 | | ThrowInvalidBeginCall(); |
| | 0 | 1126 | | } |
| | 0 | 1127 | | } |
| | | 1128 | | |
| | | 1129 | | private void AsyncOperationStarting() |
| | 0 | 1130 | | { |
| | 0 | 1131 | | if (Interlocked.Exchange(ref _activeAsyncOperation, true)) |
| | 0 | 1132 | | { |
| | 0 | 1133 | | ThrowInvalidBeginCall(); |
| | 0 | 1134 | | } |
| | 0 | 1135 | | } |
| | | 1136 | | |
| | | 1137 | | private void AsyncOperationCompleting() |
| | 0 | 1138 | | { |
| | 0 | 1139 | | Debug.Assert(_activeAsyncOperation); |
| | 0 | 1140 | | _activeAsyncOperation = false; |
| | 0 | 1141 | | } |
| | | 1142 | | |
| | | 1143 | | private static void ThrowInvalidBeginCall() => |
| | 0 | 1144 | | throw new InvalidOperationException(SR.InvalidBeginCall); |
| | | 1145 | | |
| | 0 | 1146 | | private static readonly bool s_useStrictValidation = |
| | 0 | 1147 | | AppContext.TryGetSwitch("System.IO.Compression.UseStrictValidation", out bool strictValidation) ? strictVali |
| | | 1148 | | } |
| | | 1149 | | } |