| | | 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.CompilerServices; |
| | | 7 | | using System.Runtime.InteropServices; |
| | | 8 | | using Microsoft.Win32.SafeHandles; |
| | | 9 | | |
| | | 10 | | namespace System.IO.Compression |
| | | 11 | | { |
| | | 12 | | /// <summary>Represents a Zstandard compression dictionary.</summary> |
| | | 13 | | [System.Runtime.Versioning.UnsupportedOSPlatform("browser")] |
| | | 14 | | [System.Runtime.Versioning.UnsupportedOSPlatform("wasi")] |
| | | 15 | | public sealed class ZstandardDictionary : IDisposable |
| | | 16 | | { |
| | | 17 | | private readonly SafeZstdCDictHandle _compressionDictionary; |
| | | 18 | | private readonly SafeZstdDDictHandle _decompressionDictionary; |
| | | 19 | | private readonly byte[] _dictionaryData; |
| | | 20 | | private bool _disposed; |
| | | 21 | | |
| | 0 | 22 | | private ZstandardDictionary(SafeZstdCDictHandle compressionDict, SafeZstdDDictHandle decompressionDict, byte[] d |
| | 0 | 23 | | { |
| | 0 | 24 | | _compressionDictionary = compressionDict; |
| | 0 | 25 | | _decompressionDictionary = decompressionDict; |
| | 0 | 26 | | _dictionaryData = data; |
| | 0 | 27 | | } |
| | | 28 | | |
| | | 29 | | /// <summary>Creates a Zstandard dictionary from the specified buffer.</summary> |
| | | 30 | | /// <param name="buffer">The buffer containing the dictionary data.</param> |
| | | 31 | | /// <returns>A new <see cref="ZstandardDictionary"/> instance.</returns> |
| | | 32 | | /// <exception cref="ArgumentException">The buffer is empty.</exception> |
| | 0 | 33 | | public static ZstandardDictionary Create(ReadOnlySpan<byte> buffer) => Create(buffer, ZstandardUtils.Quality_Def |
| | | 34 | | |
| | | 35 | | /// <summary>Creates a Zstandard dictionary from the specified buffer with the specified quality level and dicti |
| | | 36 | | /// <param name="buffer">The buffer containing the dictionary data.</param> |
| | | 37 | | /// <param name="quality">The quality level for dictionary creation.</param> |
| | | 38 | | /// <returns>A new <see cref="ZstandardDictionary"/> instance.</returns> |
| | | 39 | | /// <exception cref="ArgumentException">The buffer is empty.</exception> |
| | | 40 | | /// <exception cref="IOException">Failed to create the <see cref="ZstandardDictionary"/> instance.</exception> |
| | | 41 | | public static ZstandardDictionary Create(ReadOnlySpan<byte> buffer, int quality) |
| | 0 | 42 | | { |
| | 0 | 43 | | if (buffer.IsEmpty) |
| | 0 | 44 | | { |
| | 0 | 45 | | throw new ArgumentException(SR.ZstandardDictionary_EmptyBuffer, nameof(buffer)); |
| | | 46 | | } |
| | | 47 | | |
| | 0 | 48 | | byte[] data = buffer.ToArray(); |
| | | 49 | | |
| | | 50 | | |
| | | 51 | | unsafe |
| | 0 | 52 | | { |
| | 0 | 53 | | fixed (byte* dictPtr = data) |
| | 0 | 54 | | { |
| | 0 | 55 | | SafeZstdCDictHandle compressionDict = Interop.Zstd.ZSTD_createCDict_byReference(dictPtr, (nuint)data |
| | | 56 | | |
| | 0 | 57 | | if (compressionDict.IsInvalid) |
| | 0 | 58 | | { |
| | 0 | 59 | | throw new IOException(SR.ZstandardDictionary_CreateCompressionFailed); |
| | | 60 | | } |
| | 0 | 61 | | compressionDict._pinnedData = new PinnedGCHandle<byte[]>(data); |
| | | 62 | | |
| | 0 | 63 | | SafeZstdDDictHandle decompressionDict = Interop.Zstd.ZSTD_createDDict_byReference(dictPtr, (nuint)da |
| | | 64 | | |
| | 0 | 65 | | if (decompressionDict.IsInvalid) |
| | 0 | 66 | | { |
| | 0 | 67 | | compressionDict.Dispose(); |
| | 0 | 68 | | throw new IOException(SR.ZstandardDictionary_CreateDecompressionFailed); |
| | | 69 | | } |
| | 0 | 70 | | decompressionDict._pinnedData = new PinnedGCHandle<byte[]>(data); |
| | | 71 | | |
| | 0 | 72 | | return new ZstandardDictionary(compressionDict, decompressionDict, data); |
| | | 73 | | } |
| | | 74 | | } |
| | 0 | 75 | | } |
| | | 76 | | |
| | | 77 | | /// <summary>Creates a dictionary by training on the provided samples.</summary> |
| | | 78 | | /// <param name="samples">All training samples concatenated in one large buffer.</param> |
| | | 79 | | /// <param name="sampleLengths">The lengths of the individual samples. The sum of these lengths must equal the l |
| | | 80 | | /// <param name="maxDictionarySize">The maximum size of the dictionary to create.</param> |
| | | 81 | | /// <returns>A new <see cref="ZstandardDictionary"/> instance.</returns> |
| | | 82 | | /// <exception cref="ArgumentException">The sample data or lengths are invalid.</exception> |
| | | 83 | | /// <exception cref="ArgumentOutOfRangeException"><paramref name="maxDictionarySize"/> is not between the minimu |
| | | 84 | | /// <exception cref="IOException">Failed to train the dictionary.</exception> |
| | | 85 | | /// <remarks> |
| | | 86 | | /// The recommended maximum dictionary size is 100 KB, and the size of the training data |
| | | 87 | | /// should be approximately 100 times the size of the resulting dictionary. |
| | | 88 | | /// </remarks> |
| | | 89 | | public static ZstandardDictionary Train(ReadOnlySpan<byte> samples, ReadOnlySpan<int> sampleLengths, int maxDict |
| | 0 | 90 | | { |
| | 0 | 91 | | if (samples.IsEmpty) |
| | 0 | 92 | | { |
| | 0 | 93 | | throw new ArgumentException(SR.ZstandardDictionary_EmptyBuffer, nameof(samples)); |
| | | 94 | | } |
| | | 95 | | |
| | | 96 | | // this requirement is enforced by zstd native library, probably due to the underlying algorithm design |
| | 0 | 97 | | if (sampleLengths.Length < 5) |
| | 0 | 98 | | { |
| | 0 | 99 | | throw new ArgumentException(SR.Format(SR.ZstandardDictionary_Train_MinimumSampleCount, 5), nameof(sample |
| | | 100 | | } |
| | | 101 | | |
| | | 102 | | // the lengths need to be converted to nuint for the native call. Rent appropriately sized array from pool |
| | | 103 | | // This incidentally also protects against concurrent modifications of the sampleLengths that could cause |
| | | 104 | | // access violations later in native code. |
| | 0 | 105 | | byte[] lengthsArray = ArrayPool<byte>.Shared.Rent(sampleLengths.Length * sizeof(nuint)); |
| | 0 | 106 | | byte[]? dictionaryBuffer = null; |
| | | 107 | | try |
| | 0 | 108 | | { |
| | 0 | 109 | | Span<nuint> lengthsAsNuint = MemoryMarshal.Cast<byte, nuint>(lengthsArray.AsSpan(0, sampleLengths.Length |
| | 0 | 110 | | Debug.Assert(lengthsAsNuint.Length == sampleLengths.Length); |
| | | 111 | | |
| | 0 | 112 | | long totalLength = 0; |
| | 0 | 113 | | for (int i = 0; i < sampleLengths.Length; i++) |
| | 0 | 114 | | { |
| | 0 | 115 | | int length = sampleLengths[i]; |
| | 0 | 116 | | if (length <= 0) |
| | 0 | 117 | | { |
| | 0 | 118 | | throw new ArgumentException(SR.ZstandardDictionary_Train_InvalidSampleLength, nameof(sampleLengt |
| | | 119 | | } |
| | 0 | 120 | | totalLength += length; |
| | 0 | 121 | | lengthsAsNuint[i] = (nuint)length; |
| | 0 | 122 | | } |
| | | 123 | | |
| | 0 | 124 | | if (totalLength != samples.Length) |
| | 0 | 125 | | { |
| | 0 | 126 | | throw new ArgumentException(SR.ZstandardDictionary_SampleLengthsMismatch, nameof(sampleLengths)); |
| | | 127 | | } |
| | | 128 | | |
| | 0 | 129 | | ArgumentOutOfRangeException.ThrowIfLessThan(maxDictionarySize, 256, nameof(maxDictionarySize)); |
| | | 130 | | |
| | 0 | 131 | | dictionaryBuffer = ArrayPool<byte>.Shared.Rent(maxDictionarySize); |
| | | 132 | | nuint dictSize; |
| | | 133 | | |
| | | 134 | | unsafe |
| | 0 | 135 | | { |
| | 0 | 136 | | fixed (byte* samplesPtr = &MemoryMarshal.GetReference(samples)) |
| | 0 | 137 | | fixed (byte* dictPtr = dictionaryBuffer) |
| | 0 | 138 | | fixed (nuint* lengthsAsNuintPtr = &MemoryMarshal.GetReference(lengthsAsNuint)) |
| | 0 | 139 | | { |
| | 0 | 140 | | dictSize = Interop.Zstd.ZDICT_trainFromBuffer( |
| | 0 | 141 | | dictPtr, (nuint)maxDictionarySize, |
| | 0 | 142 | | samplesPtr, lengthsAsNuintPtr, (uint)sampleLengths.Length); |
| | 0 | 143 | | } |
| | | 144 | | |
| | 0 | 145 | | ZstandardUtils.ThrowIfError(dictSize); |
| | 0 | 146 | | return Create(dictionaryBuffer.AsSpan(0, (int)dictSize)); |
| | | 147 | | } |
| | | 148 | | } |
| | | 149 | | finally |
| | 0 | 150 | | { |
| | 0 | 151 | | if (dictionaryBuffer is not null) |
| | 0 | 152 | | { |
| | 0 | 153 | | ArrayPool<byte>.Shared.Return(dictionaryBuffer); |
| | 0 | 154 | | } |
| | 0 | 155 | | ArrayPool<byte>.Shared.Return(lengthsArray); |
| | 0 | 156 | | } |
| | 0 | 157 | | } |
| | | 158 | | |
| | | 159 | | /// <summary>Gets the compression dictionary handle.</summary> |
| | | 160 | | internal SafeZstdCDictHandle CompressionDictionary |
| | | 161 | | { |
| | | 162 | | get |
| | 0 | 163 | | { |
| | 0 | 164 | | ThrowIfDisposed(); |
| | 0 | 165 | | return _compressionDictionary; |
| | 0 | 166 | | } |
| | | 167 | | } |
| | | 168 | | |
| | | 169 | | /// <summary>Gets the decompression dictionary handle.</summary> |
| | | 170 | | internal SafeZstdDDictHandle DecompressionDictionary |
| | | 171 | | { |
| | | 172 | | get |
| | 0 | 173 | | { |
| | 0 | 174 | | ThrowIfDisposed(); |
| | 0 | 175 | | return _decompressionDictionary; |
| | 0 | 176 | | } |
| | | 177 | | } |
| | | 178 | | |
| | | 179 | | /// <summary>Gets the dictionary data.</summary> |
| | | 180 | | /// <value>The raw dictionary bytes.</value> |
| | | 181 | | public ReadOnlyMemory<byte> Data |
| | | 182 | | { |
| | | 183 | | get |
| | 0 | 184 | | { |
| | 0 | 185 | | ThrowIfDisposed(); |
| | 0 | 186 | | return _dictionaryData; |
| | 0 | 187 | | } |
| | | 188 | | } |
| | | 189 | | |
| | | 190 | | /// <summary>Releases all resources used by the <see cref="ZstandardDictionary"/>.</summary> |
| | | 191 | | public void Dispose() |
| | 0 | 192 | | { |
| | 0 | 193 | | if (!_disposed) |
| | 0 | 194 | | { |
| | 0 | 195 | | _compressionDictionary.Dispose(); |
| | 0 | 196 | | _decompressionDictionary.Dispose(); |
| | 0 | 197 | | _disposed = true; |
| | 0 | 198 | | } |
| | 0 | 199 | | } |
| | | 200 | | |
| | | 201 | | private void ThrowIfDisposed() |
| | 0 | 202 | | { |
| | 0 | 203 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | 0 | 204 | | } |
| | | 205 | | } |
| | | 206 | | } |