| 1 |
from contextlib import suppress |
| 2 |
from threading import Lock |
| 3 |
|
| 4 |
from backports.zstd._cffi._blocks_output_buffer import BlocksOutputBuffer |
| 5 |
from backports.zstd._cffi._common import ( |
| 6 |
_PARAMETER_TYPES, |
| 7 |
ZstdError, |
| 8 |
_check_int, |
| 9 |
_DictionaryType, |
| 10 |
_ErrorType, |
| 11 |
_ffi, |
| 12 |
_lib, |
| 13 |
_new_nonzero, |
| 14 |
_set_parameter_error, |
| 15 |
_set_zstd_error, |
| 16 |
) |
| 17 |
from backports.zstd._cffi.buffer import ( |
| 18 |
_OutputBuffer_Finish, |
| 19 |
_OutputBuffer_Grow, |
| 20 |
_OutputBuffer_InitAndGrow, |
| 21 |
_OutputBuffer_ReachedMaxLength, |
| 22 |
) |
| 23 |
from backports.zstd._cffi.zstddict import _Py_parse_zstd_dict |
| 24 |
|
| 25 |
|
| 26 |
class ZstdDecompressor: |
| 27 |
"""Create a decompressor object for decompressing data incrementally. |
| 28 |
|
| 29 |
zstd_dict |
| 30 |
A ZstdDict object, a pre-trained Zstandard dictionary. |
| 31 |
options |
| 32 |
A dict object that contains advanced decompression parameters. |
| 33 |
|
| 34 |
Thread-safe at method level. For one-shot decompression, use the |
| 35 |
decompress() function instead.""" |
| 36 |
|
| 37 |
def __init__(self, zstd_dict=None, options=None): |
| 38 |
self._input_buffer = _ffi.NULL |
| 39 |
self._input_buffer_size = 0 |
| 40 |
self._in_begin = -1 |
| 41 |
self._in_end = -1 |
| 42 |
self._unused_data = _ffi.NULL |
| 43 |
self._eof = False |
| 44 |
self._lock = Lock() |
| 45 |
|
| 46 |
# needs_input flag |
| 47 |
self._needs_input = True |
| 48 |
|
| 49 |
# Decompression context |
| 50 |
self._dctx = _lib.ZSTD_createDCtx() |
| 51 |
if self._dctx == _ffi.NULL: |
| 52 |
raise ZstdError("Unable to create ZSTD_DCtx instance.") |
| 53 |
|
| 54 |
# Load Zstandard dictionary to decompression context |
| 55 |
if zstd_dict is not None: |
| 56 |
self._zstd_load_d_dict(zstd_dict) |
| 57 |
|
| 58 |
# Set options dictionary |
| 59 |
if options is not None: |
| 60 |
self._zstd_set_d_parameters(options) |
| 61 |
|
| 62 |
def _zstd_load_d_dict(self, dict_): |
| 63 |
# When decompressing, use digested dictionary by default. |
| 64 |
zd, type_ = _Py_parse_zstd_dict(dict_, _DictionaryType.DICT_TYPE_DIGESTED) |
| 65 |
with self._lock: |
| 66 |
self._zstd_load_impl(zd, type_) |
| 67 |
|
| 68 |
def _zstd_load_impl(self, zd, type_): |
| 69 |
if type_ == _DictionaryType.DICT_TYPE_DIGESTED: |
| 70 |
# Get ZSTD_DDict |
| 71 |
d_dict = zd._get_ddict() |
| 72 |
# Reference a prepared dictionary |
| 73 |
zstd_ret = _lib.ZSTD_DCtx_refDDict(self._dctx, d_dict) |
| 74 |
elif type_ == _DictionaryType.DICT_TYPE_UNDIGESTED: |
| 75 |
# Load a dictionary |
| 76 |
zstd_ret = _lib.ZSTD_DCtx_loadDictionary( |
| 77 |
self._dctx, _ffi.from_buffer(zd._dict_content), len(zd._dict_content) |
| 78 |
) |
| 79 |
elif type_ == _DictionaryType.DICT_TYPE_PREFIX: |
| 80 |
# Load a prefix |
| 81 |
zstd_ret = _lib.ZSTD_DCtx_refPrefix( |
| 82 |
self._dctx, _ffi.from_buffer(zd._dict_content), len(zd._dict_content) |
| 83 |
) |
| 84 |
else: |
| 85 |
raise SystemError("Unreachable") |
| 86 |
|
| 87 |
# Check error |
| 88 |
if _lib.ZSTD_isError(zstd_ret): |
| 89 |
_set_zstd_error(_ErrorType.ERR_LOAD_D_DICT, zstd_ret) |
| 90 |
|
| 91 |
def _zstd_set_d_parameters(self, options): |
| 92 |
if not isinstance(options, dict): |
| 93 |
raise TypeError( |
| 94 |
"ZstdDecompressor() argument 'options' must be dict, not %s" |
| 95 |
% options.__class__.__name__ |
| 96 |
) |
| 97 |
|
| 98 |
for key, value in options.items(): |
| 99 |
# Check key type |
| 100 |
if isinstance(key, _PARAMETER_TYPES["compression"]): |
| 101 |
raise TypeError( |
| 102 |
"decompression options dictionary key must not be a " |
| 103 |
"CompressionParameter attribute" |
| 104 |
) |
| 105 |
|
| 106 |
_check_int(key) |
| 107 |
_check_int(value) |
| 108 |
|
| 109 |
# Set parameter to compression context |
| 110 |
try: |
| 111 |
zstd_ret = _lib.ZSTD_DCtx_setParameter(self._dctx, key, value) |
| 112 |
except OverflowError: |
| 113 |
_set_parameter_error(False, key, value) |
| 114 |
|
| 115 |
# Check error |
| 116 |
if _lib.ZSTD_isError(zstd_ret): |
| 117 |
_set_parameter_error(False, key, value) |
| 118 |
|
| 119 |
def __del__(self): |
| 120 |
with suppress(AttributeError): |
| 121 |
_lib.ZSTD_freeDCtx(self._dctx) |
| 122 |
self._dctx = _ffi.NULL |
| 123 |
|
| 124 |
@property |
| 125 |
def unused_data(self): |
| 126 |
"""A bytes object of un-consumed input data. |
| 127 |
|
| 128 |
When ZstdDecompressor object stops after a frame is |
| 129 |
decompressed, unused input data after the frame. Otherwise this |
| 130 |
will be b''.""" |
| 131 |
with self._lock: |
| 132 |
if not self._eof: |
| 133 |
return b"" |
| 134 |
if self._unused_data == _ffi.NULL: |
| 135 |
if self._input_buffer == _ffi.NULL: |
| 136 |
self._unused_data = b"" |
| 137 |
else: |
| 138 |
self._unused_data = _ffi.buffer(self._input_buffer)[ |
| 139 |
self._in_begin : self._in_end |
| 140 |
] |
| 141 |
return self._unused_data |
| 142 |
|
| 143 |
@property |
| 144 |
def eof(self): |
| 145 |
"""True means the end of the first frame has been reached. If decompress data |
| 146 |
after that, an EOFError exception will be raised.""" |
| 147 |
return self._eof |
| 148 |
|
| 149 |
@property |
| 150 |
def needs_input(self): |
| 151 |
"""If the max_length output limit in .decompress() method has been reached, |
| 152 |
and the decompressor has (or may has) unconsumed input data, it will be set |
| 153 |
to False. In this case, passing b'' to the .decompress() method may output |
| 154 |
further data.""" |
| 155 |
return self._needs_input |
| 156 |
|
| 157 |
def decompress(self, data, max_length=-1): |
| 158 |
"""Decompress *data*, returning uncompressed bytes if possible, or b'' otherwise. |
| 159 |
|
| 160 |
data |
| 161 |
A bytes-like object, Zstandard data to be decompressed. |
| 162 |
max_length |
| 163 |
Maximum size of returned data. When it is negative, the size of |
| 164 |
output buffer is unlimited. When it is nonnegative, returns at |
| 165 |
most max_length bytes of decompressed data. |
| 166 |
|
| 167 |
If *max_length* is nonnegative, returns at most *max_length* bytes |
| 168 |
of decompressed data. If this limit is reached and further output |
| 169 |
can be produced, *self.needs_input* will be set to ``False``. In |
| 170 |
this case, the next call to *decompress()* may provide *data* as b'' |
| 171 |
to obtain more of the output. |
| 172 |
|
| 173 |
If all of the input data was decompressed and returned (either |
| 174 |
because this was less than *max_length* bytes, or because |
| 175 |
*max_length* was negative), *self.needs_input* will be set to True. |
| 176 |
|
| 177 |
Attempting to decompress data after the end of a frame is reached |
| 178 |
raises an EOFError. Any data found after the end of the frame is |
| 179 |
ignored and saved in the self.unused_data attribute.""" |
| 180 |
with self._lock: |
| 181 |
return self._stream_decompress_lock_held(data, max_length) |
| 182 |
|
| 183 |
def _stream_decompress_lock_held(self, data, max_length): |
| 184 |
in_ = _new_nonzero("ZSTD_inBuffer *") |
| 185 |
if in_ == _ffi.NULL: |
| 186 |
raise MemoryError |
| 187 |
|
| 188 |
try: |
| 189 |
# Check .eof flag |
| 190 |
if self._eof: |
| 191 |
raise EOFError("Already at the end of a Zstandard frame.") |
| 192 |
|
| 193 |
# Prepare input buffer w/wo unconsumed data |
| 194 |
if self._in_begin == self._in_end: |
| 195 |
# No unconsumed data |
| 196 |
use_input_buffer = False |
| 197 |
in_.src = _ffi.from_buffer(data) |
| 198 |
in_.size = len(data) |
| 199 |
in_.pos = 0 |
| 200 |
elif len(data) == 0: |
| 201 |
# Has unconsumed data, fast path for b'' |
| 202 |
use_input_buffer = True |
| 203 |
in_.src = self._input_buffer + self._in_begin |
| 204 |
in_.size = self._in_end - self._in_begin |
| 205 |
in_.pos = 0 |
| 206 |
else: |
| 207 |
# Has unconsumed data |
| 208 |
use_input_buffer = True |
| 209 |
|
| 210 |
# Unconsumed data size in input_buffer |
| 211 |
used_now = self._in_end - self._in_begin |
| 212 |
|
| 213 |
# Number of bytes we can append to input buffer |
| 214 |
avail_now = self._input_buffer_size - self._in_end |
| 215 |
|
| 216 |
# Number of bytes we can append if we move existing contents to |
| 217 |
# beginning of buffer |
| 218 |
avail_total = self._input_buffer_size - used_now |
| 219 |
|
| 220 |
if avail_total < len(data): |
| 221 |
new_size = used_now + len(data) |
| 222 |
|
| 223 |
# Allocate with new size |
| 224 |
tmp = _new_nonzero("char[]", new_size) |
| 225 |
if tmp == _ffi.NULL: |
| 226 |
raise MemoryError |
| 227 |
|
| 228 |
# Copy unconsumed data to the beginning of new buffer |
| 229 |
_ffi.memmove(tmp, self._input_buffer + self._in_begin, used_now) |
| 230 |
|
| 231 |
# Switch to new buffer |
| 232 |
self._input_buffer = tmp |
| 233 |
self._input_buffer_size = new_size |
| 234 |
|
| 235 |
# Set begin & end position |
| 236 |
self._in_begin = 0 |
| 237 |
self._in_end = used_now |
| 238 |
|
| 239 |
elif avail_now < len(data): |
| 240 |
# Move unconsumed data to the beginning. |
| 241 |
_ffi.memmove( |
| 242 |
self._input_buffer, |
| 243 |
self._input_buffer + self._in_begin, |
| 244 |
used_now, |
| 245 |
) |
| 246 |
|
| 247 |
# Set begin & end position |
| 248 |
self._in_begin = 0 |
| 249 |
self._in_end = used_now |
| 250 |
|
| 251 |
# Copy data to input buffer |
| 252 |
_ffi.memmove( |
| 253 |
self._input_buffer + self._in_end, _ffi.from_buffer(data), len(data) |
| 254 |
) |
| 255 |
self._in_end += len(data) |
| 256 |
|
| 257 |
in_.src = self._input_buffer + self._in_begin |
| 258 |
in_.size = used_now + len(data) |
| 259 |
in_.pos = 0 |
| 260 |
|
| 261 |
# Decompress |
| 262 |
ret = self._decompress_lock_held(in_, max_length) |
| 263 |
|
| 264 |
# Unconsumed input data |
| 265 |
if in_.pos == in_.size: |
| 266 |
if len(ret) == max_length or self._eof: |
| 267 |
self._needs_input = False |
| 268 |
else: |
| 269 |
self._needs_input = True |
| 270 |
|
| 271 |
if use_input_buffer: |
| 272 |
# Clear input_buffer |
| 273 |
self._in_begin = 0 |
| 274 |
self._in_end = 0 |
| 275 |
|
| 276 |
else: |
| 277 |
data_size = in_.size - in_.pos |
| 278 |
|
| 279 |
self._needs_input = False |
| 280 |
|
| 281 |
if not use_input_buffer: |
| 282 |
# Discard buffer if it's too small |
| 283 |
# (resizing it may needlessly copy the current contents) |
| 284 |
if ( |
| 285 |
self._input_buffer != _ffi.NULL |
| 286 |
and self._input_buffer_size < data_size |
| 287 |
): |
| 288 |
self._input_buffer = _ffi.NULL |
| 289 |
self._input_buffer_size = 0 |
| 290 |
|
| 291 |
# Allocate if necessary |
| 292 |
if self._input_buffer == _ffi.NULL: |
| 293 |
self._input_buffer = _new_nonzero("char[]", data_size) |
| 294 |
if self._input_buffer == _ffi.NULL: |
| 295 |
raise MemoryError |
| 296 |
self._input_buffer_size = data_size |
| 297 |
|
| 298 |
# Copy unconsumed data |
| 299 |
_ffi.memmove(self._input_buffer, in_.src + in_.pos, data_size) |
| 300 |
self._in_begin = 0 |
| 301 |
self._in_end = data_size |
| 302 |
|
| 303 |
else: |
| 304 |
# Use input buffer |
| 305 |
self._in_begin += in_.pos |
| 306 |
|
| 307 |
return ret |
| 308 |
|
| 309 |
except: |
| 310 |
# Reset decompressor's states/session |
| 311 |
self._decompressor_reset_session_lock_held() |
| 312 |
raise |
| 313 |
|
| 314 |
def _decompress_lock_held(self, in_, max_length): |
| 315 |
out = _new_nonzero("ZSTD_outBuffer *") |
| 316 |
if out == _ffi.NULL: |
| 317 |
raise MemoryError |
| 318 |
buffer = BlocksOutputBuffer() |
| 319 |
|
| 320 |
# Initialize the output buffer |
| 321 |
_OutputBuffer_InitAndGrow(buffer, out, max_length) |
| 322 |
|
| 323 |
while True: |
| 324 |
# Decompress |
| 325 |
zstd_ret = _lib.ZSTD_decompressStream(self._dctx, out, in_) |
| 326 |
|
| 327 |
# Check error |
| 328 |
if _lib.ZSTD_isError(zstd_ret): |
| 329 |
_set_zstd_error(_ErrorType.ERR_DECOMPRESS, zstd_ret) |
| 330 |
|
| 331 |
# Set .eof flag |
| 332 |
if zstd_ret == 0: |
| 333 |
# Stop when a frame is decompressed |
| 334 |
self._eof = 1 |
| 335 |
break |
| 336 |
|
| 337 |
# Need to check out before in. Maybe zstd's internal buffer still has |
| 338 |
# a few bytes that can be output, grow the buffer and continue. |
| 339 |
if out.pos == out.size: |
| 340 |
# Output buffer exhausted |
| 341 |
|
| 342 |
# Output buffer reached max_length |
| 343 |
if _OutputBuffer_ReachedMaxLength(buffer, out): |
| 344 |
break |
| 345 |
|
| 346 |
# Grow output buffer |
| 347 |
_OutputBuffer_Grow(buffer, out) |
| 348 |
|
| 349 |
elif in_.pos == in_.size: |
| 350 |
# Finished |
| 351 |
break |
| 352 |
|
| 353 |
# Return a bytes object |
| 354 |
return _OutputBuffer_Finish(buffer, out) |
| 355 |
|
| 356 |
def _decompressor_reset_session_lock_held(self): |
| 357 |
# Reset variables |
| 358 |
self._in_begin = 0 |
| 359 |
self._in_end = 0 |
| 360 |
|
| 361 |
self._unused_data = _ffi.NULL |
| 362 |
|
| 363 |
# Reset variables in one operation |
| 364 |
self._needs_input = 1 |
| 365 |
self._eof = 0 |
| 366 |
|
| 367 |
# Resetting session is guaranteed to never fail |
| 368 |
_lib.ZSTD_DCtx_reset(self._dctx, _lib.ZSTD_reset_session_only) |