| | | 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.CompilerServices; |
| | | 8 | | using System.Runtime.InteropServices; |
| | | 9 | | using Microsoft.Win32.SafeHandles; |
| | | 10 | | |
| | | 11 | | namespace System.IO.Compression |
| | | 12 | | { |
| | | 13 | | /// <summary>Provides methods and properties to decompress data using Zstandard decompression.</summary> |
| | | 14 | | [System.Runtime.Versioning.UnsupportedOSPlatform("browser")] |
| | | 15 | | [System.Runtime.Versioning.UnsupportedOSPlatform("wasi")] |
| | | 16 | | public sealed class ZstandardDecoder : IDisposable |
| | | 17 | | { |
| | | 18 | | private SafeZstdDecompressHandle _context; |
| | | 19 | | private bool _disposed; |
| | | 20 | | |
| | | 21 | | /// <summary> |
| | | 22 | | /// True if we finished decompressing the entire input. |
| | | 23 | | /// </summary> |
| | | 24 | | private bool _finished; |
| | | 25 | | |
| | | 26 | | /// <summary>Initializes a new instance of the <see cref="ZstandardDecoder"/> class with default settings.</summ |
| | | 27 | | /// <exception cref="IOException">Failed to create the <see cref="ZstandardDecoder"/> instance.</exception> |
| | 0 | 28 | | public ZstandardDecoder() |
| | 0 | 29 | | { |
| | 0 | 30 | | _disposed = false; |
| | 0 | 31 | | _finished = false; |
| | 0 | 32 | | InitializeDecoder(); |
| | 0 | 33 | | } |
| | | 34 | | |
| | | 35 | | /// <summary>Initializes a new instance of the <see cref="ZstandardDecoder"/> class with the specified maximum w |
| | | 36 | | /// <param name="maxWindowLog2">The maximum base-2 logarithm of the window size to use for decompression.</param |
| | | 37 | | /// <exception cref="ArgumentOutOfRangeException"><paramref name="maxWindowLog2"/> is not between the minimum an |
| | | 38 | | /// <exception cref="IOException">Failed to create the <see cref="ZstandardDecoder"/> instance.</exception> |
| | 0 | 39 | | public ZstandardDecoder(int maxWindowLog2) |
| | 0 | 40 | | { |
| | 0 | 41 | | _disposed = false; |
| | | 42 | | |
| | 0 | 43 | | InitializeDecoder(); |
| | | 44 | | |
| | | 45 | | try |
| | 0 | 46 | | { |
| | 0 | 47 | | if (maxWindowLog2 != 0) |
| | 0 | 48 | | { |
| | 0 | 49 | | SetWindowLog(maxWindowLog2); |
| | 0 | 50 | | } |
| | 0 | 51 | | } |
| | 0 | 52 | | catch |
| | 0 | 53 | | { |
| | 0 | 54 | | _context.Dispose(); |
| | 0 | 55 | | throw; |
| | | 56 | | } |
| | 0 | 57 | | } |
| | | 58 | | |
| | | 59 | | /// <summary>Initializes a new instance of the <see cref="ZstandardDecoder"/> class with the specified dictionar |
| | | 60 | | /// <param name="dictionary">The decompression dictionary to use.</param> |
| | | 61 | | /// <exception cref="ArgumentNullException"><paramref name="dictionary"/> is null.</exception> |
| | | 62 | | /// <exception cref="IOException">Failed to create the <see cref="ZstandardDecoder"/> instance.</exception> |
| | 0 | 63 | | public ZstandardDecoder(ZstandardDictionary dictionary) |
| | 0 | 64 | | { |
| | 0 | 65 | | ArgumentNullException.ThrowIfNull(dictionary); |
| | | 66 | | |
| | 0 | 67 | | _disposed = false; |
| | | 68 | | |
| | 0 | 69 | | InitializeDecoder(); |
| | | 70 | | |
| | | 71 | | try |
| | 0 | 72 | | { |
| | 0 | 73 | | SetDictionary(dictionary); |
| | 0 | 74 | | } |
| | 0 | 75 | | catch |
| | 0 | 76 | | { |
| | 0 | 77 | | _context.Dispose(); |
| | 0 | 78 | | throw; |
| | | 79 | | } |
| | 0 | 80 | | } |
| | | 81 | | |
| | | 82 | | /// <summary>Initializes a new instance of the <see cref="ZstandardDecoder"/> class with the specified decompres |
| | | 83 | | /// <param name="decompressionOptions">The options to use for Zstandard decompression.</param> |
| | | 84 | | /// <exception cref="ArgumentNullException"><paramref name="decompressionOptions"/> is null.</exception> |
| | | 85 | | /// <exception cref="IOException">Failed to create the <see cref="ZstandardDecoder"/> instance.</exception> |
| | 0 | 86 | | public ZstandardDecoder(ZstandardDecompressionOptions decompressionOptions) |
| | 0 | 87 | | { |
| | 0 | 88 | | ArgumentNullException.ThrowIfNull(decompressionOptions); |
| | | 89 | | |
| | 0 | 90 | | _disposed = false; |
| | | 91 | | |
| | 0 | 92 | | InitializeDecoder(); |
| | | 93 | | |
| | | 94 | | try |
| | 0 | 95 | | { |
| | 0 | 96 | | if (decompressionOptions.MaxWindowLog2 != 0) |
| | 0 | 97 | | { |
| | 0 | 98 | | SetWindowLog(decompressionOptions.MaxWindowLog2); |
| | 0 | 99 | | } |
| | | 100 | | |
| | 0 | 101 | | if (decompressionOptions.Dictionary is not null) |
| | 0 | 102 | | { |
| | 0 | 103 | | SetDictionary(decompressionOptions.Dictionary); |
| | 0 | 104 | | } |
| | 0 | 105 | | } |
| | 0 | 106 | | catch |
| | 0 | 107 | | { |
| | 0 | 108 | | _context.Dispose(); |
| | 0 | 109 | | throw; |
| | | 110 | | } |
| | 0 | 111 | | } |
| | | 112 | | |
| | | 113 | | /// <summary>Initializes a new instance of the <see cref="ZstandardDecoder"/> class with the specified dictionar |
| | | 114 | | /// <param name="dictionary">The decompression dictionary to use.</param> |
| | | 115 | | /// <param name="maxWindowLog2">The maximum base-2 logarithm of the window size to use for decompression.</param |
| | | 116 | | /// <exception cref="ArgumentNullException"><paramref name="dictionary"/> is null.</exception> |
| | | 117 | | /// <exception cref="ArgumentOutOfRangeException"><paramref name="maxWindowLog2"/> is not between the minimum an |
| | | 118 | | /// <exception cref="IOException">Failed to create the <see cref="ZstandardDecoder"/> instance.</exception> |
| | 0 | 119 | | public ZstandardDecoder(ZstandardDictionary dictionary, int maxWindowLog2) |
| | 0 | 120 | | { |
| | 0 | 121 | | ArgumentNullException.ThrowIfNull(dictionary); |
| | | 122 | | |
| | 0 | 123 | | _disposed = false; |
| | | 124 | | |
| | 0 | 125 | | InitializeDecoder(); |
| | | 126 | | |
| | | 127 | | try |
| | 0 | 128 | | { |
| | 0 | 129 | | if (maxWindowLog2 != 0) |
| | 0 | 130 | | { |
| | 0 | 131 | | SetWindowLog(maxWindowLog2); |
| | 0 | 132 | | } |
| | | 133 | | |
| | 0 | 134 | | SetDictionary(dictionary); |
| | 0 | 135 | | } |
| | 0 | 136 | | catch |
| | 0 | 137 | | { |
| | 0 | 138 | | _context.Dispose(); |
| | 0 | 139 | | throw; |
| | | 140 | | } |
| | 0 | 141 | | } |
| | | 142 | | |
| | | 143 | | [MemberNotNull(nameof(_context))] |
| | | 144 | | private void InitializeDecoder() |
| | 0 | 145 | | { |
| | 0 | 146 | | _context = Interop.Zstd.ZSTD_createDCtx(); |
| | 0 | 147 | | if (_context.IsInvalid) |
| | 0 | 148 | | { |
| | 0 | 149 | | throw new OutOfMemoryException(); |
| | | 150 | | } |
| | 0 | 151 | | } |
| | | 152 | | |
| | | 153 | | /// <summary>Decompresses the specified data.</summary> |
| | | 154 | | /// <param name="source">The compressed data to decompress.</param> |
| | | 155 | | /// <param name="destination">The buffer to write the decompressed data to.</param> |
| | | 156 | | /// <param name="bytesConsumed">When this method returns, contains the number of bytes consumed from the source. |
| | | 157 | | /// <param name="bytesWritten">When this method returns, contains the number of bytes written to the destination |
| | | 158 | | /// <returns>An <see cref="OperationStatus"/> indicating the result of the operation.</returns> |
| | | 159 | | /// <remarks> |
| | | 160 | | /// The method returns <see cref="OperationStatus.Done"/> after all |
| | | 161 | | /// contents of a single Zstandard frame are decoded and returned. However, |
| | | 162 | | /// Zstandard data streams may consist of multiple concatenated frames |
| | | 163 | | /// (some of which may even be empty). To allow processing further |
| | | 164 | | /// frames on the same <see cref="ZstandardDecoder" /> instance, call |
| | | 165 | | /// <see cref="Reset" /> before calling <see cref="Decompress" /> on the rest of the data. |
| | | 166 | | /// </remarks> |
| | | 167 | | /// <exception cref="ObjectDisposedException">The decoder has been disposed.</exception> |
| | | 168 | | /// <exception cref="IOException">An error occurred during decompression.</exception> |
| | | 169 | | public OperationStatus Decompress(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesConsumed, out |
| | 0 | 170 | | { |
| | 0 | 171 | | bytesWritten = 0; |
| | 0 | 172 | | bytesConsumed = 0; |
| | | 173 | | |
| | 0 | 174 | | if (_finished) |
| | 0 | 175 | | { |
| | 0 | 176 | | return OperationStatus.Done; |
| | | 177 | | } |
| | | 178 | | |
| | 0 | 179 | | EnsureNotDisposed(); |
| | | 180 | | |
| | 0 | 181 | | if (destination.IsEmpty) |
| | 0 | 182 | | { |
| | 0 | 183 | | return OperationStatus.DestinationTooSmall; |
| | | 184 | | } |
| | | 185 | | |
| | | 186 | | unsafe |
| | 0 | 187 | | { |
| | 0 | 188 | | fixed (byte* sourcePtr = &MemoryMarshal.GetReference(source)) |
| | 0 | 189 | | fixed (byte* destPtr = &MemoryMarshal.GetReference(destination)) |
| | 0 | 190 | | { |
| | 0 | 191 | | var input = new Interop.Zstd.ZstdInBuffer |
| | 0 | 192 | | { |
| | 0 | 193 | | src = sourcePtr, |
| | 0 | 194 | | size = (nuint)source.Length, |
| | 0 | 195 | | pos = 0 |
| | 0 | 196 | | }; |
| | | 197 | | |
| | 0 | 198 | | var output = new Interop.Zstd.ZstdOutBuffer |
| | 0 | 199 | | { |
| | 0 | 200 | | dst = destPtr, |
| | 0 | 201 | | size = (nuint)destination.Length, |
| | 0 | 202 | | pos = 0 |
| | 0 | 203 | | }; |
| | | 204 | | |
| | 0 | 205 | | nuint result = Interop.Zstd.ZSTD_decompressStream(_context, ref output, ref input); |
| | | 206 | | |
| | 0 | 207 | | if (ZstandardUtils.IsError(result, out var error)) |
| | 0 | 208 | | { |
| | 0 | 209 | | switch (error) |
| | | 210 | | { |
| | | 211 | | // These specific errors are actionable by the caller and don't imply |
| | | 212 | | // that the data itself is corrupt. |
| | | 213 | | case Interop.Zstd.ZSTD_error.frameParameter_windowTooLarge: |
| | | 214 | | case Interop.Zstd.ZSTD_error.dictionary_wrong: |
| | 0 | 215 | | ZstandardUtils.Throw(error); |
| | | 216 | | break; |
| | | 217 | | |
| | | 218 | | default: |
| | 0 | 219 | | return OperationStatus.InvalidData; |
| | | 220 | | } |
| | | 221 | | } |
| | | 222 | | |
| | 0 | 223 | | bytesConsumed = (int)input.pos; |
| | 0 | 224 | | bytesWritten = (int)output.pos; |
| | | 225 | | |
| | 0 | 226 | | if (result == 0) |
| | 0 | 227 | | { |
| | 0 | 228 | | _finished = true; |
| | 0 | 229 | | return OperationStatus.Done; |
| | | 230 | | } |
| | 0 | 231 | | else if (output.pos == output.size) |
| | 0 | 232 | | { |
| | 0 | 233 | | return OperationStatus.DestinationTooSmall; |
| | | 234 | | } |
| | | 235 | | else |
| | 0 | 236 | | { |
| | 0 | 237 | | return OperationStatus.NeedMoreData; |
| | | 238 | | } |
| | | 239 | | } |
| | | 240 | | } |
| | 0 | 241 | | } |
| | | 242 | | |
| | | 243 | | /// <summary>Attempts to get the maximum decompressed length for the specified compressed data.</summary> |
| | | 244 | | /// <param name="data">The compressed data.</param> |
| | | 245 | | /// <param name="length">When this method returns <see langword="true" />, contains the maximum decompressed len |
| | | 246 | | /// <returns><see langword="true" /> on success; <see langword="false" /> otherwise.</returns> |
| | | 247 | | public static bool TryGetMaxDecompressedLength(ReadOnlySpan<byte> data, out long length) |
| | 0 | 248 | | { |
| | 0 | 249 | | if (data.IsEmpty) |
| | 0 | 250 | | { |
| | 0 | 251 | | length = 0; |
| | 0 | 252 | | return true; |
| | | 253 | | } |
| | | 254 | | |
| | | 255 | | unsafe |
| | 0 | 256 | | { |
| | 0 | 257 | | fixed (byte* dataPtr = &MemoryMarshal.GetReference(data)) |
| | 0 | 258 | | { |
| | 0 | 259 | | ulong frameContentSize = Interop.Zstd.ZSTD_decompressBound(dataPtr, (nuint)data.Length); |
| | | 260 | | |
| | | 261 | | const ulong ZSTD_CONTENTSIZE_UNKNOWN = unchecked(0UL - 1); |
| | | 262 | | const ulong ZSTD_CONTENTSIZE_ERROR = unchecked(0UL - 2); |
| | 0 | 263 | | if (frameContentSize == ZSTD_CONTENTSIZE_UNKNOWN || frameContentSize == ZSTD_CONTENTSIZE_ERROR || fr |
| | 0 | 264 | | { |
| | 0 | 265 | | length = 0; |
| | 0 | 266 | | return false; |
| | | 267 | | } |
| | | 268 | | |
| | 0 | 269 | | length = (long)frameContentSize; |
| | 0 | 270 | | return true; |
| | | 271 | | } |
| | | 272 | | } |
| | 0 | 273 | | } |
| | | 274 | | |
| | | 275 | | /// <summary>Attempts to decompress the specified data.</summary> |
| | | 276 | | /// <param name="source">The compressed data to decompress.</param> |
| | | 277 | | /// <param name="destination">The buffer to write the decompressed data to.</param> |
| | | 278 | | /// <param name="bytesWritten">When this method returns <see langword="true" />, contains the number of bytes wr |
| | | 279 | | /// <returns><see langword="true" /> on success; <see langword="false" /> otherwise.</returns> |
| | | 280 | | /// <remarks>If this method returns <see langword="false" />, <paramref name="destination" /> may be empty or co |
| | | 281 | | public static bool TryDecompress(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten) |
| | 0 | 282 | | { |
| | 0 | 283 | | bytesWritten = 0; |
| | | 284 | | |
| | 0 | 285 | | if (source.IsEmpty) |
| | 0 | 286 | | { |
| | 0 | 287 | | return false; |
| | | 288 | | } |
| | | 289 | | |
| | | 290 | | unsafe |
| | 0 | 291 | | { |
| | 0 | 292 | | fixed (byte* sourcePtr = &MemoryMarshal.GetReference(source)) |
| | 0 | 293 | | fixed (byte* destPtr = &MemoryMarshal.GetReference(destination)) |
| | 0 | 294 | | { |
| | 0 | 295 | | nuint result = Interop.Zstd.ZSTD_decompress( |
| | 0 | 296 | | destPtr, (nuint)destination.Length, |
| | 0 | 297 | | sourcePtr, (nuint)source.Length); |
| | | 298 | | |
| | 0 | 299 | | if (ZstandardUtils.IsError(result, out var error)) |
| | 0 | 300 | | { |
| | 0 | 301 | | return false; |
| | | 302 | | } |
| | | 303 | | |
| | 0 | 304 | | bytesWritten = (int)result; |
| | 0 | 305 | | return true; |
| | | 306 | | } |
| | | 307 | | } |
| | 0 | 308 | | } |
| | | 309 | | |
| | | 310 | | /// <summary>Attempts to decompress the specified data using the specified dictionary.</summary> |
| | | 311 | | /// <param name="source">The compressed data to decompress.</param> |
| | | 312 | | /// <param name="dictionary">The decompression dictionary to use.</param> |
| | | 313 | | /// <param name="destination">The buffer to write the decompressed data to.</param> |
| | | 314 | | /// <param name="bytesWritten">When this method returns <see langword="true" />, contains the number of bytes wr |
| | | 315 | | /// <returns><see langword="true" /> on success; <see langword="false" /> otherwise.</returns> |
| | | 316 | | /// <exception cref="ArgumentNullException"><paramref name="dictionary"/> is null.</exception> |
| | | 317 | | /// <remarks>If this method returns <see langword="false" />, <paramref name="destination" /> may be empty or co |
| | | 318 | | public static bool TryDecompress(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten, Zstand |
| | 0 | 319 | | { |
| | 0 | 320 | | ArgumentNullException.ThrowIfNull(dictionary); |
| | | 321 | | |
| | 0 | 322 | | bytesWritten = 0; |
| | | 323 | | |
| | 0 | 324 | | if (source.IsEmpty) |
| | 0 | 325 | | { |
| | 0 | 326 | | return false; |
| | | 327 | | } |
| | | 328 | | |
| | 0 | 329 | | using var dctx = Interop.Zstd.ZSTD_createDCtx(); |
| | 0 | 330 | | if (dctx.IsInvalid) |
| | 0 | 331 | | { |
| | 0 | 332 | | throw new OutOfMemoryException(); |
| | | 333 | | } |
| | | 334 | | |
| | | 335 | | unsafe |
| | 0 | 336 | | { |
| | 0 | 337 | | fixed (byte* sourcePtr = &MemoryMarshal.GetReference(source)) |
| | 0 | 338 | | fixed (byte* destPtr = &MemoryMarshal.GetReference(destination)) |
| | 0 | 339 | | { |
| | 0 | 340 | | nuint result = Interop.Zstd.ZSTD_decompress_usingDDict( |
| | 0 | 341 | | dctx, destPtr, (nuint)destination.Length, |
| | 0 | 342 | | sourcePtr, (nuint)source.Length, dictionary.DecompressionDictionary); |
| | | 343 | | |
| | 0 | 344 | | if (ZstandardUtils.IsError(result, out var error)) |
| | 0 | 345 | | { |
| | 0 | 346 | | return false; |
| | | 347 | | } |
| | | 348 | | |
| | 0 | 349 | | bytesWritten = checked((int)result); |
| | 0 | 350 | | return true; |
| | | 351 | | } |
| | | 352 | | } |
| | 0 | 353 | | } |
| | | 354 | | |
| | | 355 | | /// <summary>Resets the decoder session, allowing reuse for decompressing the next Zstandard frame.</summary> |
| | | 356 | | /// <exception cref="ObjectDisposedException">The decoder has been disposed.</exception> |
| | | 357 | | /// <exception cref="IOException">Failed to reset the decoder session.</exception> |
| | | 358 | | public void Reset() |
| | 0 | 359 | | { |
| | 0 | 360 | | EnsureNotDisposed(); |
| | | 361 | | |
| | 0 | 362 | | _context.Reset(); |
| | 0 | 363 | | _finished = false; |
| | 0 | 364 | | } |
| | | 365 | | |
| | | 366 | | /// <summary>References a prefix for the next decompression operation.</summary> |
| | | 367 | | /// <remarks>The prefix will be used only for the next decompression frame and will be removed when <see cref="R |
| | | 368 | | /// <exception cref="ObjectDisposedException">The decoder has been disposed.</exception> |
| | | 369 | | /// <exception cref="InvalidOperationException">The decoder is in an invalid state for setting a prefix.</except |
| | | 370 | | public void SetPrefix(ReadOnlyMemory<byte> prefix) |
| | 0 | 371 | | { |
| | 0 | 372 | | EnsureNotDisposed(); |
| | | 373 | | |
| | 0 | 374 | | if (_finished) |
| | 0 | 375 | | { |
| | 0 | 376 | | throw new InvalidOperationException(SR.ZstandardEncoderDecoder_InvalidState); |
| | | 377 | | } |
| | | 378 | | |
| | 0 | 379 | | nuint result = _context.SetPrefix(prefix); |
| | | 380 | | |
| | 0 | 381 | | if (ZstandardUtils.IsError(result, out var error)) |
| | 0 | 382 | | { |
| | 0 | 383 | | ZstandardUtils.Throw(error); |
| | | 384 | | } |
| | 0 | 385 | | } |
| | | 386 | | |
| | | 387 | | /// <summary>Releases all resources used by the <see cref="ZstandardDecoder"/>.</summary> |
| | | 388 | | public void Dispose() |
| | 0 | 389 | | { |
| | 0 | 390 | | _disposed = true; |
| | 0 | 391 | | _context.Dispose(); |
| | 0 | 392 | | } |
| | | 393 | | |
| | | 394 | | private void EnsureNotDisposed() |
| | 0 | 395 | | { |
| | 0 | 396 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | 0 | 397 | | } |
| | | 398 | | |
| | | 399 | | internal void SetWindowLog(int maxWindowLog2) |
| | 0 | 400 | | { |
| | 0 | 401 | | Debug.Assert(_context != null); |
| | | 402 | | |
| | 0 | 403 | | if (maxWindowLog2 != 0) |
| | 0 | 404 | | { |
| | 0 | 405 | | ArgumentOutOfRangeException.ThrowIfLessThan(maxWindowLog2, ZstandardUtils.WindowLog_Min, nameof(maxWindo |
| | 0 | 406 | | ArgumentOutOfRangeException.ThrowIfGreaterThan(maxWindowLog2, ZstandardUtils.WindowLog_Max, nameof(maxWi |
| | 0 | 407 | | } |
| | | 408 | | |
| | 0 | 409 | | nuint result = Interop.Zstd.ZSTD_DCtx_setParameter(_context, Interop.Zstd.ZstdDParameter.ZSTD_d_windowLogMax |
| | 0 | 410 | | ZstandardUtils.ThrowIfError(result); |
| | 0 | 411 | | } |
| | | 412 | | |
| | | 413 | | internal void SetDictionary(ZstandardDictionary dictionary) |
| | 0 | 414 | | { |
| | 0 | 415 | | Debug.Assert(_context != null); |
| | 0 | 416 | | ArgumentNullException.ThrowIfNull(dictionary); |
| | | 417 | | |
| | 0 | 418 | | _context.SetDictionary(dictionary.DecompressionDictionary); |
| | 0 | 419 | | } |
| | | 420 | | } |
| | | 421 | | } |