| 1 |
"""Python bindings to the Zstandard (zstd) compression library (RFC-8878).""" |
| 2 |
|
| 3 |
import sys |
| 4 |
if not ((3, 10) <= sys.version_info < (3, 14)): |
| 5 |
raise RuntimeError(f"Unsupported Python version: {sys.version}") |
| 6 |
|
| 7 |
__all__ = ( |
| 8 |
# backports.zstd |
| 9 |
'COMPRESSION_LEVEL_DEFAULT', |
| 10 |
'compress', |
| 11 |
'CompressionParameter', |
| 12 |
'decompress', |
| 13 |
'DecompressionParameter', |
| 14 |
'finalize_dict', |
| 15 |
'get_frame_info', |
| 16 |
'Strategy', |
| 17 |
'train_dict', |
| 18 |
|
| 19 |
# backports.zstd._shutil |
| 20 |
'register_shutil', |
| 21 |
|
| 22 |
# backports.zstd._zstdfile |
| 23 |
'open', |
| 24 |
'ZstdFile', |
| 25 |
|
| 26 |
# backports.zstd._zstd |
| 27 |
'get_frame_size', |
| 28 |
'zstd_version', |
| 29 |
'zstd_version_info', |
| 30 |
'ZstdCompressor', |
| 31 |
'ZstdDecompressor', |
| 32 |
'ZstdDict', |
| 33 |
'ZstdError', |
| 34 |
) |
| 35 |
|
| 36 |
import backports.zstd._zstd as _zstd |
| 37 |
import enum |
| 38 |
from backports.zstd._zstd import (ZstdCompressor, ZstdDecompressor, ZstdDict, ZstdError, |
| 39 |
get_frame_size, zstd_version) |
| 40 |
from backports.zstd._zstdfile import ZstdFile, open, _nbytes |
| 41 |
|
| 42 |
# zstd_version_number is (MAJOR * 100 * 100 + MINOR * 100 + RELEASE) |
| 43 |
zstd_version_info = (*divmod(_zstd.zstd_version_number // 100, 100), |
| 44 |
_zstd.zstd_version_number % 100) |
| 45 |
"""Version number of the runtime zstd library as a tuple of integers.""" |
| 46 |
|
| 47 |
if zstd_version_info < (1, 4, 5): |
| 48 |
raise RuntimeError("zstd version is too old") |
| 49 |
|
| 50 |
COMPRESSION_LEVEL_DEFAULT = _zstd.ZSTD_CLEVEL_DEFAULT |
| 51 |
"""The default compression level for Zstandard, currently '3'.""" |
| 52 |
|
| 53 |
|
| 54 |
class FrameInfo: |
| 55 |
"""Information about a Zstandard frame.""" |
| 56 |
|
| 57 |
__slots__ = 'decompressed_size', 'dictionary_id' |
| 58 |
|
| 59 |
def __init__(self, decompressed_size, dictionary_id): |
| 60 |
super().__setattr__('decompressed_size', decompressed_size) |
| 61 |
super().__setattr__('dictionary_id', dictionary_id) |
| 62 |
|
| 63 |
def __repr__(self): |
| 64 |
return (f'FrameInfo(decompressed_size={self.decompressed_size}, ' |
| 65 |
f'dictionary_id={self.dictionary_id})') |
| 66 |
|
| 67 |
def __setattr__(self, name, _): |
| 68 |
raise AttributeError(f"can't set attribute {name!r}") |
| 69 |
|
| 70 |
|
| 71 |
def get_frame_info(frame_buffer): |
| 72 |
"""Get Zstandard frame information from a frame header. |
| 73 |
|
| 74 |
*frame_buffer* is a bytes-like object. It should start from the |
| 75 |
beginning of a frame, and needs to include at least the frame header |
| 76 |
(6 to 18 bytes). |
| 77 |
|
| 78 |
The returned FrameInfo object has two attributes. |
| 79 |
'decompressed_size' is the size in bytes of the data in the frame when |
| 80 |
decompressed, or None when the decompressed size is unknown. |
| 81 |
'dictionary_id' is an int in the range (0, 2**32). The special value 0 |
| 82 |
means that the dictionary ID was not recorded in the frame header, |
| 83 |
the frame may or may not need a dictionary to be decoded, |
| 84 |
and the ID of such a dictionary is not specified. |
| 85 |
""" |
| 86 |
return FrameInfo(*_zstd.get_frame_info(frame_buffer)) |
| 87 |
|
| 88 |
|
| 89 |
def train_dict(samples, dict_size): |
| 90 |
"""Return a ZstdDict representing a trained Zstandard dictionary. |
| 91 |
|
| 92 |
*samples* is an iterable of samples, where a sample is a bytes-like |
| 93 |
object representing a file. |
| 94 |
|
| 95 |
*dict_size* is the dictionary's maximum size, in bytes. |
| 96 |
""" |
| 97 |
if not isinstance(dict_size, int): |
| 98 |
ds_cls = type(dict_size).__qualname__ |
| 99 |
raise TypeError(f'dict_size must be an int object, not {ds_cls!r}.') |
| 100 |
|
| 101 |
samples = tuple(samples) |
| 102 |
chunks = b''.join(samples) |
| 103 |
chunk_sizes = tuple(_nbytes(sample) for sample in samples) |
| 104 |
if not chunks: |
| 105 |
raise ValueError("samples contained no data; can't train dictionary.") |
| 106 |
dict_content = _zstd.train_dict(chunks, chunk_sizes, dict_size) |
| 107 |
return ZstdDict(dict_content) |
| 108 |
|
| 109 |
|
| 110 |
def finalize_dict(zstd_dict, /, samples, dict_size, level): |
| 111 |
"""Return a ZstdDict representing a finalized Zstandard dictionary. |
| 112 |
|
| 113 |
Given a custom content as a basis for dictionary, and a set of samples, |
| 114 |
finalize *zstd_dict* by adding headers and statistics according to the |
| 115 |
Zstandard dictionary format. |
| 116 |
|
| 117 |
You may compose an effective dictionary content by hand, which is used |
| 118 |
as basis dictionary, and use some samples to finalize a dictionary. The |
| 119 |
basis dictionary may be a "raw content" dictionary. See *is_raw* in |
| 120 |
ZstdDict. |
| 121 |
|
| 122 |
*samples* is an iterable of samples, where a sample is a bytes-like |
| 123 |
object representing a file. |
| 124 |
*dict_size* is the dictionary's maximum size, in bytes. |
| 125 |
*level* is the expected compression level. The statistics for each |
| 126 |
compression level differ, so tuning the dictionary to the compression |
| 127 |
level can provide improvements. |
| 128 |
""" |
| 129 |
|
| 130 |
if not isinstance(zstd_dict, ZstdDict): |
| 131 |
raise TypeError('zstd_dict argument should be a ZstdDict object.') |
| 132 |
if not isinstance(dict_size, int): |
| 133 |
raise TypeError('dict_size argument should be an int object.') |
| 134 |
if not isinstance(level, int): |
| 135 |
raise TypeError('level argument should be an int object.') |
| 136 |
|
| 137 |
samples = tuple(samples) |
| 138 |
chunks = b''.join(samples) |
| 139 |
chunk_sizes = tuple(_nbytes(sample) for sample in samples) |
| 140 |
if not chunks: |
| 141 |
raise ValueError("The samples are empty content, can't finalize the " |
| 142 |
"dictionary.") |
| 143 |
dict_content = _zstd.finalize_dict(zstd_dict.dict_content, chunks, |
| 144 |
chunk_sizes, dict_size, level) |
| 145 |
return ZstdDict(dict_content) |
| 146 |
|
| 147 |
|
| 148 |
def compress(data, level=None, options=None, zstd_dict=None): |
| 149 |
"""Return Zstandard compressed *data* as bytes. |
| 150 |
|
| 151 |
*level* is an int specifying the compression level to use, defaulting to |
| 152 |
COMPRESSION_LEVEL_DEFAULT ('3'). |
| 153 |
*options* is a dict object that contains advanced compression |
| 154 |
parameters. See CompressionParameter for more on options. |
| 155 |
*zstd_dict* is a ZstdDict object, a pre-trained Zstandard dictionary. |
| 156 |
See the function train_dict for how to train a ZstdDict on sample data. |
| 157 |
|
| 158 |
For incremental compression, use a ZstdCompressor instead. |
| 159 |
""" |
| 160 |
comp = ZstdCompressor(level=level, options=options, zstd_dict=zstd_dict) |
| 161 |
return comp.compress(data, mode=ZstdCompressor.FLUSH_FRAME) |
| 162 |
|
| 163 |
|
| 164 |
def decompress(data, zstd_dict=None, options=None): |
| 165 |
"""Decompress one or more frames of Zstandard compressed *data*. |
| 166 |
|
| 167 |
*zstd_dict* is a ZstdDict object, a pre-trained Zstandard dictionary. |
| 168 |
See the function train_dict for how to train a ZstdDict on sample data. |
| 169 |
*options* is a dict object that contains advanced compression |
| 170 |
parameters. See DecompressionParameter for more on options. |
| 171 |
|
| 172 |
For incremental decompression, use a ZstdDecompressor instead. |
| 173 |
""" |
| 174 |
results = [] |
| 175 |
while True: |
| 176 |
decomp = ZstdDecompressor(options=options, zstd_dict=zstd_dict) |
| 177 |
results.append(decomp.decompress(data)) |
| 178 |
if not decomp.eof: |
| 179 |
raise ZstdError('Compressed data ended before the ' |
| 180 |
'end-of-stream marker was reached') |
| 181 |
data = decomp.unused_data |
| 182 |
if not data: |
| 183 |
break |
| 184 |
return b''.join(results) |
| 185 |
|
| 186 |
|
| 187 |
class CompressionParameter(enum.IntEnum): |
| 188 |
"""Compression parameters.""" |
| 189 |
|
| 190 |
compression_level = _zstd.ZSTD_c_compressionLevel |
| 191 |
window_log = _zstd.ZSTD_c_windowLog |
| 192 |
hash_log = _zstd.ZSTD_c_hashLog |
| 193 |
chain_log = _zstd.ZSTD_c_chainLog |
| 194 |
search_log = _zstd.ZSTD_c_searchLog |
| 195 |
min_match = _zstd.ZSTD_c_minMatch |
| 196 |
target_length = _zstd.ZSTD_c_targetLength |
| 197 |
strategy = _zstd.ZSTD_c_strategy |
| 198 |
|
| 199 |
enable_long_distance_matching = _zstd.ZSTD_c_enableLongDistanceMatching |
| 200 |
ldm_hash_log = _zstd.ZSTD_c_ldmHashLog |
| 201 |
ldm_min_match = _zstd.ZSTD_c_ldmMinMatch |
| 202 |
ldm_bucket_size_log = _zstd.ZSTD_c_ldmBucketSizeLog |
| 203 |
ldm_hash_rate_log = _zstd.ZSTD_c_ldmHashRateLog |
| 204 |
|
| 205 |
content_size_flag = _zstd.ZSTD_c_contentSizeFlag |
| 206 |
checksum_flag = _zstd.ZSTD_c_checksumFlag |
| 207 |
dict_id_flag = _zstd.ZSTD_c_dictIDFlag |
| 208 |
|
| 209 |
nb_workers = _zstd.ZSTD_c_nbWorkers |
| 210 |
job_size = _zstd.ZSTD_c_jobSize |
| 211 |
overlap_log = _zstd.ZSTD_c_overlapLog |
| 212 |
|
| 213 |
def bounds(self): |
| 214 |
"""Return the (lower, upper) int bounds of a compression parameter. |
| 215 |
|
| 216 |
Both the lower and upper bounds are inclusive. |
| 217 |
""" |
| 218 |
return _zstd.get_param_bounds(self.value, is_compress=True) |
| 219 |
|
| 220 |
|
| 221 |
class DecompressionParameter(enum.IntEnum): |
| 222 |
"""Decompression parameters.""" |
| 223 |
|
| 224 |
window_log_max = _zstd.ZSTD_d_windowLogMax |
| 225 |
|
| 226 |
def bounds(self): |
| 227 |
"""Return the (lower, upper) int bounds of a decompression parameter. |
| 228 |
|
| 229 |
Both the lower and upper bounds are inclusive. |
| 230 |
""" |
| 231 |
return _zstd.get_param_bounds(self.value, is_compress=False) |
| 232 |
|
| 233 |
|
| 234 |
class Strategy(enum.IntEnum): |
| 235 |
"""Compression strategies, listed from fastest to strongest. |
| 236 |
|
| 237 |
Note that new strategies might be added in the future. |
| 238 |
Only the order (from fast to strong) is guaranteed, |
| 239 |
the numeric value might change. |
| 240 |
""" |
| 241 |
|
| 242 |
fast = _zstd.ZSTD_fast |
| 243 |
dfast = _zstd.ZSTD_dfast |
| 244 |
greedy = _zstd.ZSTD_greedy |
| 245 |
lazy = _zstd.ZSTD_lazy |
| 246 |
lazy2 = _zstd.ZSTD_lazy2 |
| 247 |
btlazy2 = _zstd.ZSTD_btlazy2 |
| 248 |
btopt = _zstd.ZSTD_btopt |
| 249 |
btultra = _zstd.ZSTD_btultra |
| 250 |
btultra2 = _zstd.ZSTD_btultra2 |
| 251 |
|
| 252 |
|
| 253 |
# Check validity of the CompressionParameter & DecompressionParameter types |
| 254 |
_zstd.set_parameter_types(CompressionParameter, DecompressionParameter) |
| 255 |
|
| 256 |
|
| 257 |
# Lazy loading |
| 258 |
def __getattr__(name): |
| 259 |
if name == "register_shutil": |
| 260 |
from backports.zstd._shutil import register_shutil |
| 261 |
return register_shutil |
| 262 |
raise AttributeError(f"module {__name__!r} has no attribute {name!r}") |