Debian Codegraph @

src/python/backports/zstd/_cffi/compressor.py

raw
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 _nbytes,
14 _new_nonzero,
15 _set_parameter_error,
16 _set_zstd_error,
17 )
18 from backports.zstd._cffi.buffer import (
19 _OutputBuffer_Finish,
20 _OutputBuffer_Grow,
21 _OutputBuffer_InitAndGrow,
22 _OutputBuffer_InitWithSize,
23 )
24 from backports.zstd._cffi.zstddict import _Py_parse_zstd_dict
25
26
27 def _zstd_contentsize_converter(size):
28 if size is None:
29 return _lib.ZSTD_CONTENTSIZE_UNKNOWN
30
31 if size < 0 or size >= _lib.ZSTD_CONTENTSIZE_ERROR:
32 raise ValueError(
33 "size argument should be a positive int less "
34 "than %u" % _lib.ZSTD_CONTENTSIZE_ERROR
35 )
36
37 return size
38
39
40 class ZstdCompressor:
41 """Create a compressor object for compressing data incrementally.
42
43 level
44 The compression level to use. Defaults to COMPRESSION_LEVEL_DEFAULT.
45 options
46 A dict object that contains advanced compression parameters.
47 zstd_dict
48 A ZstdDict object, a pre-trained Zstandard dictionary.
49
50 Thread-safe at method level. For one-shot compression, use the
51 compress() function instead."""
52
53 CONTINUE = _lib.ZSTD_e_continue
54 FLUSH_BLOCK = _lib.ZSTD_e_flush
55 FLUSH_FRAME = _lib.ZSTD_e_end
56
57 def __init__(self, level=None, options=None, zstd_dict=None):
58 self._compression_level = 0
59 self._use_multithread = False
60 self._lock = Lock()
61
62 # Compression context
63 self._cctx = _lib.ZSTD_createCCtx()
64 if self._cctx == _ffi.NULL:
65 raise ZstdError("Unable to create ZSTD_CCtx instance.")
66
67 # Last mode
68 self._last_mode = _lib.ZSTD_e_end
69
70 if level is not None and options is not None:
71 raise TypeError("Only one of level or options should be used.")
72
73 # Set compression level
74 if level is not None:
75 if not isinstance(level, int):
76 raise TypeError("invalid type for level, expected int")
77 try:
78 _check_int(level)
79 except OverflowError:
80 raise ValueError(
81 "illegal compression level; the valid range is [%d, %d]"
82 % (_lib.ZSTD_minCLevel(), _lib.ZSTD_maxCLevel())
83 )
84 self._zstd_set_c_level(level)
85
86 # Set options dictionary
87 if options is not None:
88 self._zstd_set_c_parameters(options)
89
90 # Load Zstandard dictionary to compression context
91 if zstd_dict is not None:
92 self._zstd_load_c_dict(zstd_dict)
93
94 @property
95 def last_mode(self):
96 """The last mode used to this compressor object, its value can be .CONTINUE,
97 .FLUSH_BLOCK, .FLUSH_FRAME. Initialized to .FLUSH_FRAME.
98
99 It can be used to get the current state of a compressor, such as, data
100 flushed, or a frame ended."""
101 return self._last_mode
102
103 def _zstd_set_c_level(self, level):
104 # Set integer compression level
105 min_level = _lib.ZSTD_minCLevel()
106 max_level = _lib.ZSTD_maxCLevel()
107 if level < min_level or level > max_level:
108 raise ValueError(
109 "illegal compression level %d; the valid range is [%d, %d]"
110 % (level, min_level, max_level)
111 )
112
113 # Save for generating ZSTD_CDICT
114 self._compression_level = level
115
116 # Set compressionLevel to compression context
117 zstd_ret = _lib.ZSTD_CCtx_setParameter(
118 self._cctx, _lib.ZSTD_c_compressionLevel, level
119 )
120
121 # Check error
122 if _lib.ZSTD_isError(zstd_ret):
123 _set_zstd_error(_ErrorType.ERR_SET_C_LEVEL, zstd_ret)
124
125 def _zstd_set_c_parameters(self, options):
126 if not isinstance(options, dict):
127 raise TypeError(
128 "ZstdCompressor() argument 'options' must be dict, not %s"
129 % options.__class__.__name__
130 )
131
132 for key, value in options.items():
133 # Check key type
134 if isinstance(key, _PARAMETER_TYPES["decompression"]):
135 raise TypeError(
136 "compression options dictionary key must not be a "
137 "DecompressionParameter attribute"
138 )
139
140 _check_int(key)
141 _check_int(value)
142
143 if key == _lib.ZSTD_c_compressionLevel:
144 self._zstd_set_c_level(value)
145 continue
146 if key == _lib.ZSTD_c_nbWorkers:
147 # From the zstd library docs:
148 # 1. When nbWorkers >= 1, triggers asynchronous mode when
149 # used with ZSTD_compressStream2().
150 # 2, Default value is `0`, aka "single-threaded mode" : no
151 # worker is spawned, compression is performed inside
152 # caller's thread, all invocations are blocking.
153 if value:
154 self._use_multithread = True
155
156 # Set parameter to compression context */
157 try:
158 zstd_ret = _lib.ZSTD_CCtx_setParameter(self._cctx, key, value)
159 except OverflowError:
160 _set_parameter_error(True, key, value)
161 if _lib.ZSTD_isError(zstd_ret):
162 _set_parameter_error(True, key, value)
163
164 def _zstd_load_c_dict(self, dict_):
165 # When compressing, use undigested dictionary by default.
166 zd, type_ = _Py_parse_zstd_dict(dict_, _DictionaryType.DICT_TYPE_UNDIGESTED)
167 with self._lock:
168 ret = self._zstd_load_impl(zd, type_)
169 return ret
170
171 def _zstd_load_impl(self, zd, type_):
172 if type_ == _DictionaryType.DICT_TYPE_DIGESTED:
173 # Get ZSTD_CDict
174 c_dict = zd._get_cdict(self._compression_level)
175 # Reference a prepared dictionary.
176 # It overrides some compression context's parameters.
177 zstd_ret = _lib.ZSTD_CCtx_refCDict(self._cctx, c_dict)
178 elif type_ == _DictionaryType.DICT_TYPE_UNDIGESTED:
179 # Load a dictionary.
180 # It doesn't override compression context's parameters.
181 zstd_ret = _lib.ZSTD_CCtx_loadDictionary(
182 self._cctx, _ffi.from_buffer(zd._dict_content), len(zd._dict_content)
183 )
184 elif type_ == _DictionaryType.DICT_TYPE_PREFIX:
185 # Load a prefix
186 zstd_ret = _lib.ZSTD_CCtx_refPrefix(
187 self._cctx, zd._dict_content, len(zd._dict_content)
188 )
189 else:
190 raise SystemError("Unreachable")
191
192 # Check error
193 if _lib.ZSTD_isError(zstd_ret):
194 _set_zstd_error(_ErrorType.ERR_LOAD_C_DICT, zstd_ret)
195
196 def __del__(self):
197 with suppress(AttributeError):
198 _lib.ZSTD_freeCCtx(self._cctx)
199 self._cctx = _ffi.NULL
200
201 def compress(self, data, mode=_lib.ZSTD_e_continue):
202 """Provide data to the compressor object.
203
204 mode
205 Can be these 3 values ZstdCompressor.CONTINUE,
206 ZstdCompressor.FLUSH_BLOCK, ZstdCompressor.FLUSH_FRAME
207
208 Return a chunk of compressed data if possible, or b'' otherwise.
209 When you have finished providing data to the compressor, call the
210 flush() method to finish the compression process."""
211 if (
212 mode != _lib.ZSTD_e_continue
213 and mode != _lib.ZSTD_e_flush
214 and mode != _lib.ZSTD_e_end
215 ):
216 raise ValueError(
217 "mode argument wrong value, it should be one of "
218 "ZstdCompressor.CONTINUE, ZstdCompressor.FLUSH_BLOCK, "
219 "ZstdCompressor.FLUSH_FRAME."
220 )
221
222 # Thread-safe code
223 with self._lock:
224 try:
225 # Compress
226 if self._use_multithread and mode == _lib.ZSTD_e_continue:
227 ret = self._compress_mt_continue_lock_held(data)
228 else:
229 ret = self._compress_lock_held(data, mode)
230 self._last_mode = mode
231 return ret
232 except:
233 self._last_mode = _lib.ZSTD_e_end
234 _lib.ZSTD_CCtx_reset(self._cctx, _lib.ZSTD_reset_session_only)
235 raise
236
237 def _compress_lock_held(self, data, end_directive):
238 in_ = _new_nonzero("ZSTD_inBuffer *")
239 if in_ == _ffi.NULL:
240 raise MemoryError
241 out = _new_nonzero("ZSTD_outBuffer *")
242 if out == _ffi.NULL:
243 raise MemoryError
244 buffer = BlocksOutputBuffer()
245
246 # Prepare input & output buffers
247 if data:
248 in_.src = _ffi.from_buffer(data)
249 in_.size = _nbytes(data)
250 in_.pos = 0
251 else:
252 in_.src = _ffi.NULL
253 in_.size = 0
254 in_.pos = 0
255
256 # Calculate output buffer's size
257 output_buffer_size = _lib.ZSTD_compressBound(in_.size)
258 _OutputBuffer_InitWithSize(buffer, out, -1, output_buffer_size)
259
260 # Zstandard stream compress
261 while True:
262 zstd_ret = _lib.ZSTD_compressStream2(self._cctx, out, in_, end_directive)
263
264 # Check error
265 if _lib.ZSTD_isError(zstd_ret):
266 _set_zstd_error(_ErrorType.ERR_COMPRESS, zstd_ret)
267
268 # Finished
269 if zstd_ret == 0:
270 break
271
272 # Output buffer should be exhausted, grow the buffer.
273 if out.pos == out.size:
274 _OutputBuffer_Grow(buffer, out)
275
276 # Return a bytes object
277 return _OutputBuffer_Finish(buffer, out)
278
279 def _compress_mt_continue_lock_held(self, data):
280 in_ = _new_nonzero("ZSTD_inBuffer *")
281 if in_ == _ffi.NULL:
282 raise MemoryError
283 out = _new_nonzero("ZSTD_outBuffer *")
284 if out == _ffi.NULL:
285 raise MemoryError
286 buffer = BlocksOutputBuffer()
287
288 # Prepare input & output buffers
289 in_.src = _ffi.from_buffer(data)
290 in_.size = _nbytes(data)
291 in_.pos = 0
292
293 _OutputBuffer_InitAndGrow(buffer, out, -1)
294
295 # Zstandard stream compress
296 while True:
297 while True:
298 zstd_ret = _lib.ZSTD_compressStream2(
299 self._cctx, out, in_, _lib.ZSTD_e_continue
300 )
301 if (
302 out.pos != out.size
303 and in_.pos != in_.size
304 and not _lib.ZSTD_isError(zstd_ret)
305 ):
306 continue
307 break
308
309 # Check error
310 if _lib.ZSTD_isError(zstd_ret):
311 _set_zstd_error(_ErrorType.ERR_COMPRESS, zstd_ret)
312
313 # Like compress_lock_held(), output as much as possible.
314 if out.pos == out.size:
315 _OutputBuffer_Grow(buffer, out)
316 elif in_.pos == in_.size:
317 # Finished
318 break
319
320 # Return a bytes object
321 return _OutputBuffer_Finish(buffer, out)
322
323 def flush(self, mode=_lib.ZSTD_e_end):
324 """Finish the compression process.
325
326 mode
327 Can be these 2 values ZstdCompressor.FLUSH_FRAME,
328 ZstdCompressor.FLUSH_BLOCK
329
330 Flush any remaining data left in internal buffers. Since Zstandard
331 data consists of one or more independent frames, the compressor
332 object can still be used after this method is called."""
333 # Check mode value
334 if mode != _lib.ZSTD_e_end and mode != _lib.ZSTD_e_flush:
335 raise ValueError(
336 "mode argument wrong value, it should be "
337 "ZstdCompressor.FLUSH_FRAME or "
338 "ZstdCompressor.FLUSH_BLOCK."
339 )
340
341 # Thread-safe code
342 with self._lock:
343 try:
344 ret = self._compress_lock_held(None, mode)
345 self._last_mode = mode
346 return ret
347 except:
348 self._last_mode = _lib.ZSTD_e_end
349 # Resetting cctx's session never fail
350 _lib.ZSTD_CCtx_reset(self._cctx, _lib.ZSTD_reset_session_only)
351 raise
352
353 def set_pledged_input_size(self, size, /):
354 """Set the uncompressed content size to be written into the frame header.
355
356 size
357 The size of the uncompressed data to be provided to the compressor.
358
359 This method can be used to ensure the header of the frame about to
360 be written includes the size of the data, unless the
361 CompressionParameter.content_size_flag is set to False.
362 If last_mode != FLUSH_FRAME, then a RuntimeError is raised.
363
364 It is important to ensure that the pledged data size matches the
365 actual data size. If they do not match the compressed output data
366 may be corrupted and the final chunk written may be lost."""
367 size = _zstd_contentsize_converter(size)
368
369 # Thread-safe code
370 with self._lock:
371 # Check the current mode
372 if self._last_mode != _lib.ZSTD_e_end:
373 raise ValueError(
374 "set_pledged_input_size() method must be called "
375 "when last_mode == FLUSH_FRAME"
376 )
377
378 # Set pledged content size
379 zstd_ret = _lib.ZSTD_CCtx_setPledgedSrcSize(self._cctx, size)
380
381 if _lib.ZSTD_isError(zstd_ret):
382 _set_zstd_error(_ErrorType.ERR_SET_PLEDGED_INPUT_SIZE, zstd_ret)