| | | 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.Runtime.InteropServices; |
| | | 7 | | |
| | | 8 | | namespace System.IO.Compression |
| | | 9 | | { |
| | | 10 | | /// <summary> |
| | | 11 | | /// Provides methods and static methods to encode data in a streamless, non-allocating, and performant manner using |
| | | 12 | | /// </summary> |
| | | 13 | | public sealed class DeflateEncoder : IDisposable |
| | | 14 | | { |
| | | 15 | | private ZLibNative.ZLibStreamHandle? _state; |
| | | 16 | | private bool _disposed; |
| | | 17 | | private bool _finished; |
| | | 18 | | |
| | | 19 | | /// <summary> |
| | | 20 | | /// Initializes a new instance of the <see cref="DeflateEncoder"/> class using the default quality. |
| | | 21 | | /// </summary> |
| | | 22 | | /// <exception cref="IOException">Failed to create the <see cref="DeflateEncoder"/> instance.</exception> |
| | | 23 | | public DeflateEncoder() |
| | 0 | 24 | | : this(ZLibNative.DefaultQuality) |
| | 0 | 25 | | { |
| | 0 | 26 | | } |
| | | 27 | | |
| | | 28 | | /// <summary> |
| | | 29 | | /// Initializes a new instance of the <see cref="DeflateEncoder"/> class using the specified quality. |
| | | 30 | | /// </summary> |
| | | 31 | | /// <param name="quality">The compression quality value between 0 (no compression) and 9 (maximum compression), |
| | | 32 | | /// <exception cref="ArgumentOutOfRangeException"><paramref name="quality"/> is not in the valid range (0-9 or - |
| | | 33 | | /// <exception cref="IOException">Failed to create the <see cref="DeflateEncoder"/> instance.</exception> |
| | | 34 | | public DeflateEncoder(int quality) |
| | 0 | 35 | | : this(quality, ZLibNative.DefaultWindowLog) |
| | 0 | 36 | | { |
| | 0 | 37 | | } |
| | | 38 | | |
| | | 39 | | /// <summary> |
| | | 40 | | /// Initializes a new instance of the <see cref="DeflateEncoder"/> class using the specified options. |
| | | 41 | | /// </summary> |
| | | 42 | | /// <param name="options">The compression options.</param> |
| | | 43 | | /// <exception cref="ArgumentNullException"><paramref name="options"/> is null.</exception> |
| | | 44 | | /// <exception cref="IOException">Failed to create the <see cref="DeflateEncoder"/> instance.</exception> |
| | | 45 | | public DeflateEncoder(ZLibCompressionOptions options) |
| | 0 | 46 | | : this(options, CompressionFormat.Deflate) |
| | 0 | 47 | | { |
| | 0 | 48 | | } |
| | | 49 | | |
| | | 50 | | /// <summary> |
| | | 51 | | /// Initializes a new instance of the <see cref="DeflateEncoder"/> class using the specified quality and window |
| | | 52 | | /// </summary> |
| | | 53 | | /// <param name="quality">The compression quality value between 0 (no compression) and 9 (maximum compression), |
| | | 54 | | /// <param name="windowLog2">The base-2 logarithm of the window size (8-15), or -1 to use the default value. Lar |
| | | 55 | | /// <exception cref="ArgumentOutOfRangeException"><paramref name="quality"/> is not in the valid range (0-9 or - |
| | | 56 | | /// <exception cref="IOException">Failed to create the <see cref="DeflateEncoder"/> instance.</exception> |
| | | 57 | | public DeflateEncoder(int quality, int windowLog2) |
| | 0 | 58 | | : this(quality, windowLog2, CompressionFormat.Deflate) |
| | 0 | 59 | | { |
| | 0 | 60 | | } |
| | | 61 | | |
| | | 62 | | /// <summary> |
| | | 63 | | /// Internal constructor that accepts quality, windowLog2 (8-15), and format. |
| | | 64 | | /// Validates both parameters and transforms windowLog2 to windowBits based on format. |
| | | 65 | | /// </summary> |
| | 0 | 66 | | internal DeflateEncoder(int quality, int windowLog2, CompressionFormat format) |
| | 0 | 67 | | { |
| | 0 | 68 | | ValidateQuality(quality); |
| | 0 | 69 | | ValidateWindowLog(windowLog2); |
| | | 70 | | |
| | 0 | 71 | | int windowBits = CompressionFormatHelper.ResolveWindowBits(windowLog2, format); |
| | | 72 | | |
| | 0 | 73 | | int memLevel = quality == (int)ZLibNative.CompressionLevel.NoCompression |
| | 0 | 74 | | ? ZLibNative.Deflate_NoCompressionMemLevel |
| | 0 | 75 | | : ZLibNative.Deflate_DefaultMemLevel; |
| | | 76 | | |
| | 0 | 77 | | _state = ZLibNative.ZLibStreamHandle.CreateForDeflate( |
| | 0 | 78 | | (ZLibNative.CompressionLevel)quality, |
| | 0 | 79 | | windowBits, |
| | 0 | 80 | | memLevel, |
| | 0 | 81 | | ZLibNative.CompressionStrategy.DefaultStrategy); |
| | 0 | 82 | | } |
| | | 83 | | |
| | | 84 | | /// <summary> |
| | | 85 | | /// Internal constructor that accepts ZLibCompressionOptions and format. |
| | | 86 | | /// </summary> |
| | 0 | 87 | | internal DeflateEncoder(ZLibCompressionOptions options, CompressionFormat format) |
| | 0 | 88 | | { |
| | 0 | 89 | | ArgumentNullException.ThrowIfNull(options); |
| | | 90 | | |
| | 0 | 91 | | int windowBits = CompressionFormatHelper.ResolveWindowBits(options.WindowLog2, format); |
| | | 92 | | |
| | 0 | 93 | | int memLevel = options.CompressionLevel == (int)ZLibNative.CompressionLevel.NoCompression |
| | 0 | 94 | | ? ZLibNative.Deflate_NoCompressionMemLevel |
| | 0 | 95 | | : ZLibNative.Deflate_DefaultMemLevel; |
| | | 96 | | |
| | 0 | 97 | | _state = ZLibNative.ZLibStreamHandle.CreateForDeflate( |
| | 0 | 98 | | (ZLibNative.CompressionLevel)options.CompressionLevel, |
| | 0 | 99 | | windowBits, |
| | 0 | 100 | | memLevel, |
| | 0 | 101 | | (ZLibNative.CompressionStrategy)options.CompressionStrategy); |
| | 0 | 102 | | } |
| | | 103 | | |
| | | 104 | | private static void ValidateQuality(int quality) |
| | 0 | 105 | | { |
| | 0 | 106 | | if (quality != -1) |
| | 0 | 107 | | { |
| | 0 | 108 | | ArgumentOutOfRangeException.ThrowIfLessThan(quality, ZLibNative.MinQuality, nameof(quality)); |
| | 0 | 109 | | ArgumentOutOfRangeException.ThrowIfGreaterThan(quality, ZLibNative.MaxQuality, nameof(quality)); |
| | 0 | 110 | | } |
| | 0 | 111 | | } |
| | | 112 | | |
| | | 113 | | private static void ValidateWindowLog(int windowLog2) |
| | 0 | 114 | | { |
| | 0 | 115 | | if (windowLog2 != -1) |
| | 0 | 116 | | { |
| | 0 | 117 | | ArgumentOutOfRangeException.ThrowIfLessThan(windowLog2, ZLibNative.MinWindowLog, nameof(windowLog2)); |
| | 0 | 118 | | ArgumentOutOfRangeException.ThrowIfGreaterThan(windowLog2, ZLibNative.MaxWindowLog, nameof(windowLog2)); |
| | 0 | 119 | | } |
| | 0 | 120 | | } |
| | | 121 | | |
| | | 122 | | /// <summary> |
| | | 123 | | /// Frees and disposes unmanaged resources. |
| | | 124 | | /// </summary> |
| | | 125 | | public void Dispose() |
| | 0 | 126 | | { |
| | 0 | 127 | | _disposed = true; |
| | 0 | 128 | | _state?.Dispose(); |
| | 0 | 129 | | _state = null; |
| | 0 | 130 | | } |
| | | 131 | | |
| | | 132 | | private void EnsureNotDisposed() |
| | 0 | 133 | | { |
| | 0 | 134 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | 0 | 135 | | } |
| | | 136 | | |
| | | 137 | | /// <summary> |
| | | 138 | | /// Gets the maximum expected compressed length for the provided input size. |
| | | 139 | | /// </summary> |
| | | 140 | | /// <param name="inputLength">The input size to get the maximum expected compressed length from.</param> |
| | | 141 | | /// <returns>A number representing the maximum compressed length for the provided input size.</returns> |
| | | 142 | | /// <exception cref="ArgumentOutOfRangeException"><paramref name="inputLength"/> is negative.</exception> |
| | | 143 | | public static long GetMaxCompressedLength(long inputLength) |
| | 0 | 144 | | { |
| | 0 | 145 | | ArgumentOutOfRangeException.ThrowIfNegative(inputLength); |
| | | 146 | | |
| | | 147 | | // For inputs up to 2 GiB, delegate to the native compressBound() function, which returns |
| | | 148 | | // the exact upper bound for the zlib implementation linked into the current process |
| | | 149 | | // (either classic zlib or zlib-ng, depending on platform and build flags). The 2^31 |
| | | 150 | | // threshold keeps the value within the uint P/Invoke signature on all platforms. |
| | | 151 | | |
| | | 152 | | // Browser/WASI builds do not link the native compression library, |
| | | 153 | | // so fall through to the managed formula on those platforms. |
| | 0 | 154 | | if (inputLength <= (1L << 31) && !OperatingSystem.IsBrowser() && !OperatingSystem.IsWasi()) |
| | 0 | 155 | | { |
| | 0 | 156 | | return Interop.ZLib.compressBound((uint)inputLength); |
| | | 157 | | } |
| | | 158 | | |
| | | 159 | | // For larger inputs, compute the bound in managed code using zlib-ng's quick-strategy |
| | | 160 | | // formula. It is strictly larger than classic zlib's compressBound(), so it is a safe |
| | | 161 | | // upper bound regardless of which implementation is linked at runtime. |
| | | 162 | | // See: src/native/external/zlib-ng/compress.c and zutil.h. |
| | | 163 | | // Use ulong to avoid overflow; reject inputs whose bound does not fit in long. |
| | 0 | 164 | | ulong sourceLength = (ulong)inputLength; |
| | 0 | 165 | | ulong maxCompressedLength = sourceLength |
| | 0 | 166 | | + (sourceLength == 0 ? 1u : 0u) |
| | 0 | 167 | | + (sourceLength < 9 ? 1u : 0u) |
| | 0 | 168 | | + ((sourceLength + 7) >> 3) |
| | 0 | 169 | | + 3 // DEFLATE_BLOCK_OVERHEAD: (3 + 15 + 6) >> 3 |
| | 0 | 170 | | + 6; // ZLIB_WRAPLEN: zlib header (2 bytes) + Adler32 trailer (4 bytes) |
| | | 171 | | |
| | 0 | 172 | | if (maxCompressedLength > long.MaxValue) |
| | 0 | 173 | | { |
| | 0 | 174 | | throw new ArgumentOutOfRangeException(nameof(inputLength)); |
| | | 175 | | } |
| | | 176 | | |
| | 0 | 177 | | return (long)maxCompressedLength; |
| | 0 | 178 | | } |
| | | 179 | | |
| | | 180 | | /// <summary> |
| | | 181 | | /// Compresses a read-only byte span into a destination span. |
| | | 182 | | /// </summary> |
| | | 183 | | /// <param name="source">A read-only span of bytes containing the source data to compress.</param> |
| | | 184 | | /// <param name="destination">When this method returns, a byte span where the compressed data is stored.</param> |
| | | 185 | | /// <param name="bytesConsumed">When this method returns, the total number of bytes that were read from <paramre |
| | | 186 | | /// <param name="bytesWritten">When this method returns, the total number of bytes that were written to <paramre |
| | | 187 | | /// <param name="isFinalBlock"><see langword="true"/> to finalize the internal stream, which prevents adding mor |
| | | 188 | | /// <returns>One of the enumeration values that describes the status with which the span-based operation finishe |
| | | 189 | | public OperationStatus Compress(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesConsumed, out in |
| | 0 | 190 | | { |
| | 0 | 191 | | EnsureNotDisposed(); |
| | 0 | 192 | | Debug.Assert(_state is not null); |
| | | 193 | | |
| | 0 | 194 | | bytesConsumed = 0; |
| | 0 | 195 | | bytesWritten = 0; |
| | | 196 | | |
| | 0 | 197 | | if (_finished) |
| | 0 | 198 | | { |
| | 0 | 199 | | return OperationStatus.Done; |
| | | 200 | | } |
| | | 201 | | |
| | 0 | 202 | | if (source.IsEmpty && !isFinalBlock) |
| | 0 | 203 | | { |
| | 0 | 204 | | return OperationStatus.Done; |
| | | 205 | | } |
| | | 206 | | |
| | 0 | 207 | | if (destination.IsEmpty && (source.Length > 0 || isFinalBlock)) |
| | 0 | 208 | | { |
| | 0 | 209 | | return OperationStatus.DestinationTooSmall; |
| | | 210 | | } |
| | | 211 | | |
| | 0 | 212 | | ZLibNative.FlushCode flushCode = isFinalBlock ? ZLibNative.FlushCode.Finish : ZLibNative.FlushCode.NoFlush; |
| | | 213 | | |
| | | 214 | | unsafe |
| | 0 | 215 | | { |
| | 0 | 216 | | fixed (byte* inputPtr = &MemoryMarshal.GetReference(source)) |
| | 0 | 217 | | fixed (byte* outputPtr = &MemoryMarshal.GetReference(destination)) |
| | 0 | 218 | | { |
| | 0 | 219 | | _state.NextIn = (IntPtr)inputPtr; |
| | 0 | 220 | | _state.AvailIn = (uint)source.Length; |
| | 0 | 221 | | _state.NextOut = (IntPtr)outputPtr; |
| | 0 | 222 | | _state.AvailOut = (uint)destination.Length; |
| | | 223 | | |
| | 0 | 224 | | ZLibNative.ErrorCode errorCode = _state.Deflate(flushCode); |
| | | 225 | | |
| | 0 | 226 | | bytesConsumed = source.Length - (int)_state.AvailIn; |
| | 0 | 227 | | bytesWritten = destination.Length - (int)_state.AvailOut; |
| | | 228 | | |
| | 0 | 229 | | OperationStatus status = errorCode switch |
| | 0 | 230 | | { |
| | 0 | 231 | | ZLibNative.ErrorCode.Ok when isFinalBlock => OperationStatus.DestinationTooSmall, |
| | 0 | 232 | | ZLibNative.ErrorCode.Ok => _state.AvailIn == 0 |
| | 0 | 233 | | ? OperationStatus.Done |
| | 0 | 234 | | : OperationStatus.DestinationTooSmall, |
| | 0 | 235 | | ZLibNative.ErrorCode.StreamEnd => OperationStatus.Done, |
| | 0 | 236 | | ZLibNative.ErrorCode.BufError => _state.AvailOut == 0 |
| | 0 | 237 | | ? OperationStatus.DestinationTooSmall |
| | 0 | 238 | | : OperationStatus.Done, |
| | 0 | 239 | | _ => throw new ZLibException(SR.ZLibErrorUnexpected, "deflate", (int)errorCode, _state.GetErrorM |
| | 0 | 240 | | }; |
| | | 241 | | |
| | | 242 | | // Track if compression is finished |
| | 0 | 243 | | if (isFinalBlock && errorCode == ZLibNative.ErrorCode.StreamEnd) |
| | 0 | 244 | | { |
| | 0 | 245 | | _finished = true; |
| | 0 | 246 | | } |
| | | 247 | | |
| | 0 | 248 | | return status; |
| | | 249 | | } |
| | | 250 | | } |
| | 0 | 251 | | } |
| | | 252 | | |
| | | 253 | | /// <summary> |
| | | 254 | | /// Compresses an empty read-only span of bytes into its destination, ensuring that output is produced for all t |
| | | 255 | | /// </summary> |
| | | 256 | | /// <param name="destination">When this method returns, a span of bytes where the compressed data will be stored |
| | | 257 | | /// <param name="bytesWritten">When this method returns, the total number of bytes that were written to <paramre |
| | | 258 | | /// <returns>One of the enumeration values that describes the status with which the operation finished.</returns |
| | | 259 | | public OperationStatus Flush(Span<byte> destination, out int bytesWritten) |
| | 0 | 260 | | { |
| | 0 | 261 | | EnsureNotDisposed(); |
| | 0 | 262 | | Debug.Assert(_state is not null); |
| | | 263 | | |
| | 0 | 264 | | bytesWritten = 0; |
| | | 265 | | |
| | 0 | 266 | | if (_finished) |
| | 0 | 267 | | { |
| | 0 | 268 | | return OperationStatus.Done; |
| | | 269 | | } |
| | | 270 | | |
| | | 271 | | unsafe |
| | 0 | 272 | | { |
| | 0 | 273 | | fixed (byte* outputPtr = &MemoryMarshal.GetReference(destination)) |
| | 0 | 274 | | { |
| | 0 | 275 | | _state.NextIn = IntPtr.Zero; |
| | 0 | 276 | | _state.AvailIn = 0; |
| | 0 | 277 | | _state.NextOut = (IntPtr)outputPtr; |
| | 0 | 278 | | _state.AvailOut = (uint)destination.Length; |
| | | 279 | | |
| | 0 | 280 | | ZLibNative.ErrorCode errorCode = _state.Deflate(ZLibNative.FlushCode.SyncFlush); |
| | | 281 | | |
| | 0 | 282 | | bytesWritten = destination.Length - (int)_state.AvailOut; |
| | | 283 | | |
| | 0 | 284 | | return errorCode switch |
| | 0 | 285 | | { |
| | 0 | 286 | | ZLibNative.ErrorCode.Ok => _state.AvailOut == 0 |
| | 0 | 287 | | ? OperationStatus.DestinationTooSmall |
| | 0 | 288 | | : OperationStatus.Done, |
| | 0 | 289 | | ZLibNative.ErrorCode.StreamEnd => OperationStatus.Done, |
| | 0 | 290 | | ZLibNative.ErrorCode.BufError => _state.AvailOut == 0 |
| | 0 | 291 | | ? OperationStatus.DestinationTooSmall |
| | 0 | 292 | | : OperationStatus.Done, |
| | 0 | 293 | | _ => throw new ZLibException(SR.ZLibErrorUnexpected, "deflate", (int)errorCode, _state.GetErrorM |
| | 0 | 294 | | }; |
| | | 295 | | } |
| | | 296 | | } |
| | 0 | 297 | | } |
| | | 298 | | |
| | | 299 | | /// <summary> |
| | | 300 | | /// Tries to compress a source byte span into a destination span using the default quality. |
| | | 301 | | /// </summary> |
| | | 302 | | /// <param name="source">A read-only span of bytes containing the source data to compress.</param> |
| | | 303 | | /// <param name="destination">When this method returns, a span of bytes where the compressed data is stored.</pa |
| | | 304 | | /// <param name="bytesWritten">When this method returns, the total number of bytes that were written to <paramre |
| | | 305 | | /// <returns><see langword="true"/> if the compression operation was successful; <see langword="false"/> otherwi |
| | | 306 | | public static bool TryCompress(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten) |
| | 0 | 307 | | => TryCompress(source, destination, out bytesWritten, ZLibNative.DefaultQuality, ZLibNative.DefaultWindowLog |
| | | 308 | | |
| | | 309 | | /// <summary> |
| | | 310 | | /// Tries to compress a source byte span into a destination span using the specified quality. |
| | | 311 | | /// </summary> |
| | | 312 | | /// <param name="source">A read-only span of bytes containing the source data to compress.</param> |
| | | 313 | | /// <param name="destination">When this method returns, a span of bytes where the compressed data is stored.</pa |
| | | 314 | | /// <param name="bytesWritten">When this method returns, the total number of bytes that were written to <paramre |
| | | 315 | | /// <param name="quality">The compression quality value between 0 (no compression) and 9 (maximum compression), |
| | | 316 | | /// <returns><see langword="true"/> if the compression operation was successful; <see langword="false"/> otherwi |
| | | 317 | | public static bool TryCompress(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten, int qual |
| | 0 | 318 | | => TryCompress(source, destination, out bytesWritten, quality, ZLibNative.DefaultWindowLog); |
| | | 319 | | |
| | | 320 | | /// <summary> |
| | | 321 | | /// Tries to compress a source byte span into a destination span using the specified quality and window size. |
| | | 322 | | /// </summary> |
| | | 323 | | /// <param name="source">A read-only span of bytes containing the source data to compress.</param> |
| | | 324 | | /// <param name="destination">When this method returns, a span of bytes where the compressed data is stored.</pa |
| | | 325 | | /// <param name="bytesWritten">When this method returns, the total number of bytes that were written to <paramre |
| | | 326 | | /// <param name="quality">The compression quality value between 0 (no compression) and 9 (maximum compression), |
| | | 327 | | /// <param name="windowLog2">The base-2 logarithm of the window size (8-15), or -1 to use the default value. Lar |
| | | 328 | | /// <returns><see langword="true"/> if the compression operation was successful; <see langword="false"/> otherwi |
| | | 329 | | public static bool TryCompress(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten, int qual |
| | 0 | 330 | | { |
| | 0 | 331 | | using var encoder = new DeflateEncoder(quality, windowLog2); |
| | 0 | 332 | | OperationStatus status = encoder.Compress(source, destination, out int consumed, out bytesWritten, isFinalBl |
| | | 333 | | |
| | 0 | 334 | | bool success = status == OperationStatus.Done && consumed == source.Length; |
| | 0 | 335 | | if (!success) |
| | 0 | 336 | | { |
| | 0 | 337 | | bytesWritten = 0; |
| | 0 | 338 | | } |
| | | 339 | | |
| | 0 | 340 | | return success; |
| | 0 | 341 | | } |
| | | 342 | | } |
| | | 343 | | } |