| 1 |
from backports.zstd._cffi._common import ( |
| 2 |
ZstdError, |
| 3 |
_check_int, |
| 4 |
_clinic_check, |
| 5 |
_ErrorType, |
| 6 |
_ffi, |
| 7 |
_lib, |
| 8 |
_nbytes, |
| 9 |
_new_nonzero, |
| 10 |
_set_zstd_error, |
| 11 |
set_parameter_types, |
| 12 |
) |
| 13 |
from backports.zstd._cffi.compressor import ZstdCompressor |
| 14 |
from backports.zstd._cffi.decompressor import ZstdDecompressor |
| 15 |
from backports.zstd._cffi.zstddict import ZstdDict |
| 16 |
|
| 17 |
zstd_version = _ffi.string(_lib.ZSTD_versionString()).decode() |
| 18 |
zstd_version_number = _lib.ZSTD_versionNumber() |
| 19 |
ZSTD_CLEVEL_DEFAULT = _lib.ZSTD_defaultCLevel() |
| 20 |
ZSTD_DStreamOutSize = _lib.ZSTD_DStreamOutSize() |
| 21 |
|
| 22 |
ZSTD_c_compressionLevel = _lib.ZSTD_c_compressionLevel |
| 23 |
ZSTD_c_windowLog = _lib.ZSTD_c_windowLog |
| 24 |
ZSTD_c_hashLog = _lib.ZSTD_c_hashLog |
| 25 |
ZSTD_c_chainLog = _lib.ZSTD_c_chainLog |
| 26 |
ZSTD_c_searchLog = _lib.ZSTD_c_searchLog |
| 27 |
ZSTD_c_minMatch = _lib.ZSTD_c_minMatch |
| 28 |
ZSTD_c_targetLength = _lib.ZSTD_c_targetLength |
| 29 |
ZSTD_c_strategy = _lib.ZSTD_c_strategy |
| 30 |
ZSTD_c_enableLongDistanceMatching = _lib.ZSTD_c_enableLongDistanceMatching |
| 31 |
ZSTD_c_ldmHashLog = _lib.ZSTD_c_ldmHashLog |
| 32 |
ZSTD_c_ldmMinMatch = _lib.ZSTD_c_ldmMinMatch |
| 33 |
ZSTD_c_ldmBucketSizeLog = _lib.ZSTD_c_ldmBucketSizeLog |
| 34 |
ZSTD_c_ldmHashRateLog = _lib.ZSTD_c_ldmHashRateLog |
| 35 |
ZSTD_c_contentSizeFlag = _lib.ZSTD_c_contentSizeFlag |
| 36 |
ZSTD_c_checksumFlag = _lib.ZSTD_c_checksumFlag |
| 37 |
ZSTD_c_dictIDFlag = _lib.ZSTD_c_dictIDFlag |
| 38 |
ZSTD_c_nbWorkers = _lib.ZSTD_c_nbWorkers |
| 39 |
ZSTD_c_jobSize = _lib.ZSTD_c_jobSize |
| 40 |
ZSTD_c_overlapLog = _lib.ZSTD_c_overlapLog |
| 41 |
|
| 42 |
ZSTD_d_windowLogMax = _lib.ZSTD_d_windowLogMax |
| 43 |
|
| 44 |
ZSTD_fast = _lib.ZSTD_fast |
| 45 |
ZSTD_dfast = _lib.ZSTD_dfast |
| 46 |
ZSTD_greedy = _lib.ZSTD_greedy |
| 47 |
ZSTD_lazy = _lib.ZSTD_lazy |
| 48 |
ZSTD_lazy2 = _lib.ZSTD_lazy2 |
| 49 |
ZSTD_btlazy2 = _lib.ZSTD_btlazy2 |
| 50 |
ZSTD_btopt = _lib.ZSTD_btopt |
| 51 |
ZSTD_btultra = _lib.ZSTD_btultra |
| 52 |
ZSTD_btultra2 = _lib.ZSTD_btultra2 |
| 53 |
|
| 54 |
|
| 55 |
def get_param_bounds(parameter, is_compress): |
| 56 |
"""Get CompressionParameter/DecompressionParameter bounds. |
| 57 |
|
| 58 |
parameter |
| 59 |
The parameter to get bounds. |
| 60 |
is_compress |
| 61 |
True for CompressionParameter, False for DecompressionParameter.""" |
| 62 |
if is_compress: |
| 63 |
bound = _lib.ZSTD_cParam_getBounds(parameter) |
| 64 |
if _lib.ZSTD_isError(bound.error): |
| 65 |
_set_zstd_error(_ErrorType.ERR_GET_C_BOUNDS, bound.error) |
| 66 |
else: |
| 67 |
bound = _lib.ZSTD_dParam_getBounds(parameter) |
| 68 |
if _lib.ZSTD_isError(bound.error): |
| 69 |
_set_zstd_error(_ErrorType.ERR_GET_D_BOUNDS, bound.error) |
| 70 |
return bound.lowerBound, bound.upperBound |
| 71 |
|
| 72 |
|
| 73 |
def get_frame_info(frame_buffer): |
| 74 |
"""Get Zstandard frame infomation from a frame header. |
| 75 |
|
| 76 |
frame_buffer |
| 77 |
A bytes-like object, containing the header of a Zstandard frame.""" |
| 78 |
decompressed_size = _lib.ZSTD_getFrameContentSize( |
| 79 |
_ffi.from_buffer(frame_buffer), len(frame_buffer) |
| 80 |
) |
| 81 |
if decompressed_size == _lib.ZSTD_CONTENTSIZE_ERROR: |
| 82 |
raise ZstdError( |
| 83 |
"Error when getting information from the header of " |
| 84 |
"a Zstandard frame. Ensure the frame_buffer argument " |
| 85 |
"starts from the beginning of a frame, and its length " |
| 86 |
"is not less than the frame header (6~18 bytes)." |
| 87 |
) |
| 88 |
dict_id = _lib.ZSTD_getDictID_fromFrame( |
| 89 |
_ffi.from_buffer(frame_buffer), len(frame_buffer) |
| 90 |
) |
| 91 |
if decompressed_size == _lib.ZSTD_CONTENTSIZE_UNKNOWN: |
| 92 |
return None, dict_id |
| 93 |
return decompressed_size, dict_id |
| 94 |
|
| 95 |
|
| 96 |
def get_frame_size(frame_buffer): |
| 97 |
"""Get the size of a Zstandard frame, including the header and optional checksum. |
| 98 |
|
| 99 |
frame_buffer |
| 100 |
A bytes-like object, it should start from the beginning of a frame, |
| 101 |
and contains at least one complete frame.""" |
| 102 |
frame_size = _lib.ZSTD_findFrameCompressedSize( |
| 103 |
_ffi.from_buffer(frame_buffer), len(frame_buffer) |
| 104 |
) |
| 105 |
if _lib.ZSTD_isError(frame_size): |
| 106 |
raise ZstdError( |
| 107 |
"Error when finding the compressed size of a Zstandard frame. " |
| 108 |
"Ensure the frame_buffer argument starts from the " |
| 109 |
"beginning of a frame, and its length is not less than this " |
| 110 |
"complete frame. Zstd error message: %s." |
| 111 |
% _ffi.string(_lib.ZSTD_getErrorName(frame_size)).decode() |
| 112 |
) |
| 113 |
return frame_size |
| 114 |
|
| 115 |
|
| 116 |
def _calculate_samples_stats(samples_bytes, samples_sizes): |
| 117 |
chunks_number = len(samples_sizes) |
| 118 |
# Prepare chunk_sizes |
| 119 |
chunk_sizes = _new_nonzero("size_t[]", chunks_number) |
| 120 |
sizes_sum = _nbytes(samples_bytes) |
| 121 |
for i, size in enumerate(samples_sizes): |
| 122 |
try: |
| 123 |
chunk_sizes[i] = size |
| 124 |
except OverflowError: |
| 125 |
sizes_sum = -1 |
| 126 |
break |
| 127 |
sizes_sum -= size |
| 128 |
if sizes_sum != 0: |
| 129 |
raise ValueError( |
| 130 |
"The samples size tuple doesn't match the concatenation's size." |
| 131 |
) |
| 132 |
return chunk_sizes, chunks_number |
| 133 |
|
| 134 |
|
| 135 |
def _clinic_train_dict(*args): |
| 136 |
_clinic_check("train_dict", args, 0, bytes) |
| 137 |
_clinic_check("train_dict", args, 1, tuple) |
| 138 |
|
| 139 |
|
| 140 |
def train_dict(samples_bytes, samples_sizes, dict_size): |
| 141 |
"""Train a Zstandard dictionary on sample data. |
| 142 |
|
| 143 |
samples_bytes |
| 144 |
Concatenation of samples. |
| 145 |
samples_sizes |
| 146 |
Tuple of samples' sizes. |
| 147 |
dict_size |
| 148 |
The size of the dictionary.""" |
| 149 |
_clinic_train_dict(samples_bytes, samples_sizes, dict_size) |
| 150 |
|
| 151 |
# Check arguments |
| 152 |
_check_int(dict_size) |
| 153 |
if dict_size <= 0: |
| 154 |
raise ValueError("dict_size argument should be positive number.") |
| 155 |
|
| 156 |
# Check that the samples are valid and get their sizes |
| 157 |
chunk_sizes, chunks_number = _calculate_samples_stats(samples_bytes, samples_sizes) |
| 158 |
|
| 159 |
# Allocate dict buffer |
| 160 |
dst_dict_bytes = _new_nonzero("char[]", dict_size) |
| 161 |
if dst_dict_bytes == _ffi.NULL: |
| 162 |
raise MemoryError |
| 163 |
|
| 164 |
# Train the dictionary |
| 165 |
zstd_ret = _lib.ZDICT_trainFromBuffer( |
| 166 |
dst_dict_bytes, |
| 167 |
dict_size, |
| 168 |
_ffi.from_buffer(samples_bytes), |
| 169 |
chunk_sizes, |
| 170 |
chunks_number, |
| 171 |
) |
| 172 |
if _lib.ZDICT_isError(zstd_ret): |
| 173 |
_set_zstd_error(_ErrorType.ERR_TRAIN_DICT, zstd_ret) |
| 174 |
|
| 175 |
# Resize dict_buffer |
| 176 |
return _ffi.buffer(dst_dict_bytes)[:zstd_ret] |
| 177 |
|
| 178 |
|
| 179 |
def _clinic_finalize_dict(*args): |
| 180 |
_clinic_check("finalize_dict", args, 0, bytes) |
| 181 |
_clinic_check("finalize_dict", args, 1, bytes) |
| 182 |
_clinic_check("finalize_dict", args, 2, tuple) |
| 183 |
|
| 184 |
|
| 185 |
def finalize_dict( |
| 186 |
custom_dict_bytes, samples_bytes, samples_sizes, dict_size, compression_level |
| 187 |
): |
| 188 |
"""Finalize a Zstandard dictionary. |
| 189 |
|
| 190 |
custom_dict_bytes |
| 191 |
Custom dictionary content. |
| 192 |
samples_bytes |
| 193 |
Concatenation of samples. |
| 194 |
samples_sizes |
| 195 |
Tuple of samples' sizes. |
| 196 |
dict_size |
| 197 |
The size of the dictionary. |
| 198 |
compression_level |
| 199 |
Optimize for a specific Zstandard compression level, 0 means default.""" |
| 200 |
_clinic_finalize_dict( |
| 201 |
custom_dict_bytes, samples_bytes, samples_sizes, dict_size, compression_level |
| 202 |
) |
| 203 |
|
| 204 |
# Check arguments |
| 205 |
_check_int(dict_size) |
| 206 |
if dict_size <= 0: |
| 207 |
raise ValueError("dict_size argument should be positive number.") |
| 208 |
|
| 209 |
# Check that the samples are valid and get their sizes |
| 210 |
chunk_sizes, chunks_number = _calculate_samples_stats(samples_bytes, samples_sizes) |
| 211 |
|
| 212 |
# Allocate dict buffer |
| 213 |
dst_dict_bytes = _new_nonzero("char[]", dict_size) |
| 214 |
if dst_dict_bytes == _ffi.NULL: |
| 215 |
raise MemoryError |
| 216 |
|
| 217 |
# Parameters |
| 218 |
params = _new_nonzero("ZDICT_params_t *") |
| 219 |
if params == _ffi.NULL: |
| 220 |
raise MemoryError |
| 221 |
# Optimize for a specific Zstandard compression level, 0 means default. |
| 222 |
params.compressionLevel = compression_level |
| 223 |
# Write log to stderr, 0 = none. |
| 224 |
params.notificationLevel = 0 |
| 225 |
# Force dictID value, 0 means auto mode (32-bits random value). |
| 226 |
params.dictID = 0 |
| 227 |
|
| 228 |
# Finalize the dictionary |
| 229 |
zstd_ret = _lib.ZDICT_finalizeDictionary( |
| 230 |
dst_dict_bytes, |
| 231 |
dict_size, |
| 232 |
_ffi.from_buffer(custom_dict_bytes), |
| 233 |
_nbytes(custom_dict_bytes), |
| 234 |
_ffi.from_buffer(samples_bytes), |
| 235 |
chunk_sizes, |
| 236 |
chunks_number, |
| 237 |
params[0], |
| 238 |
) |
| 239 |
|
| 240 |
# Check Zstandard dict error |
| 241 |
if _lib.ZDICT_isError(zstd_ret): |
| 242 |
_set_zstd_error(_ErrorType.ERR_FINALIZE_DICT, zstd_ret) |
| 243 |
|
| 244 |
# Resize dict_buffer |
| 245 |
return _ffi.buffer(dst_dict_bytes)[:zstd_ret] |