Debian Codegraph @

contrib/python-zstandard/zstandard/backend_cffi.py

raw
1 # Copyright (c) 2016-present, Gregory Szorc
2 # All rights reserved.
3 #
4 # This software may be modified and distributed under the terms
5 # of the BSD license. See the LICENSE file for details.
6
7 """Python interface to the Zstandard (zstd) compression library."""
8
9 from __future__ import absolute_import, unicode_literals
10
11 # This should match what the C extension exports.
12 __all__ = [
13 "BufferSegment",
14 "BufferSegments",
15 "BufferWithSegments",
16 "BufferWithSegmentsCollection",
17 "ZstdCompressionChunker",
18 "ZstdCompressionDict",
19 "ZstdCompressionObj",
20 "ZstdCompressionParameters",
21 "ZstdCompressionReader",
22 "ZstdCompressionWriter",
23 "ZstdCompressor",
24 "ZstdDecompressionObj",
25 "ZstdDecompressionReader",
26 "ZstdDecompressionWriter",
27 "ZstdDecompressor",
28 "ZstdError",
29 "FrameParameters",
30 "backend_features",
31 "estimate_decompression_context_size",
32 "frame_content_size",
33 "frame_header_size",
34 "get_frame_parameters",
35 "train_dictionary",
36 # Constants.
37 "FLUSH_BLOCK",
38 "FLUSH_FRAME",
39 "COMPRESSOBJ_FLUSH_FINISH",
40 "COMPRESSOBJ_FLUSH_BLOCK",
41 "ZSTD_VERSION",
42 "FRAME_HEADER",
43 "CONTENTSIZE_UNKNOWN",
44 "CONTENTSIZE_ERROR",
45 "MAX_COMPRESSION_LEVEL",
46 "COMPRESSION_RECOMMENDED_INPUT_SIZE",
47 "COMPRESSION_RECOMMENDED_OUTPUT_SIZE",
48 "DECOMPRESSION_RECOMMENDED_INPUT_SIZE",
49 "DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE",
50 "MAGIC_NUMBER",
51 "BLOCKSIZELOG_MAX",
52 "BLOCKSIZE_MAX",
53 "WINDOWLOG_MIN",
54 "WINDOWLOG_MAX",
55 "CHAINLOG_MIN",
56 "CHAINLOG_MAX",
57 "HASHLOG_MIN",
58 "HASHLOG_MAX",
59 "MINMATCH_MIN",
60 "MINMATCH_MAX",
61 "SEARCHLOG_MIN",
62 "SEARCHLOG_MAX",
63 "SEARCHLENGTH_MIN",
64 "SEARCHLENGTH_MAX",
65 "TARGETLENGTH_MIN",
66 "TARGETLENGTH_MAX",
67 "LDM_MINMATCH_MIN",
68 "LDM_MINMATCH_MAX",
69 "LDM_BUCKETSIZELOG_MAX",
70 "STRATEGY_FAST",
71 "STRATEGY_DFAST",
72 "STRATEGY_GREEDY",
73 "STRATEGY_LAZY",
74 "STRATEGY_LAZY2",
75 "STRATEGY_BTLAZY2",
76 "STRATEGY_BTOPT",
77 "STRATEGY_BTULTRA",
78 "STRATEGY_BTULTRA2",
79 "DICT_TYPE_AUTO",
80 "DICT_TYPE_RAWCONTENT",
81 "DICT_TYPE_FULLDICT",
82 "FORMAT_ZSTD1",
83 "FORMAT_ZSTD1_MAGICLESS",
84 ]
85
86 import io
87 import os
88
89 from ._cffi import ( # type: ignore
90 ffi,
91 lib,
92 )
93
94
95 backend_features = set() # type: ignore
96
97 COMPRESSION_RECOMMENDED_INPUT_SIZE = lib.ZSTD_CStreamInSize()
98 COMPRESSION_RECOMMENDED_OUTPUT_SIZE = lib.ZSTD_CStreamOutSize()
99 DECOMPRESSION_RECOMMENDED_INPUT_SIZE = lib.ZSTD_DStreamInSize()
100 DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE = lib.ZSTD_DStreamOutSize()
101
102 new_nonzero = ffi.new_allocator(should_clear_after_alloc=False)
103
104
105 MAX_COMPRESSION_LEVEL = lib.ZSTD_maxCLevel()
106 MAGIC_NUMBER = lib.ZSTD_MAGICNUMBER
107 FRAME_HEADER = b"\x28\xb5\x2f\xfd"
108 CONTENTSIZE_UNKNOWN = lib.ZSTD_CONTENTSIZE_UNKNOWN
109 CONTENTSIZE_ERROR = lib.ZSTD_CONTENTSIZE_ERROR
110 ZSTD_VERSION = (
111 lib.ZSTD_VERSION_MAJOR,
112 lib.ZSTD_VERSION_MINOR,
113 lib.ZSTD_VERSION_RELEASE,
114 )
115
116 BLOCKSIZELOG_MAX = lib.ZSTD_BLOCKSIZELOG_MAX
117 BLOCKSIZE_MAX = lib.ZSTD_BLOCKSIZE_MAX
118 WINDOWLOG_MIN = lib.ZSTD_WINDOWLOG_MIN
119 WINDOWLOG_MAX = lib.ZSTD_WINDOWLOG_MAX
120 CHAINLOG_MIN = lib.ZSTD_CHAINLOG_MIN
121 CHAINLOG_MAX = lib.ZSTD_CHAINLOG_MAX
122 HASHLOG_MIN = lib.ZSTD_HASHLOG_MIN
123 HASHLOG_MAX = lib.ZSTD_HASHLOG_MAX
124 MINMATCH_MIN = lib.ZSTD_MINMATCH_MIN
125 MINMATCH_MAX = lib.ZSTD_MINMATCH_MAX
126 SEARCHLOG_MIN = lib.ZSTD_SEARCHLOG_MIN
127 SEARCHLOG_MAX = lib.ZSTD_SEARCHLOG_MAX
128 SEARCHLENGTH_MIN = lib.ZSTD_MINMATCH_MIN
129 SEARCHLENGTH_MAX = lib.ZSTD_MINMATCH_MAX
130 TARGETLENGTH_MIN = lib.ZSTD_TARGETLENGTH_MIN
131 TARGETLENGTH_MAX = lib.ZSTD_TARGETLENGTH_MAX
132 LDM_MINMATCH_MIN = lib.ZSTD_LDM_MINMATCH_MIN
133 LDM_MINMATCH_MAX = lib.ZSTD_LDM_MINMATCH_MAX
134 LDM_BUCKETSIZELOG_MAX = lib.ZSTD_LDM_BUCKETSIZELOG_MAX
135
136 STRATEGY_FAST = lib.ZSTD_fast
137 STRATEGY_DFAST = lib.ZSTD_dfast
138 STRATEGY_GREEDY = lib.ZSTD_greedy
139 STRATEGY_LAZY = lib.ZSTD_lazy
140 STRATEGY_LAZY2 = lib.ZSTD_lazy2
141 STRATEGY_BTLAZY2 = lib.ZSTD_btlazy2
142 STRATEGY_BTOPT = lib.ZSTD_btopt
143 STRATEGY_BTULTRA = lib.ZSTD_btultra
144 STRATEGY_BTULTRA2 = lib.ZSTD_btultra2
145
146 DICT_TYPE_AUTO = lib.ZSTD_dct_auto
147 DICT_TYPE_RAWCONTENT = lib.ZSTD_dct_rawContent
148 DICT_TYPE_FULLDICT = lib.ZSTD_dct_fullDict
149
150 FORMAT_ZSTD1 = lib.ZSTD_f_zstd1
151 FORMAT_ZSTD1_MAGICLESS = lib.ZSTD_f_zstd1_magicless
152
153 FLUSH_BLOCK = 0
154 FLUSH_FRAME = 1
155
156 COMPRESSOBJ_FLUSH_FINISH = 0
157 COMPRESSOBJ_FLUSH_BLOCK = 1
158
159
160 def _cpu_count():
161 # os.cpu_count() was introducd in Python 3.4.
162 try:
163 return os.cpu_count() or 0
164 except AttributeError:
165 pass
166
167 # Linux.
168 try:
169 return os.sysconf("SC_NPROCESSORS_ONLN")
170 except (AttributeError, ValueError):
171 pass
172
173 # TODO implement on other platforms.
174 return 0
175
176
177 class BufferSegment:
178 """Represents a segment within a ``BufferWithSegments``.
179
180 This type is essentially a reference to N bytes within a
181 ``BufferWithSegments``.
182
183 The object conforms to the buffer protocol.
184 """
185
186 @property
187 def offset(self):
188 """The byte offset of this segment within its parent buffer."""
189 raise NotImplementedError()
190
191 def __len__(self):
192 """Obtain the length of the segment, in bytes."""
193 raise NotImplementedError()
194
195 def tobytes(self):
196 """Obtain bytes copy of this segment."""
197 raise NotImplementedError()
198
199
200 class BufferSegments:
201 """Represents an array of ``(offset, length)`` integers.
202
203 This type is effectively an index used by :py:class:`BufferWithSegments`.
204
205 The array members are 64-bit unsigned integers using host/native bit order.
206
207 Instances conform to the buffer protocol.
208 """
209
210
211 class BufferWithSegments:
212 """A memory buffer containing N discrete items of known lengths.
213
214 This type is essentially a fixed size memory address and an array
215 of 2-tuples of ``(offset, length)`` 64-bit unsigned native-endian
216 integers defining the byte offset and length of each segment within
217 the buffer.
218
219 Instances behave like containers.
220
221 Instances also conform to the buffer protocol. So a reference to the
222 backing bytes can be obtained via ``memoryview(o)``. A *copy* of the
223 backing bytes can be obtained via ``.tobytes()``.
224
225 This type exists to facilitate operations against N>1 items without
226 the overhead of Python object creation and management. Used with
227 APIs like :py:meth:`ZstdDecompressor.multi_decompress_to_buffer`, it
228 is possible to decompress many objects in parallel without the GIL
229 held, leading to even better performance.
230 """
231
232 @property
233 def size(self):
234 """Total sizein bytes of the backing buffer."""
235 raise NotImplementedError()
236
237 def __len__(self):
238 raise NotImplementedError()
239
240 def __getitem__(self, i):
241 """Obtains a segment within the buffer.
242
243 The returned object references memory within this buffer.
244
245 :param i:
246 Integer index of segment to retrieve.
247 :return:
248 :py:class:`BufferSegment`
249 """
250 raise NotImplementedError()
251
252 def segments(self):
253 """Obtain the array of ``(offset, length)`` segments in the buffer.
254
255 :return:
256 :py:class:`BufferSegments`
257 """
258 raise NotImplementedError()
259
260 def tobytes(self):
261 """Obtain bytes copy of this instance."""
262 raise NotImplementedError()
263
264
265 class BufferWithSegmentsCollection:
266 """A virtual spanning view over multiple BufferWithSegments.
267
268 Instances are constructed from 1 or more :py:class:`BufferWithSegments`
269 instances. The resulting object behaves like an ordered sequence whose
270 members are the segments within each ``BufferWithSegments``.
271
272 If the object is composed of 2 ``BufferWithSegments`` instances with the
273 first having 2 segments and the second have 3 segments, then ``b[0]``
274 and ``b[1]`` access segments in the first object and ``b[2]``, ``b[3]``,
275 and ``b[4]`` access segments from the second.
276 """
277
278 def __len__(self):
279 """The number of segments within all ``BufferWithSegments``."""
280 raise NotImplementedError()
281
282 def __getitem__(self, i):
283 """Obtain the ``BufferSegment`` at an offset."""
284 raise NotImplementedError()
285
286
287 class ZstdError(Exception):
288 pass
289
290
291 def _zstd_error(zresult):
292 # Resolves to bytes on Python 2 and 3. We use the string for formatting
293 # into error messages, which will be literal unicode. So convert it to
294 # unicode.
295 return ffi.string(lib.ZSTD_getErrorName(zresult)).decode("utf-8")
296
297
298 def _make_cctx_params(params):
299 res = lib.ZSTD_createCCtxParams()
300 if res == ffi.NULL:
301 raise MemoryError()
302
303 res = ffi.gc(res, lib.ZSTD_freeCCtxParams)
304
305 attrs = [
306 (lib.ZSTD_c_format, params.format),
307 (lib.ZSTD_c_compressionLevel, params.compression_level),
308 (lib.ZSTD_c_windowLog, params.window_log),
309 (lib.ZSTD_c_hashLog, params.hash_log),
310 (lib.ZSTD_c_chainLog, params.chain_log),
311 (lib.ZSTD_c_searchLog, params.search_log),
312 (lib.ZSTD_c_minMatch, params.min_match),
313 (lib.ZSTD_c_targetLength, params.target_length),
314 (lib.ZSTD_c_strategy, params.strategy),
315 (lib.ZSTD_c_contentSizeFlag, params.write_content_size),
316 (lib.ZSTD_c_checksumFlag, params.write_checksum),
317 (lib.ZSTD_c_dictIDFlag, params.write_dict_id),
318 (lib.ZSTD_c_nbWorkers, params.threads),
319 (lib.ZSTD_c_jobSize, params.job_size),
320 (lib.ZSTD_c_overlapLog, params.overlap_log),
321 (lib.ZSTD_c_forceMaxWindow, params.force_max_window),
322 (lib.ZSTD_c_enableLongDistanceMatching, params.enable_ldm),
323 (lib.ZSTD_c_ldmHashLog, params.ldm_hash_log),
324 (lib.ZSTD_c_ldmMinMatch, params.ldm_min_match),
325 (lib.ZSTD_c_ldmBucketSizeLog, params.ldm_bucket_size_log),
326 (lib.ZSTD_c_ldmHashRateLog, params.ldm_hash_rate_log),
327 ]
328
329 for param, value in attrs:
330 _set_compression_parameter(res, param, value)
331
332 return res
333
334
335 class ZstdCompressionParameters(object):
336 """Low-level zstd compression parameters.
337
338 This type represents a collection of parameters to control how zstd
339 compression is performed.
340
341 Instances can be constructed from raw parameters or derived from a
342 base set of defaults specified from a compression level (recommended)
343 via :py:meth:`ZstdCompressionParameters.from_level`.
344
345 >>> # Derive compression settings for compression level 7.
346 >>> params = zstandard.ZstdCompressionParameters.from_level(7)
347
348 >>> # With an input size of 1MB
349 >>> params = zstandard.ZstdCompressionParameters.from_level(7, source_size=1048576)
350
351 Using ``from_level()``, it is also possible to override individual compression
352 parameters or to define additional settings that aren't automatically derived.
353 e.g.:
354
355 >>> params = zstandard.ZstdCompressionParameters.from_level(4, window_log=10)
356 >>> params = zstandard.ZstdCompressionParameters.from_level(5, threads=4)
357
358 Or you can define low-level compression settings directly:
359
360 >>> params = zstandard.ZstdCompressionParameters(window_log=12, enable_ldm=True)
361
362 Once a ``ZstdCompressionParameters`` instance is obtained, it can be used to
363 configure a compressor:
364
365 >>> cctx = zstandard.ZstdCompressor(compression_params=params)
366
367 Some of these are very low-level settings. It may help to consult the official
368 zstandard documentation for their behavior. Look for the ``ZSTD_p_*`` constants
369 in ``zstd.h`` (https://github.com/facebook/zstd/blob/dev/lib/zstd.h).
370 """
371
372 @staticmethod
373 def from_level(level, source_size=0, dict_size=0, **kwargs):
374 """Create compression parameters from a compression level.
375
376 :param level:
377 Integer compression level.
378 :param source_size:
379 Integer size in bytes of source to be compressed.
380 :param dict_size:
381 Integer size in bytes of compression dictionary to use.
382 :return:
383 :py:class:`ZstdCompressionParameters`
384 """
385 params = lib.ZSTD_getCParams(level, source_size, dict_size)
386
387 args = {
388 "window_log": "windowLog",
389 "chain_log": "chainLog",
390 "hash_log": "hashLog",
391 "search_log": "searchLog",
392 "min_match": "minMatch",
393 "target_length": "targetLength",
394 "strategy": "strategy",
395 }
396
397 for arg, attr in args.items():
398 if arg not in kwargs:
399 kwargs[arg] = getattr(params, attr)
400
401 return ZstdCompressionParameters(**kwargs)
402
403 def __init__(
404 self,
405 format=0,
406 compression_level=0,
407 window_log=0,
408 hash_log=0,
409 chain_log=0,
410 search_log=0,
411 min_match=0,
412 target_length=0,
413 strategy=-1,
414 write_content_size=1,
415 write_checksum=0,
416 write_dict_id=0,
417 job_size=0,
418 overlap_log=-1,
419 force_max_window=0,
420 enable_ldm=0,
421 ldm_hash_log=0,
422 ldm_min_match=0,
423 ldm_bucket_size_log=0,
424 ldm_hash_rate_log=-1,
425 threads=0,
426 ):
427 params = lib.ZSTD_createCCtxParams()
428 if params == ffi.NULL:
429 raise MemoryError()
430
431 params = ffi.gc(params, lib.ZSTD_freeCCtxParams)
432
433 self._params = params
434
435 if threads < 0:
436 threads = _cpu_count()
437
438 # We need to set ZSTD_c_nbWorkers before ZSTD_c_jobSize and ZSTD_c_overlapLog
439 # because setting ZSTD_c_nbWorkers resets the other parameters.
440 _set_compression_parameter(params, lib.ZSTD_c_nbWorkers, threads)
441
442 _set_compression_parameter(params, lib.ZSTD_c_format, format)
443 _set_compression_parameter(
444 params, lib.ZSTD_c_compressionLevel, compression_level
445 )
446 _set_compression_parameter(params, lib.ZSTD_c_windowLog, window_log)
447 _set_compression_parameter(params, lib.ZSTD_c_hashLog, hash_log)
448 _set_compression_parameter(params, lib.ZSTD_c_chainLog, chain_log)
449 _set_compression_parameter(params, lib.ZSTD_c_searchLog, search_log)
450 _set_compression_parameter(params, lib.ZSTD_c_minMatch, min_match)
451 _set_compression_parameter(
452 params, lib.ZSTD_c_targetLength, target_length
453 )
454
455 if strategy == -1:
456 strategy = 0
457
458 _set_compression_parameter(params, lib.ZSTD_c_strategy, strategy)
459 _set_compression_parameter(
460 params, lib.ZSTD_c_contentSizeFlag, write_content_size
461 )
462 _set_compression_parameter(
463 params, lib.ZSTD_c_checksumFlag, write_checksum
464 )
465 _set_compression_parameter(params, lib.ZSTD_c_dictIDFlag, write_dict_id)
466 _set_compression_parameter(params, lib.ZSTD_c_jobSize, job_size)
467
468 if overlap_log == -1:
469 overlap_log = 0
470
471 _set_compression_parameter(params, lib.ZSTD_c_overlapLog, overlap_log)
472 _set_compression_parameter(
473 params, lib.ZSTD_c_forceMaxWindow, force_max_window
474 )
475 _set_compression_parameter(
476 params, lib.ZSTD_c_enableLongDistanceMatching, enable_ldm
477 )
478 _set_compression_parameter(params, lib.ZSTD_c_ldmHashLog, ldm_hash_log)
479 _set_compression_parameter(
480 params, lib.ZSTD_c_ldmMinMatch, ldm_min_match
481 )
482 _set_compression_parameter(
483 params, lib.ZSTD_c_ldmBucketSizeLog, ldm_bucket_size_log
484 )
485
486 if ldm_hash_rate_log == -1:
487 ldm_hash_rate_log = 0
488
489 _set_compression_parameter(
490 params, lib.ZSTD_c_ldmHashRateLog, ldm_hash_rate_log
491 )
492
493 @property
494 def format(self):
495 return _get_compression_parameter(self._params, lib.ZSTD_c_format)
496
497 @property
498 def compression_level(self):
499 return _get_compression_parameter(
500 self._params, lib.ZSTD_c_compressionLevel
501 )
502
503 @property
504 def window_log(self):
505 return _get_compression_parameter(self._params, lib.ZSTD_c_windowLog)
506
507 @property
508 def hash_log(self):
509 return _get_compression_parameter(self._params, lib.ZSTD_c_hashLog)
510
511 @property
512 def chain_log(self):
513 return _get_compression_parameter(self._params, lib.ZSTD_c_chainLog)
514
515 @property
516 def search_log(self):
517 return _get_compression_parameter(self._params, lib.ZSTD_c_searchLog)
518
519 @property
520 def min_match(self):
521 return _get_compression_parameter(self._params, lib.ZSTD_c_minMatch)
522
523 @property
524 def target_length(self):
525 return _get_compression_parameter(self._params, lib.ZSTD_c_targetLength)
526
527 @property
528 def strategy(self):
529 return _get_compression_parameter(self._params, lib.ZSTD_c_strategy)
530
531 @property
532 def write_content_size(self):
533 return _get_compression_parameter(
534 self._params, lib.ZSTD_c_contentSizeFlag
535 )
536
537 @property
538 def write_checksum(self):
539 return _get_compression_parameter(self._params, lib.ZSTD_c_checksumFlag)
540
541 @property
542 def write_dict_id(self):
543 return _get_compression_parameter(self._params, lib.ZSTD_c_dictIDFlag)
544
545 @property
546 def job_size(self):
547 return _get_compression_parameter(self._params, lib.ZSTD_c_jobSize)
548
549 @property
550 def overlap_log(self):
551 return _get_compression_parameter(self._params, lib.ZSTD_c_overlapLog)
552
553 @property
554 def force_max_window(self):
555 return _get_compression_parameter(
556 self._params, lib.ZSTD_c_forceMaxWindow
557 )
558
559 @property
560 def enable_ldm(self):
561 return _get_compression_parameter(
562 self._params, lib.ZSTD_c_enableLongDistanceMatching
563 )
564
565 @property
566 def ldm_hash_log(self):
567 return _get_compression_parameter(self._params, lib.ZSTD_c_ldmHashLog)
568
569 @property
570 def ldm_min_match(self):
571 return _get_compression_parameter(self._params, lib.ZSTD_c_ldmMinMatch)
572
573 @property
574 def ldm_bucket_size_log(self):
575 return _get_compression_parameter(
576 self._params, lib.ZSTD_c_ldmBucketSizeLog
577 )
578
579 @property
580 def ldm_hash_rate_log(self):
581 return _get_compression_parameter(
582 self._params, lib.ZSTD_c_ldmHashRateLog
583 )
584
585 @property
586 def threads(self):
587 return _get_compression_parameter(self._params, lib.ZSTD_c_nbWorkers)
588
589 def estimated_compression_context_size(self):
590 """Estimated size in bytes needed to compress with these parameters."""
591 return lib.ZSTD_estimateCCtxSize_usingCCtxParams(self._params)
592
593
594 def estimate_decompression_context_size():
595 """Estimate the memory size requirements for a decompressor instance.
596
597 :return:
598 Integer number of bytes.
599 """
600 return lib.ZSTD_estimateDCtxSize()
601
602
603 def _set_compression_parameter(params, param, value):
604 zresult = lib.ZSTD_CCtxParams_setParameter(params, param, value)
605 if lib.ZSTD_isError(zresult):
606 raise ZstdError(
607 "unable to set compression context parameter: %s"
608 % _zstd_error(zresult)
609 )
610
611
612 def _get_compression_parameter(params, param):
613 result = ffi.new("int *")
614
615 zresult = lib.ZSTD_CCtxParams_getParameter(params, param, result)
616 if lib.ZSTD_isError(zresult):
617 raise ZstdError(
618 "unable to get compression context parameter: %s"
619 % _zstd_error(zresult)
620 )
621
622 return result[0]
623
624
625 class ZstdCompressionWriter(object):
626 """Writable compressing stream wrapper.
627
628 ``ZstdCompressionWriter`` is a write-only stream interface for writing
629 compressed data to another stream.
630
631 This type conforms to the ``io.RawIOBase`` interface and should be usable
632 by any type that operates against a *file-object* (``typing.BinaryIO``
633 in Python type hinting speak). Only methods that involve writing will do
634 useful things.
635
636 As data is written to this stream (e.g. via ``write()``), that data
637 is sent to the compressor. As compressed data becomes available from
638 the compressor, it is sent to the underlying stream by calling its
639 ``write()`` method.
640
641 Both ``write()`` and ``flush()`` return the number of bytes written to the
642 object's ``write()``. In many cases, small inputs do not accumulate enough
643 data to cause a write and ``write()`` will return ``0``.
644
645 Calling ``close()`` will mark the stream as closed and subsequent I/O
646 operations will raise ``ValueError`` (per the documented behavior of
647 ``io.RawIOBase``). ``close()`` will also call ``close()`` on the underlying
648 stream if such a method exists and the instance was constructed with
649 ``closefd=True``
650
651 Instances are obtained by calling :py:meth:`ZstdCompressor.stream_writer`.
652
653 Typically usage is as follows:
654
655 >>> cctx = zstandard.ZstdCompressor(level=10)
656 >>> compressor = cctx.stream_writer(fh)
657 >>> compressor.write(b"chunk 0\\n")
658 >>> compressor.write(b"chunk 1\\n")
659 >>> compressor.flush()
660 >>> # Receiver will be able to decode ``chunk 0\\nchunk 1\\n`` at this point.
661 >>> # Receiver is also expecting more data in the zstd *frame*.
662 >>>
663 >>> compressor.write(b"chunk 2\\n")
664 >>> compressor.flush(zstandard.FLUSH_FRAME)
665 >>> # Receiver will be able to decode ``chunk 0\\nchunk 1\\nchunk 2``.
666 >>> # Receiver is expecting no more data, as the zstd frame is closed.
667 >>> # Any future calls to ``write()`` at this point will construct a new
668 >>> # zstd frame.
669
670 Instances can be used as context managers. Exiting the context manager is
671 the equivalent of calling ``close()``, which is equivalent to calling
672 ``flush(zstandard.FLUSH_FRAME)``:
673
674 >>> cctx = zstandard.ZstdCompressor(level=10)
675 >>> with cctx.stream_writer(fh) as compressor:
676 ... compressor.write(b'chunk 0')
677 ... compressor.write(b'chunk 1')
678 ... ...
679
680 .. important::
681
682 If ``flush(FLUSH_FRAME)`` is not called, emitted data doesn't
683 constitute a full zstd *frame* and consumers of this data may complain
684 about malformed input. It is recommended to use instances as a context
685 manager to ensure *frames* are properly finished.
686
687 If the size of the data being fed to this streaming compressor is known,
688 you can declare it before compression begins:
689
690 >>> cctx = zstandard.ZstdCompressor()
691 >>> with cctx.stream_writer(fh, size=data_len) as compressor:
692 ... compressor.write(chunk0)
693 ... compressor.write(chunk1)
694 ... ...
695
696 Declaring the size of the source data allows compression parameters to
697 be tuned. And if ``write_content_size`` is used, it also results in the
698 content size being written into the frame header of the output data.
699
700 The size of chunks being ``write()`` to the destination can be specified:
701
702 >>> cctx = zstandard.ZstdCompressor()
703 >>> with cctx.stream_writer(fh, write_size=32768) as compressor:
704 ... ...
705
706 To see how much memory is being used by the streaming compressor:
707
708 >>> cctx = zstandard.ZstdCompressor()
709 >>> with cctx.stream_writer(fh) as compressor:
710 ... ...
711 ... byte_size = compressor.memory_size()
712
713 Thte total number of bytes written so far are exposed via ``tell()``:
714
715 >>> cctx = zstandard.ZstdCompressor()
716 >>> with cctx.stream_writer(fh) as compressor:
717 ... ...
718 ... total_written = compressor.tell()
719
720 ``stream_writer()`` accepts a ``write_return_read`` boolean argument to
721 control the return value of ``write()``. When ``False`` (the default),
722 ``write()`` returns the number of bytes that were ``write()``'en to the
723 underlying object. When ``True``, ``write()`` returns the number of bytes
724 read from the input that were subsequently written to the compressor.
725 ``True`` is the *proper* behavior for ``write()`` as specified by the
726 ``io.RawIOBase`` interface and will become the default value in a future
727 release.
728 """
729
730 def __init__(
731 self,
732 compressor,
733 writer,
734 source_size,
735 write_size,
736 write_return_read,
737 closefd=True,
738 ):
739 self._compressor = compressor
740 self._writer = writer
741 self._write_size = write_size
742 self._write_return_read = bool(write_return_read)
743 self._closefd = bool(closefd)
744 self._entered = False
745 self._closing = False
746 self._closed = False
747 self._bytes_compressed = 0
748
749 self._dst_buffer = ffi.new("char[]", write_size)
750 self._out_buffer = ffi.new("ZSTD_outBuffer *")
751 self._out_buffer.dst = self._dst_buffer
752 self._out_buffer.size = len(self._dst_buffer)
753 self._out_buffer.pos = 0
754
755 zresult = lib.ZSTD_CCtx_setPledgedSrcSize(compressor._cctx, source_size)
756 if lib.ZSTD_isError(zresult):
757 raise ZstdError(
758 "error setting source size: %s" % _zstd_error(zresult)
759 )
760
761 def __enter__(self):
762 if self._closed:
763 raise ValueError("stream is closed")
764
765 if self._entered:
766 raise ZstdError("cannot __enter__ multiple times")
767
768 self._entered = True
769 return self
770
771 def __exit__(self, exc_type, exc_value, exc_tb):
772 self._entered = False
773 self.close()
774 self._compressor = None
775
776 return False
777
778 def __iter__(self):
779 raise io.UnsupportedOperation()
780
781 def __next__(self):
782 raise io.UnsupportedOperation()
783
784 def memory_size(self):
785 return lib.ZSTD_sizeof_CCtx(self._compressor._cctx)
786
787 def fileno(self):
788 f = getattr(self._writer, "fileno", None)
789 if f:
790 return f()
791 else:
792 raise OSError("fileno not available on underlying writer")
793
794 def close(self):
795 if self._closed:
796 return
797
798 try:
799 self._closing = True
800 self.flush(FLUSH_FRAME)
801 finally:
802 self._closing = False
803 self._closed = True
804
805 # Call close() on underlying stream as well.
806 f = getattr(self._writer, "close", None)
807 if self._closefd and f:
808 f()
809
810 @property
811 def closed(self):
812 return self._closed
813
814 def isatty(self):
815 return False
816
817 def readable(self):
818 return False
819
820 def readline(self, size=-1):
821 raise io.UnsupportedOperation()
822
823 def readlines(self, hint=-1):
824 raise io.UnsupportedOperation()
825
826 def seek(self, offset, whence=None):
827 raise io.UnsupportedOperation()
828
829 def seekable(self):
830 return False
831
832 def truncate(self, size=None):
833 raise io.UnsupportedOperation()
834
835 def writable(self):
836 return True
837
838 def writelines(self, lines):
839 raise NotImplementedError("writelines() is not yet implemented")
840
841 def read(self, size=-1):
842 raise io.UnsupportedOperation()
843
844 def readall(self):
845 raise io.UnsupportedOperation()
846
847 def readinto(self, b):
848 raise io.UnsupportedOperation()
849
850 def write(self, data):
851 """Send data to the compressor and possibly to the inner stream."""
852 if self._closed:
853 raise ValueError("stream is closed")
854
855 total_write = 0
856
857 data_buffer = ffi.from_buffer(data)
858
859 in_buffer = ffi.new("ZSTD_inBuffer *")
860 in_buffer.src = data_buffer
861 in_buffer.size = len(data_buffer)
862 in_buffer.pos = 0
863
864 out_buffer = self._out_buffer
865 out_buffer.pos = 0
866
867 while in_buffer.pos < in_buffer.size:
868 zresult = lib.ZSTD_compressStream2(
869 self._compressor._cctx,
870 out_buffer,
871 in_buffer,
872 lib.ZSTD_e_continue,
873 )
874 if lib.ZSTD_isError(zresult):
875 raise ZstdError(
876 "zstd compress error: %s" % _zstd_error(zresult)
877 )
878
879 if out_buffer.pos:
880 self._writer.write(
881 ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
882 )
883 total_write += out_buffer.pos
884 self._bytes_compressed += out_buffer.pos
885 out_buffer.pos = 0
886
887 if self._write_return_read:
888 return in_buffer.pos
889 else:
890 return total_write
891
892 def flush(self, flush_mode=FLUSH_BLOCK):
893 """Evict data from compressor's internal state and write it to inner stream.
894
895 Calling this method may result in 0 or more ``write()`` calls to the
896 inner stream.
897
898 This method will also call ``flush()`` on the inner stream, if such a
899 method exists.
900
901 :param flush_mode:
902 How to flush the zstd compressor.
903
904 ``zstandard.FLUSH_BLOCK`` will flush data already sent to the
905 compressor but not emitted to the inner stream. The stream is still
906 writable after calling this. This is the default behavior.
907
908 See documentation for other ``zstandard.FLUSH_*`` constants for more
909 flushing options.
910 :return:
911 Integer number of bytes written to the inner stream.
912 """
913
914 if flush_mode == FLUSH_BLOCK:
915 flush = lib.ZSTD_e_flush
916 elif flush_mode == FLUSH_FRAME:
917 flush = lib.ZSTD_e_end
918 else:
919 raise ValueError("unknown flush_mode: %r" % flush_mode)
920
921 if self._closed:
922 raise ValueError("stream is closed")
923
924 total_write = 0
925
926 out_buffer = self._out_buffer
927 out_buffer.pos = 0
928
929 in_buffer = ffi.new("ZSTD_inBuffer *")
930 in_buffer.src = ffi.NULL
931 in_buffer.size = 0
932 in_buffer.pos = 0
933
934 while True:
935 zresult = lib.ZSTD_compressStream2(
936 self._compressor._cctx, out_buffer, in_buffer, flush
937 )
938 if lib.ZSTD_isError(zresult):
939 raise ZstdError(
940 "zstd compress error: %s" % _zstd_error(zresult)
941 )
942
943 if out_buffer.pos:
944 self._writer.write(
945 ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
946 )
947 total_write += out_buffer.pos
948 self._bytes_compressed += out_buffer.pos
949 out_buffer.pos = 0
950
951 if not zresult:
952 break
953
954 f = getattr(self._writer, "flush", None)
955 if f and not self._closing:
956 f()
957
958 return total_write
959
960 def tell(self):
961 return self._bytes_compressed
962
963
964 class ZstdCompressionObj(object):
965 """A compressor conforming to the API in Python's standard library.
966
967 This type implements an API similar to compression types in Python's
968 standard library such as ``zlib.compressobj`` and ``bz2.BZ2Compressor``.
969 This enables existing code targeting the standard library API to swap
970 in this type to achieve zstd compression.
971
972 .. important::
973
974 The design of this API is not ideal for optimal performance.
975
976 The reason performance is not optimal is because the API is limited to
977 returning a single buffer holding compressed data. When compressing
978 data, we don't know how much data will be emitted. So in order to
979 capture all this data in a single buffer, we need to perform buffer
980 reallocations and/or extra memory copies. This can add significant
981 overhead depending on the size or nature of the compressed data how
982 much your application calls this type.
983
984 If performance is critical, consider an API like
985 :py:meth:`ZstdCompressor.stream_reader`,
986 :py:meth:`ZstdCompressor.stream_writer`,
987 :py:meth:`ZstdCompressor.chunker`, or
988 :py:meth:`ZstdCompressor.read_to_iter`, which result in less overhead
989 managing buffers.
990
991 Instances are obtained by calling :py:meth:`ZstdCompressor.compressobj`.
992
993 Here is how this API should be used:
994
995 >>> cctx = zstandard.ZstdCompressor()
996 >>> cobj = cctx.compressobj()
997 >>> data = cobj.compress(b"raw input 0")
998 >>> data = cobj.compress(b"raw input 1")
999 >>> data = cobj.flush()
1000
1001 Or to flush blocks:
1002
1003 >>> cctx.zstandard.ZstdCompressor()
1004 >>> cobj = cctx.compressobj()
1005 >>> data = cobj.compress(b"chunk in first block")
1006 >>> data = cobj.flush(zstandard.COMPRESSOBJ_FLUSH_BLOCK)
1007 >>> data = cobj.compress(b"chunk in second block")
1008 >>> data = cobj.flush()
1009
1010 For best performance results, keep input chunks under 256KB. This avoids
1011 extra allocations for a large output object.
1012
1013 It is possible to declare the input size of the data that will be fed
1014 into the compressor:
1015
1016 >>> cctx = zstandard.ZstdCompressor()
1017 >>> cobj = cctx.compressobj(size=6)
1018 >>> data = cobj.compress(b"foobar")
1019 >>> data = cobj.flush()
1020 """
1021
1022 def __init__(
1023 self, compressor, write_size=COMPRESSION_RECOMMENDED_OUTPUT_SIZE
1024 ):
1025 self._compressor = compressor
1026 self._out = ffi.new("ZSTD_outBuffer *")
1027 self._dst_buffer = ffi.new("char[]", write_size)
1028 self._out.dst = self._dst_buffer
1029 self._out.size = write_size
1030 self._out.pos = 0
1031 self._finished = False
1032
1033 def compress(self, data):
1034 """Send data to the compressor.
1035
1036 This method receives bytes to feed to the compressor and returns
1037 bytes constituting zstd compressed data.
1038
1039 The zstd compressor accumulates bytes and the returned bytes may be
1040 substantially smaller or larger than the size of the input data on
1041 any given call. The returned value may be the empty byte string
1042 (``b""``).
1043
1044 :param data:
1045 Data to write to the compressor.
1046 :return:
1047 Compressed data.
1048 """
1049 if self._finished:
1050 raise ZstdError("cannot call compress() after compressor finished")
1051
1052 data_buffer = ffi.from_buffer(data)
1053 source = ffi.new("ZSTD_inBuffer *")
1054 source.src = data_buffer
1055 source.size = len(data_buffer)
1056 source.pos = 0
1057
1058 chunks = []
1059
1060 while source.pos < len(data):
1061 zresult = lib.ZSTD_compressStream2(
1062 self._compressor._cctx, self._out, source, lib.ZSTD_e_continue
1063 )
1064 if lib.ZSTD_isError(zresult):
1065 raise ZstdError(
1066 "zstd compress error: %s" % _zstd_error(zresult)
1067 )
1068
1069 if self._out.pos:
1070 chunks.append(ffi.buffer(self._out.dst, self._out.pos)[:])
1071 self._out.pos = 0
1072
1073 return b"".join(chunks)
1074
1075 def flush(self, flush_mode=COMPRESSOBJ_FLUSH_FINISH):
1076 """Emit data accumulated in the compressor that hasn't been outputted yet.
1077
1078 The ``flush_mode`` argument controls how to end the stream.
1079
1080 ``zstandard.COMPRESSOBJ_FLUSH_FINISH`` (the default) ends the
1081 compression stream and finishes a zstd frame. Once this type of flush
1082 is performed, ``compress()`` and ``flush()`` can no longer be called.
1083 This type of flush **must** be called to end the compression context. If
1084 not called, the emitted data may be incomplete and may not be readable
1085 by a decompressor.
1086
1087 ``zstandard.COMPRESSOBJ_FLUSH_BLOCK`` will flush a zstd block. This
1088 ensures that all data fed to this instance will have been omitted and
1089 can be decoded by a decompressor. Flushes of this type can be performed
1090 multiple times. The next call to ``compress()`` will begin a new zstd
1091 block.
1092
1093 :param flush_mode:
1094 How to flush the zstd compressor.
1095 :return:
1096 Compressed data.
1097 """
1098 if flush_mode not in (
1099 COMPRESSOBJ_FLUSH_FINISH,
1100 COMPRESSOBJ_FLUSH_BLOCK,
1101 ):
1102 raise ValueError("flush mode not recognized")
1103
1104 if self._finished:
1105 raise ZstdError("compressor object already finished")
1106
1107 if flush_mode == COMPRESSOBJ_FLUSH_BLOCK:
1108 z_flush_mode = lib.ZSTD_e_flush
1109 elif flush_mode == COMPRESSOBJ_FLUSH_FINISH:
1110 z_flush_mode = lib.ZSTD_e_end
1111 self._finished = True
1112 else:
1113 raise ZstdError("unhandled flush mode")
1114
1115 assert self._out.pos == 0
1116
1117 in_buffer = ffi.new("ZSTD_inBuffer *")
1118 in_buffer.src = ffi.NULL
1119 in_buffer.size = 0
1120 in_buffer.pos = 0
1121
1122 chunks = []
1123
1124 while True:
1125 zresult = lib.ZSTD_compressStream2(
1126 self._compressor._cctx, self._out, in_buffer, z_flush_mode
1127 )
1128 if lib.ZSTD_isError(zresult):
1129 raise ZstdError(
1130 "error ending compression stream: %s" % _zstd_error(zresult)
1131 )
1132
1133 if self._out.pos:
1134 chunks.append(ffi.buffer(self._out.dst, self._out.pos)[:])
1135 self._out.pos = 0
1136
1137 if not zresult:
1138 break
1139
1140 return b"".join(chunks)
1141
1142
1143 class ZstdCompressionChunker(object):
1144 """Compress data to uniformly sized chunks.
1145
1146 This type allows you to iteratively feed chunks of data into a compressor
1147 and produce output chunks of uniform size.
1148
1149 ``compress()``, ``flush()``, and ``finish()`` all return an iterator of
1150 ``bytes`` instances holding compressed data. The iterator may be empty.
1151 Callers MUST iterate through all elements of the returned iterator before
1152 performing another operation on the object or else the compressor's
1153 internal state may become confused. This can result in an exception being
1154 raised or malformed data being emitted.
1155
1156 All chunks emitted by ``compress()`` will have a length of the configured
1157 chunk size.
1158
1159 ``flush()`` and ``finish()`` may return a final chunk smaller than
1160 the configured chunk size.
1161
1162 Instances are obtained by calling :py:meth:`ZstdCompressor.chunker`.
1163
1164 Here is how the API should be used:
1165
1166 >>> cctx = zstandard.ZstdCompressor()
1167 >>> chunker = cctx.chunker(chunk_size=32768)
1168 >>>
1169 >>> with open(path, 'rb') as fh:
1170 ... while True:
1171 ... in_chunk = fh.read(32768)
1172 ... if not in_chunk:
1173 ... break
1174 ...
1175 ... for out_chunk in chunker.compress(in_chunk):
1176 ... # Do something with output chunk of size 32768.
1177 ...
1178 ... for out_chunk in chunker.finish():
1179 ... # Do something with output chunks that finalize the zstd frame.
1180
1181 This compressor type is often a better alternative to
1182 :py:class:`ZstdCompressor.compressobj` because it has better performance
1183 properties.
1184
1185 ``compressobj()`` will emit output data as it is available. This results
1186 in a *stream* of output chunks of varying sizes. The consistency of the
1187 output chunk size with ``chunker()`` is more appropriate for many usages,
1188 such as sending compressed data to a socket.
1189
1190 ``compressobj()`` may also perform extra memory reallocations in order
1191 to dynamically adjust the sizes of the output chunks. Since ``chunker()``
1192 output chunks are all the same size (except for flushed or final chunks),
1193 there is less memory allocation/copying overhead.
1194 """
1195
1196 def __init__(self, compressor, chunk_size):
1197 self._compressor = compressor
1198 self._out = ffi.new("ZSTD_outBuffer *")
1199 self._dst_buffer = ffi.new("char[]", chunk_size)
1200 self._out.dst = self._dst_buffer
1201 self._out.size = chunk_size
1202 self._out.pos = 0
1203
1204 self._in = ffi.new("ZSTD_inBuffer *")
1205 self._in.src = ffi.NULL
1206 self._in.size = 0
1207 self._in.pos = 0
1208 self._finished = False
1209
1210 def compress(self, data):
1211 """Feed new input data into the compressor.
1212
1213 :param data:
1214 Data to feed to compressor.
1215 :return:
1216 Iterator of ``bytes`` representing chunks of compressed data.
1217 """
1218 if self._finished:
1219 raise ZstdError("cannot call compress() after compression finished")
1220
1221 if self._in.src != ffi.NULL:
1222 raise ZstdError(
1223 "cannot perform operation before consuming output "
1224 "from previous operation"
1225 )
1226
1227 data_buffer = ffi.from_buffer(data)
1228
1229 if not len(data_buffer):
1230 return
1231
1232 self._in.src = data_buffer
1233 self._in.size = len(data_buffer)
1234 self._in.pos = 0
1235
1236 while self._in.pos < self._in.size:
1237 zresult = lib.ZSTD_compressStream2(
1238 self._compressor._cctx, self._out, self._in, lib.ZSTD_e_continue
1239 )
1240
1241 if self._in.pos == self._in.size:
1242 self._in.src = ffi.NULL
1243 self._in.size = 0
1244 self._in.pos = 0
1245
1246 if lib.ZSTD_isError(zresult):
1247 raise ZstdError(
1248 "zstd compress error: %s" % _zstd_error(zresult)
1249 )
1250
1251 if self._out.pos == self._out.size:
1252 yield ffi.buffer(self._out.dst, self._out.pos)[:]
1253 self._out.pos = 0
1254
1255 def flush(self):
1256 """Flushes all data currently in the compressor.
1257
1258 :return:
1259 Iterator of ``bytes`` of compressed data.
1260 """
1261 if self._finished:
1262 raise ZstdError("cannot call flush() after compression finished")
1263
1264 if self._in.src != ffi.NULL:
1265 raise ZstdError(
1266 "cannot call flush() before consuming output from "
1267 "previous operation"
1268 )
1269
1270 while True:
1271 zresult = lib.ZSTD_compressStream2(
1272 self._compressor._cctx, self._out, self._in, lib.ZSTD_e_flush
1273 )
1274 if lib.ZSTD_isError(zresult):
1275 raise ZstdError(
1276 "zstd compress error: %s" % _zstd_error(zresult)
1277 )
1278
1279 if self._out.pos:
1280 yield ffi.buffer(self._out.dst, self._out.pos)[:]
1281 self._out.pos = 0
1282
1283 if not zresult:
1284 return
1285
1286 def finish(self):
1287 """Signals the end of input data.
1288
1289 No new data can be compressed after this method is called.
1290
1291 This method will flush buffered data and finish the zstd frame.
1292
1293 :return:
1294 Iterator of ``bytes`` of compressed data.
1295 """
1296 if self._finished:
1297 raise ZstdError("cannot call finish() after compression finished")
1298
1299 if self._in.src != ffi.NULL:
1300 raise ZstdError(
1301 "cannot call finish() before consuming output from "
1302 "previous operation"
1303 )
1304
1305 while True:
1306 zresult = lib.ZSTD_compressStream2(
1307 self._compressor._cctx, self._out, self._in, lib.ZSTD_e_end
1308 )
1309 if lib.ZSTD_isError(zresult):
1310 raise ZstdError(
1311 "zstd compress error: %s" % _zstd_error(zresult)
1312 )
1313
1314 if self._out.pos:
1315 yield ffi.buffer(self._out.dst, self._out.pos)[:]
1316 self._out.pos = 0
1317
1318 if not zresult:
1319 self._finished = True
1320 return
1321
1322
1323 class ZstdCompressionReader(object):
1324 """Readable compressing stream wrapper.
1325
1326 ``ZstdCompressionReader`` is a read-only stream interface for obtaining
1327 compressed data from a source.
1328
1329 This type conforms to the ``io.RawIOBase`` interface and should be usable
1330 by any type that operates against a *file-object* (``typing.BinaryIO``
1331 in Python type hinting speak).
1332
1333 Instances are neither writable nor seekable (even if the underlying
1334 source is seekable). ``readline()`` and ``readlines()`` are not implemented
1335 because they don't make sense for compressed data. ``tell()`` returns the
1336 number of compressed bytes emitted so far.
1337
1338 Instances are obtained by calling :py:meth:`ZstdCompressor.stream_reader`.
1339
1340 In this example, we open a file for reading and then wrap that file
1341 handle with a stream from which compressed data can be ``read()``.
1342
1343 >>> with open(path, 'rb') as fh:
1344 ... cctx = zstandard.ZstdCompressor()
1345 ... reader = cctx.stream_reader(fh)
1346 ... while True:
1347 ... chunk = reader.read(16384)
1348 ... if not chunk:
1349 ... break
1350 ...
1351 ... # Do something with compressed chunk.
1352
1353 Instances can also be used as context managers:
1354
1355 >>> with open(path, 'rb') as fh:
1356 ... cctx = zstandard.ZstdCompressor()
1357 ... with cctx.stream_reader(fh) as reader:
1358 ... while True:
1359 ... chunk = reader.read(16384)
1360 ... if not chunk:
1361 ... break
1362 ...
1363 ... # Do something with compressed chunk.
1364
1365 When the context manager exits or ``close()`` is called, the stream is
1366 closed, underlying resources are released, and future operations against
1367 the compression stream will fail.
1368
1369 ``stream_reader()`` accepts a ``size`` argument specifying how large the
1370 input stream is. This is used to adjust compression parameters so they are
1371 tailored to the source size. e.g.
1372
1373 >>> with open(path, 'rb') as fh:
1374 ... cctx = zstandard.ZstdCompressor()
1375 ... with cctx.stream_reader(fh, size=os.stat(path).st_size) as reader:
1376 ... ...
1377
1378 If the ``source`` is a stream, you can specify how large ``read()``
1379 requests to that stream should be via the ``read_size`` argument.
1380 It defaults to ``zstandard.COMPRESSION_RECOMMENDED_INPUT_SIZE``. e.g.
1381
1382 >>> with open(path, 'rb') as fh:
1383 ... cctx = zstandard.ZstdCompressor()
1384 ... # Will perform fh.read(8192) when obtaining data to feed into the
1385 ... # compressor.
1386 ... with cctx.stream_reader(fh, read_size=8192) as reader:
1387 ... ...
1388 """
1389
1390 def __init__(self, compressor, source, read_size, closefd=True):
1391 self._compressor = compressor
1392 self._source = source
1393 self._read_size = read_size
1394 self._closefd = closefd
1395 self._entered = False
1396 self._closed = False
1397 self._bytes_compressed = 0
1398 self._finished_input = False
1399 self._finished_output = False
1400
1401 self._in_buffer = ffi.new("ZSTD_inBuffer *")
1402 # Holds a ref so backing bytes in self._in_buffer stay alive.
1403 self._source_buffer = None
1404
1405 def __enter__(self):
1406 if self._entered:
1407 raise ValueError("cannot __enter__ multiple times")
1408
1409 if self._closed:
1410 raise ValueError("stream is closed")
1411
1412 self._entered = True
1413 return self
1414
1415 def __exit__(self, exc_type, exc_value, exc_tb):
1416 self._entered = False
1417 self._compressor = None
1418 self.close()
1419 self._source = None
1420
1421 return False
1422
1423 def readable(self):
1424 return True
1425
1426 def writable(self):
1427 return False
1428
1429 def seekable(self):
1430 return False
1431
1432 def readline(self):
1433 raise io.UnsupportedOperation()
1434
1435 def readlines(self):
1436 raise io.UnsupportedOperation()
1437
1438 def write(self, data):
1439 raise OSError("stream is not writable")
1440
1441 def writelines(self, ignored):
1442 raise OSError("stream is not writable")
1443
1444 def isatty(self):
1445 return False
1446
1447 def flush(self):
1448 return None
1449
1450 def close(self):
1451 if self._closed:
1452 return
1453
1454 self._closed = True
1455
1456 f = getattr(self._source, "close", None)
1457 if self._closefd and f:
1458 f()
1459
1460 @property
1461 def closed(self):
1462 return self._closed
1463
1464 def tell(self):
1465 return self._bytes_compressed
1466
1467 def readall(self):
1468 chunks = []
1469
1470 while True:
1471 chunk = self.read(1048576)
1472 if not chunk:
1473 break
1474
1475 chunks.append(chunk)
1476
1477 return b"".join(chunks)
1478
1479 def __iter__(self):
1480 raise io.UnsupportedOperation()
1481
1482 def __next__(self):
1483 raise io.UnsupportedOperation()
1484
1485 next = __next__
1486
1487 def _read_input(self):
1488 if self._finished_input:
1489 return
1490
1491 if hasattr(self._source, "read"):
1492 data = self._source.read(self._read_size)
1493
1494 if not data:
1495 self._finished_input = True
1496 return
1497
1498 self._source_buffer = ffi.from_buffer(data)
1499 self._in_buffer.src = self._source_buffer
1500 self._in_buffer.size = len(self._source_buffer)
1501 self._in_buffer.pos = 0
1502 else:
1503 self._source_buffer = ffi.from_buffer(self._source)
1504 self._in_buffer.src = self._source_buffer
1505 self._in_buffer.size = len(self._source_buffer)
1506 self._in_buffer.pos = 0
1507
1508 def _compress_into_buffer(self, out_buffer):
1509 if self._in_buffer.pos >= self._in_buffer.size:
1510 return
1511
1512 old_pos = out_buffer.pos
1513
1514 zresult = lib.ZSTD_compressStream2(
1515 self._compressor._cctx,
1516 out_buffer,
1517 self._in_buffer,
1518 lib.ZSTD_e_continue,
1519 )
1520
1521 self._bytes_compressed += out_buffer.pos - old_pos
1522
1523 if self._in_buffer.pos == self._in_buffer.size:
1524 self._in_buffer.src = ffi.NULL
1525 self._in_buffer.pos = 0
1526 self._in_buffer.size = 0
1527 self._source_buffer = None
1528
1529 if not hasattr(self._source, "read"):
1530 self._finished_input = True
1531
1532 if lib.ZSTD_isError(zresult):
1533 raise ZstdError("zstd compress error: %s", _zstd_error(zresult))
1534
1535 return out_buffer.pos and out_buffer.pos == out_buffer.size
1536
1537 def read(self, size=-1):
1538 if self._closed:
1539 raise ValueError("stream is closed")
1540
1541 if size < -1:
1542 raise ValueError("cannot read negative amounts less than -1")
1543
1544 if size == -1:
1545 return self.readall()
1546
1547 if self._finished_output or size == 0:
1548 return b""
1549
1550 # Need a dedicated ref to dest buffer otherwise it gets collected.
1551 dst_buffer = ffi.new("char[]", size)
1552 out_buffer = ffi.new("ZSTD_outBuffer *")
1553 out_buffer.dst = dst_buffer
1554 out_buffer.size = size
1555 out_buffer.pos = 0
1556
1557 if self._compress_into_buffer(out_buffer):
1558 return ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
1559
1560 while not self._finished_input:
1561 self._read_input()
1562
1563 if self._compress_into_buffer(out_buffer):
1564 return ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
1565
1566 # EOF
1567 old_pos = out_buffer.pos
1568
1569 zresult = lib.ZSTD_compressStream2(
1570 self._compressor._cctx, out_buffer, self._in_buffer, lib.ZSTD_e_end
1571 )
1572
1573 self._bytes_compressed += out_buffer.pos - old_pos
1574
1575 if lib.ZSTD_isError(zresult):
1576 raise ZstdError(
1577 "error ending compression stream: %s", _zstd_error(zresult)
1578 )
1579
1580 if zresult == 0:
1581 self._finished_output = True
1582
1583 return ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
1584
1585 def read1(self, size=-1):
1586 if self._closed:
1587 raise ValueError("stream is closed")
1588
1589 if size < -1:
1590 raise ValueError("cannot read negative amounts less than -1")
1591
1592 if self._finished_output or size == 0:
1593 return b""
1594
1595 # -1 returns arbitrary number of bytes.
1596 if size == -1:
1597 size = COMPRESSION_RECOMMENDED_OUTPUT_SIZE
1598
1599 dst_buffer = ffi.new("char[]", size)
1600 out_buffer = ffi.new("ZSTD_outBuffer *")
1601 out_buffer.dst = dst_buffer
1602 out_buffer.size = size
1603 out_buffer.pos = 0
1604
1605 # read1() dictates that we can perform at most 1 call to the
1606 # underlying stream to get input. However, we can't satisfy this
1607 # restriction with compression because not all input generates output.
1608 # It is possible to perform a block flush in order to ensure output.
1609 # But this may not be desirable behavior. So we allow multiple read()
1610 # to the underlying stream. But unlike read(), we stop once we have
1611 # any output.
1612
1613 self._compress_into_buffer(out_buffer)
1614 if out_buffer.pos:
1615 return ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
1616
1617 while not self._finished_input:
1618 self._read_input()
1619
1620 # If we've filled the output buffer, return immediately.
1621 if self._compress_into_buffer(out_buffer):
1622 return ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
1623
1624 # If we've populated the output buffer and we're not at EOF,
1625 # also return, as we've satisfied the read1() limits.
1626 if out_buffer.pos and not self._finished_input:
1627 return ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
1628
1629 # Else if we're at EOS and we have room left in the buffer,
1630 # fall through to below and try to add more data to the output.
1631
1632 # EOF.
1633 old_pos = out_buffer.pos
1634
1635 zresult = lib.ZSTD_compressStream2(
1636 self._compressor._cctx, out_buffer, self._in_buffer, lib.ZSTD_e_end
1637 )
1638
1639 self._bytes_compressed += out_buffer.pos - old_pos
1640
1641 if lib.ZSTD_isError(zresult):
1642 raise ZstdError(
1643 "error ending compression stream: %s" % _zstd_error(zresult)
1644 )
1645
1646 if zresult == 0:
1647 self._finished_output = True
1648
1649 return ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
1650
1651 def readinto(self, b):
1652 if self._closed:
1653 raise ValueError("stream is closed")
1654
1655 if self._finished_output:
1656 return 0
1657
1658 # TODO use writable=True once we require CFFI >= 1.12.
1659 dest_buffer = ffi.from_buffer(b)
1660 ffi.memmove(b, b"", 0)
1661 out_buffer = ffi.new("ZSTD_outBuffer *")
1662 out_buffer.dst = dest_buffer
1663 out_buffer.size = len(dest_buffer)
1664 out_buffer.pos = 0
1665
1666 if self._compress_into_buffer(out_buffer):
1667 return out_buffer.pos
1668
1669 while not self._finished_input:
1670 self._read_input()
1671 if self._compress_into_buffer(out_buffer):
1672 return out_buffer.pos
1673
1674 # EOF.
1675 old_pos = out_buffer.pos
1676 zresult = lib.ZSTD_compressStream2(
1677 self._compressor._cctx, out_buffer, self._in_buffer, lib.ZSTD_e_end
1678 )
1679
1680 self._bytes_compressed += out_buffer.pos - old_pos
1681
1682 if lib.ZSTD_isError(zresult):
1683 raise ZstdError(
1684 "error ending compression stream: %s", _zstd_error(zresult)
1685 )
1686
1687 if zresult == 0:
1688 self._finished_output = True
1689
1690 return out_buffer.pos
1691
1692 def readinto1(self, b):
1693 if self._closed:
1694 raise ValueError("stream is closed")
1695
1696 if self._finished_output:
1697 return 0
1698
1699 # TODO use writable=True once we require CFFI >= 1.12.
1700 dest_buffer = ffi.from_buffer(b)
1701 ffi.memmove(b, b"", 0)
1702
1703 out_buffer = ffi.new("ZSTD_outBuffer *")
1704 out_buffer.dst = dest_buffer
1705 out_buffer.size = len(dest_buffer)
1706 out_buffer.pos = 0
1707
1708 self._compress_into_buffer(out_buffer)
1709 if out_buffer.pos:
1710 return out_buffer.pos
1711
1712 while not self._finished_input:
1713 self._read_input()
1714
1715 if self._compress_into_buffer(out_buffer):
1716 return out_buffer.pos
1717
1718 if out_buffer.pos and not self._finished_input:
1719 return out_buffer.pos
1720
1721 # EOF.
1722 old_pos = out_buffer.pos
1723
1724 zresult = lib.ZSTD_compressStream2(
1725 self._compressor._cctx, out_buffer, self._in_buffer, lib.ZSTD_e_end
1726 )
1727
1728 self._bytes_compressed += out_buffer.pos - old_pos
1729
1730 if lib.ZSTD_isError(zresult):
1731 raise ZstdError(
1732 "error ending compression stream: %s" % _zstd_error(zresult)
1733 )
1734
1735 if zresult == 0:
1736 self._finished_output = True
1737
1738 return out_buffer.pos
1739
1740
1741 class ZstdCompressor(object):
1742 """
1743 Create an object used to perform Zstandard compression.
1744
1745 Each instance is essentially a wrapper around a ``ZSTD_CCtx`` from
1746 zstd's C API.
1747
1748 An instance can compress data various ways. Instances can be used
1749 multiple times. Each compression operation will use the compression
1750 parameters defined at construction time.
1751
1752 .. note:
1753
1754 When using a compression dictionary and multiple compression
1755 operations are performed, the ``ZstdCompressionParameters`` derived
1756 from an integer compression ``level`` and the first compressed data's
1757 size will be reused for all subsequent operations. This may not be
1758 desirable if source data sizes vary significantly.
1759
1760 ``compression_params`` is mutually exclusive with ``level``,
1761 ``write_checksum``, ``write_content_size``, ``write_dict_id``, and
1762 ``threads``.
1763
1764 Assume that each ``ZstdCompressor`` instance can only handle a single
1765 logical compression operation at the same time. i.e. if you call a method
1766 like ``stream_reader()`` to obtain multiple objects derived from the same
1767 ``ZstdCompressor`` instance and attempt to use them simultaneously, errors
1768 will likely occur.
1769
1770 If you need to perform multiple logical compression operations and you
1771 can't guarantee those operations are temporally non-overlapping, you need
1772 to obtain multiple ``ZstdCompressor`` instances.
1773
1774 Unless specified otherwise, assume that no two methods of
1775 ``ZstdCompressor`` instances can be called from multiple Python
1776 threads simultaneously. In other words, assume instances are not thread safe
1777 unless stated otherwise.
1778
1779 :param level:
1780 Integer compression level. Valid values are all negative integers
1781 through 22. Lower values generally yield faster operations with lower
1782 compression ratios. Higher values are generally slower but compress
1783 better. The default is 3, which is what the ``zstd`` CLI uses. Negative
1784 levels effectively engage ``--fast`` mode from the ``zstd`` CLI.
1785 :param dict_data:
1786 A ``ZstdCompressionDict`` to be used to compress with dictionary
1787 data.
1788 :param compression_params:
1789 A ``ZstdCompressionParameters`` instance defining low-level compression
1790 parameters. If defined, this will overwrite the ``level`` argument.
1791 :param write_checksum:
1792 If True, a 4 byte content checksum will be written with the compressed
1793 data, allowing the decompressor to perform content verification.
1794 :param write_content_size:
1795 If True (the default), the decompressed content size will be included
1796 in the header of the compressed data. This data will only be written if
1797 the compressor knows the size of the input data.
1798 :param write_dict_id:
1799 Determines whether the dictionary ID will be written into the compressed
1800 data. Defaults to True. Only adds content to the compressed data if
1801 a dictionary is being used.
1802 :param threads:
1803 Number of threads to use to compress data concurrently. When set,
1804 compression operations are performed on multiple threads. The default
1805 value (0) disables multi-threaded compression. A value of ``-1`` means
1806 to set the number of threads to the number of detected logical CPUs.
1807 """
1808
1809 def __init__(
1810 self,
1811 level=3,
1812 dict_data=None,
1813 compression_params=None,
1814 write_checksum=None,
1815 write_content_size=None,
1816 write_dict_id=None,
1817 threads=0,
1818 ):
1819 if level > lib.ZSTD_maxCLevel():
1820 raise ValueError(
1821 "level must be less than %d" % lib.ZSTD_maxCLevel()
1822 )
1823
1824 if threads < 0:
1825 threads = _cpu_count()
1826
1827 if compression_params and write_checksum is not None:
1828 raise ValueError(
1829 "cannot define compression_params and " "write_checksum"
1830 )
1831
1832 if compression_params and write_content_size is not None:
1833 raise ValueError(
1834 "cannot define compression_params and " "write_content_size"
1835 )
1836
1837 if compression_params and write_dict_id is not None:
1838 raise ValueError(
1839 "cannot define compression_params and " "write_dict_id"
1840 )
1841
1842 if compression_params and threads:
1843 raise ValueError("cannot define compression_params and threads")
1844
1845 if compression_params:
1846 self._params = _make_cctx_params(compression_params)
1847 else:
1848 if write_dict_id is None:
1849 write_dict_id = True
1850
1851 params = lib.ZSTD_createCCtxParams()
1852 if params == ffi.NULL:
1853 raise MemoryError()
1854
1855 self._params = ffi.gc(params, lib.ZSTD_freeCCtxParams)
1856
1857 _set_compression_parameter(
1858 self._params, lib.ZSTD_c_compressionLevel, level
1859 )
1860
1861 _set_compression_parameter(
1862 self._params,
1863 lib.ZSTD_c_contentSizeFlag,
1864 write_content_size if write_content_size is not None else 1,
1865 )
1866
1867 _set_compression_parameter(
1868 self._params,
1869 lib.ZSTD_c_checksumFlag,
1870 1 if write_checksum else 0,
1871 )
1872
1873 _set_compression_parameter(
1874 self._params, lib.ZSTD_c_dictIDFlag, 1 if write_dict_id else 0
1875 )
1876
1877 if threads:
1878 _set_compression_parameter(
1879 self._params, lib.ZSTD_c_nbWorkers, threads
1880 )
1881
1882 cctx = lib.ZSTD_createCCtx()
1883 if cctx == ffi.NULL:
1884 raise MemoryError()
1885
1886 self._cctx = cctx
1887 self._dict_data = dict_data
1888
1889 # We defer setting up garbage collection until after calling
1890 # _setup_cctx() to ensure the memory size estimate is more accurate.
1891 try:
1892 self._setup_cctx()
1893 finally:
1894 self._cctx = ffi.gc(
1895 cctx, lib.ZSTD_freeCCtx, size=lib.ZSTD_sizeof_CCtx(cctx)
1896 )
1897
1898 def _setup_cctx(self):
1899 zresult = lib.ZSTD_CCtx_setParametersUsingCCtxParams(
1900 self._cctx, self._params
1901 )
1902 if lib.ZSTD_isError(zresult):
1903 raise ZstdError(
1904 "could not set compression parameters: %s"
1905 % _zstd_error(zresult)
1906 )
1907
1908 dict_data = self._dict_data
1909
1910 if dict_data:
1911 if dict_data._cdict:
1912 zresult = lib.ZSTD_CCtx_refCDict(self._cctx, dict_data._cdict)
1913 else:
1914 zresult = lib.ZSTD_CCtx_loadDictionary_advanced(
1915 self._cctx,
1916 dict_data.as_bytes(),
1917 len(dict_data),
1918 lib.ZSTD_dlm_byRef,
1919 dict_data._dict_type,
1920 )
1921
1922 if lib.ZSTD_isError(zresult):
1923 raise ZstdError(
1924 "could not load compression dictionary: %s"
1925 % _zstd_error(zresult)
1926 )
1927
1928 def memory_size(self):
1929 """Obtain the memory usage of this compressor, in bytes.
1930
1931 >>> cctx = zstandard.ZstdCompressor()
1932 >>> memory = cctx.memory_size()
1933 """
1934 return lib.ZSTD_sizeof_CCtx(self._cctx)
1935
1936 def compress(self, data):
1937 """
1938 Compress data in a single operation.
1939
1940 This is the simplest mechanism to perform compression: simply pass in a
1941 value and get a compressed value back. It is almost the most prone to
1942 abuse.
1943
1944 The input and output values must fit in memory, so passing in very large
1945 values can result in excessive memory usage. For this reason, one of the
1946 streaming based APIs is preferred for larger values.
1947
1948 :param data:
1949 Source data to compress
1950 :return:
1951 Compressed data
1952
1953 >>> cctx = zstandard.ZstdCompressor()
1954 >>> compressed = cctx.compress(b"data to compress")
1955 """
1956 lib.ZSTD_CCtx_reset(self._cctx, lib.ZSTD_reset_session_only)
1957
1958 data_buffer = ffi.from_buffer(data)
1959
1960 dest_size = lib.ZSTD_compressBound(len(data_buffer))
1961 out = new_nonzero("char[]", dest_size)
1962
1963 zresult = lib.ZSTD_CCtx_setPledgedSrcSize(self._cctx, len(data_buffer))
1964 if lib.ZSTD_isError(zresult):
1965 raise ZstdError(
1966 "error setting source size: %s" % _zstd_error(zresult)
1967 )
1968
1969 out_buffer = ffi.new("ZSTD_outBuffer *")
1970 in_buffer = ffi.new("ZSTD_inBuffer *")
1971
1972 out_buffer.dst = out
1973 out_buffer.size = dest_size
1974 out_buffer.pos = 0
1975
1976 in_buffer.src = data_buffer
1977 in_buffer.size = len(data_buffer)
1978 in_buffer.pos = 0
1979
1980 zresult = lib.ZSTD_compressStream2(
1981 self._cctx, out_buffer, in_buffer, lib.ZSTD_e_end
1982 )
1983
1984 if lib.ZSTD_isError(zresult):
1985 raise ZstdError("cannot compress: %s" % _zstd_error(zresult))
1986 elif zresult:
1987 raise ZstdError("unexpected partial frame flush")
1988
1989 return ffi.buffer(out, out_buffer.pos)[:]
1990
1991 def compressobj(self, size=-1):
1992 """
1993 Obtain a compressor exposing the Python standard library compression API.
1994
1995 See :py:class:`ZstdCompressionObj` for the full documentation.
1996
1997 :param size:
1998 Size in bytes of data that will be compressed.
1999 :return:
2000 :py:class:`ZstdCompressionObj`
2001 """
2002 lib.ZSTD_CCtx_reset(self._cctx, lib.ZSTD_reset_session_only)
2003
2004 if size < 0:
2005 size = lib.ZSTD_CONTENTSIZE_UNKNOWN
2006
2007 zresult = lib.ZSTD_CCtx_setPledgedSrcSize(self._cctx, size)
2008 if lib.ZSTD_isError(zresult):
2009 raise ZstdError(
2010 "error setting source size: %s" % _zstd_error(zresult)
2011 )
2012
2013 cobj = ZstdCompressionObj(self, COMPRESSION_RECOMMENDED_OUTPUT_SIZE)
2014
2015 return cobj
2016
2017 def chunker(self, size=-1, chunk_size=COMPRESSION_RECOMMENDED_OUTPUT_SIZE):
2018 """
2019 Create an object for iterative compressing to same-sized chunks.
2020
2021 This API is similar to :py:meth:`ZstdCompressor.compressobj` but has
2022 better performance properties.
2023
2024 :param size:
2025 Size in bytes of data that will be compressed.
2026 :param chunk_size:
2027 Size of compressed chunks.
2028 :return:
2029 :py:class:`ZstdCompressionChunker`
2030 """
2031 lib.ZSTD_CCtx_reset(self._cctx, lib.ZSTD_reset_session_only)
2032
2033 if size < 0:
2034 size = lib.ZSTD_CONTENTSIZE_UNKNOWN
2035
2036 zresult = lib.ZSTD_CCtx_setPledgedSrcSize(self._cctx, size)
2037 if lib.ZSTD_isError(zresult):
2038 raise ZstdError(
2039 "error setting source size: %s" % _zstd_error(zresult)
2040 )
2041
2042 return ZstdCompressionChunker(self, chunk_size=chunk_size)
2043
2044 def copy_stream(
2045 self,
2046 ifh,
2047 ofh,
2048 size=-1,
2049 read_size=COMPRESSION_RECOMMENDED_INPUT_SIZE,
2050 write_size=COMPRESSION_RECOMMENDED_OUTPUT_SIZE,
2051 ):
2052 """
2053 Copy data between 2 streams while compressing it.
2054
2055 Data will be read from ``ifh``, compressed, and written to ``ofh``.
2056 ``ifh`` must have a ``read(size)`` method. ``ofh`` must have a
2057 ``write(data)``
2058 method.
2059
2060 >>> cctx = zstandard.ZstdCompressor()
2061 >>> with open(input_path, "rb") as ifh, open(output_path, "wb") as ofh:
2062 ... cctx.copy_stream(ifh, ofh)
2063
2064 It is also possible to declare the size of the source stream:
2065
2066 >>> cctx = zstandard.ZstdCompressor()
2067 >>> cctx.copy_stream(ifh, ofh, size=len_of_input)
2068
2069 You can also specify how large the chunks that are ``read()``
2070 and ``write()`` from and to the streams:
2071
2072 >>> cctx = zstandard.ZstdCompressor()
2073 >>> cctx.copy_stream(ifh, ofh, read_size=32768, write_size=16384)
2074
2075 The stream copier returns a 2-tuple of bytes read and written:
2076
2077 >>> cctx = zstandard.ZstdCompressor()
2078 >>> read_count, write_count = cctx.copy_stream(ifh, ofh)
2079
2080 :param ifh:
2081 Source stream to read from
2082 :param ofh:
2083 Destination stream to write to
2084 :param size:
2085 Size in bytes of the source stream. If defined, compression
2086 parameters will be tuned for this size.
2087 :param read_size:
2088 Chunk sizes that source stream should be ``read()`` from.
2089 :param write_size:
2090 Chunk sizes that destination stream should be ``write()`` to.
2091 :return:
2092 2-tuple of ints of bytes read and written, respectively.
2093 """
2094
2095 if not hasattr(ifh, "read"):
2096 raise ValueError("first argument must have a read() method")
2097 if not hasattr(ofh, "write"):
2098 raise ValueError("second argument must have a write() method")
2099
2100 lib.ZSTD_CCtx_reset(self._cctx, lib.ZSTD_reset_session_only)
2101
2102 if size < 0:
2103 size = lib.ZSTD_CONTENTSIZE_UNKNOWN
2104
2105 zresult = lib.ZSTD_CCtx_setPledgedSrcSize(self._cctx, size)
2106 if lib.ZSTD_isError(zresult):
2107 raise ZstdError(
2108 "error setting source size: %s" % _zstd_error(zresult)
2109 )
2110
2111 in_buffer = ffi.new("ZSTD_inBuffer *")
2112 out_buffer = ffi.new("ZSTD_outBuffer *")
2113
2114 dst_buffer = ffi.new("char[]", write_size)
2115 out_buffer.dst = dst_buffer
2116 out_buffer.size = write_size
2117 out_buffer.pos = 0
2118
2119 total_read, total_write = 0, 0
2120
2121 while True:
2122 data = ifh.read(read_size)
2123 if not data:
2124 break
2125
2126 data_buffer = ffi.from_buffer(data)
2127 total_read += len(data_buffer)
2128 in_buffer.src = data_buffer
2129 in_buffer.size = len(data_buffer)
2130 in_buffer.pos = 0
2131
2132 while in_buffer.pos < in_buffer.size:
2133 zresult = lib.ZSTD_compressStream2(
2134 self._cctx, out_buffer, in_buffer, lib.ZSTD_e_continue
2135 )
2136 if lib.ZSTD_isError(zresult):
2137 raise ZstdError(
2138 "zstd compress error: %s" % _zstd_error(zresult)
2139 )
2140
2141 if out_buffer.pos:
2142 ofh.write(ffi.buffer(out_buffer.dst, out_buffer.pos))
2143 total_write += out_buffer.pos
2144 out_buffer.pos = 0
2145
2146 # We've finished reading. Flush the compressor.
2147 while True:
2148 zresult = lib.ZSTD_compressStream2(
2149 self._cctx, out_buffer, in_buffer, lib.ZSTD_e_end
2150 )
2151 if lib.ZSTD_isError(zresult):
2152 raise ZstdError(
2153 "error ending compression stream: %s" % _zstd_error(zresult)
2154 )
2155
2156 if out_buffer.pos:
2157 ofh.write(ffi.buffer(out_buffer.dst, out_buffer.pos))
2158 total_write += out_buffer.pos
2159 out_buffer.pos = 0
2160
2161 if zresult == 0:
2162 break
2163
2164 return total_read, total_write
2165
2166 def stream_reader(
2167 self,
2168 source,
2169 size=-1,
2170 read_size=COMPRESSION_RECOMMENDED_INPUT_SIZE,
2171 closefd=True,
2172 ):
2173 """
2174 Wrap a readable source with a stream that can read compressed data.
2175
2176 This will produce an object conforming to the ``io.RawIOBase``
2177 interface which can be ``read()`` from to retrieve compressed data
2178 from a source.
2179
2180 The source object can be any object with a ``read(size)`` method
2181 or an object that conforms to the buffer protocol.
2182
2183 See :py:class:`ZstdCompressionReader` for type documentation and usage
2184 examples.
2185
2186 :param source:
2187 Object to read source data from
2188 :param size:
2189 Size in bytes of source object.
2190 :param read_size:
2191 How many bytes to request when ``read()``'ing from the source.
2192 :param closefd:
2193 Whether to close the source stream when the returned stream is
2194 closed.
2195 :return:
2196 :py:class:`ZstdCompressionReader`
2197 """
2198 lib.ZSTD_CCtx_reset(self._cctx, lib.ZSTD_reset_session_only)
2199
2200 try:
2201 size = len(source)
2202 except Exception:
2203 pass
2204
2205 if size < 0:
2206 size = lib.ZSTD_CONTENTSIZE_UNKNOWN
2207
2208 zresult = lib.ZSTD_CCtx_setPledgedSrcSize(self._cctx, size)
2209 if lib.ZSTD_isError(zresult):
2210 raise ZstdError(
2211 "error setting source size: %s" % _zstd_error(zresult)
2212 )
2213
2214 return ZstdCompressionReader(self, source, read_size, closefd=closefd)
2215
2216 def stream_writer(
2217 self,
2218 writer,
2219 size=-1,
2220 write_size=COMPRESSION_RECOMMENDED_OUTPUT_SIZE,
2221 write_return_read=True,
2222 closefd=True,
2223 ):
2224 """
2225 Create a stream that will write compressed data into another stream.
2226
2227 The argument to ``stream_writer()`` must have a ``write(data)`` method.
2228 As compressed data is available, ``write()`` will be called with the
2229 compressed data as its argument. Many common Python types implement
2230 ``write()``, including open file handles and ``io.BytesIO``.
2231
2232 See :py:class:`ZstdCompressionWriter` for more documentation, including
2233 usage examples.
2234
2235 :param writer:
2236 Stream to write compressed data to.
2237 :param size:
2238 Size in bytes of data to be compressed. If set, it will be used
2239 to influence compression parameter tuning and could result in the
2240 size being written into the header of the compressed data.
2241 :param write_size:
2242 How much data to ``write()`` to ``writer`` at a time.
2243 :param write_return_read:
2244 Whether ``write()`` should return the number of bytes that were
2245 consumed from the input.
2246 :param closefd:
2247 Whether to ``close`` the ``writer`` when this stream is closed.
2248 :return:
2249 :py:class:`ZstdCompressionWriter`
2250 """
2251 if not hasattr(writer, "write"):
2252 raise ValueError("must pass an object with a write() method")
2253
2254 lib.ZSTD_CCtx_reset(self._cctx, lib.ZSTD_reset_session_only)
2255
2256 if size < 0:
2257 size = lib.ZSTD_CONTENTSIZE_UNKNOWN
2258
2259 return ZstdCompressionWriter(
2260 self, writer, size, write_size, write_return_read, closefd=closefd
2261 )
2262
2263 def read_to_iter(
2264 self,
2265 reader,
2266 size=-1,
2267 read_size=COMPRESSION_RECOMMENDED_INPUT_SIZE,
2268 write_size=COMPRESSION_RECOMMENDED_OUTPUT_SIZE,
2269 ):
2270 """
2271 Read uncompressed data from a reader and return an iterator
2272
2273 Returns an iterator of compressed data produced from reading from
2274 ``reader``.
2275
2276 This method provides a mechanism to stream compressed data out of a
2277 source as an iterator of data chunks.
2278
2279 Uncompressed data will be obtained from ``reader`` by calling the
2280 ``read(size)`` method of it or by reading a slice (if ``reader``
2281 conforms to the *buffer protocol*). The source data will be streamed
2282 into a compressor. As compressed data is available, it will be exposed
2283 to the iterator.
2284
2285 Data is read from the source in chunks of ``read_size``. Compressed
2286 chunks are at most ``write_size`` bytes. Both values default to the
2287 zstd input and and output defaults, respectively.
2288
2289 If reading from the source via ``read()``, ``read()`` will be called
2290 until it raises or returns an empty bytes (``b""``). It is perfectly
2291 valid for the source to deliver fewer bytes than were what requested
2292 by ``read(size)``.
2293
2294 The caller is partially in control of how fast data is fed into the
2295 compressor by how it consumes the returned iterator. The compressor
2296 will not consume from the reader unless the caller consumes from the
2297 iterator.
2298
2299 >>> cctx = zstandard.ZstdCompressor()
2300 >>> for chunk in cctx.read_to_iter(fh):
2301 ... # Do something with emitted data.
2302
2303 ``read_to_iter()`` accepts a ``size`` argument declaring the size of
2304 the input stream:
2305
2306 >>> cctx = zstandard.ZstdCompressor()
2307 >>> for chunk in cctx.read_to_iter(fh, size=some_int):
2308 >>> pass
2309
2310 You can also control the size that data is ``read()`` from the source
2311 and the ideal size of output chunks:
2312
2313 >>> cctx = zstandard.ZstdCompressor()
2314 >>> for chunk in cctx.read_to_iter(fh, read_size=16384, write_size=8192):
2315 >>> pass
2316
2317 ``read_to_iter()`` does not give direct control over the sizes of chunks
2318 fed into the compressor. Instead, chunk sizes will be whatever the object
2319 being read from delivers. These will often be of a uniform size.
2320
2321 :param reader:
2322 Stream providing data to be compressed.
2323 :param size:
2324 Size in bytes of input data.
2325 :param read_size:
2326 Controls how many bytes are ``read()`` from the source.
2327 :param write_size:
2328 Controls the output size of emitted chunks.
2329 :return:
2330 Iterator of ``bytes``.
2331 """
2332
2333 if hasattr(reader, "read"):
2334 have_read = True
2335 elif hasattr(reader, "__getitem__"):
2336 have_read = False
2337 buffer_offset = 0
2338 size = len(reader)
2339 else:
2340 raise ValueError(
2341 "must pass an object with a read() method or "
2342 "conforms to buffer protocol"
2343 )
2344
2345 lib.ZSTD_CCtx_reset(self._cctx, lib.ZSTD_reset_session_only)
2346
2347 if size < 0:
2348 size = lib.ZSTD_CONTENTSIZE_UNKNOWN
2349
2350 zresult = lib.ZSTD_CCtx_setPledgedSrcSize(self._cctx, size)
2351 if lib.ZSTD_isError(zresult):
2352 raise ZstdError(
2353 "error setting source size: %s" % _zstd_error(zresult)
2354 )
2355
2356 in_buffer = ffi.new("ZSTD_inBuffer *")
2357 out_buffer = ffi.new("ZSTD_outBuffer *")
2358
2359 in_buffer.src = ffi.NULL
2360 in_buffer.size = 0
2361 in_buffer.pos = 0
2362
2363 dst_buffer = ffi.new("char[]", write_size)
2364 out_buffer.dst = dst_buffer
2365 out_buffer.size = write_size
2366 out_buffer.pos = 0
2367
2368 while True:
2369 # We should never have output data sitting around after a previous
2370 # iteration.
2371 assert out_buffer.pos == 0
2372
2373 # Collect input data.
2374 if have_read:
2375 read_result = reader.read(read_size)
2376 else:
2377 remaining = len(reader) - buffer_offset
2378 slice_size = min(remaining, read_size)
2379 read_result = reader[buffer_offset : buffer_offset + slice_size]
2380 buffer_offset += slice_size
2381
2382 # No new input data. Break out of the read loop.
2383 if not read_result:
2384 break
2385
2386 # Feed all read data into the compressor and emit output until
2387 # exhausted.
2388 read_buffer = ffi.from_buffer(read_result)
2389 in_buffer.src = read_buffer
2390 in_buffer.size = len(read_buffer)
2391 in_buffer.pos = 0
2392
2393 while in_buffer.pos < in_buffer.size:
2394 zresult = lib.ZSTD_compressStream2(
2395 self._cctx, out_buffer, in_buffer, lib.ZSTD_e_continue
2396 )
2397 if lib.ZSTD_isError(zresult):
2398 raise ZstdError(
2399 "zstd compress error: %s" % _zstd_error(zresult)
2400 )
2401
2402 if out_buffer.pos:
2403 data = ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
2404 out_buffer.pos = 0
2405 yield data
2406
2407 assert out_buffer.pos == 0
2408
2409 # And repeat the loop to collect more data.
2410 continue
2411
2412 # If we get here, input is exhausted. End the stream and emit what
2413 # remains.
2414 while True:
2415 assert out_buffer.pos == 0
2416 zresult = lib.ZSTD_compressStream2(
2417 self._cctx, out_buffer, in_buffer, lib.ZSTD_e_end
2418 )
2419 if lib.ZSTD_isError(zresult):
2420 raise ZstdError(
2421 "error ending compression stream: %s" % _zstd_error(zresult)
2422 )
2423
2424 if out_buffer.pos:
2425 data = ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
2426 out_buffer.pos = 0
2427 yield data
2428
2429 if zresult == 0:
2430 break
2431
2432 def multi_compress_to_buffer(self, data, threads=-1):
2433 """
2434 Compress multiple pieces of data as a single function call.
2435
2436 (Experimental. Not yet supported by CFFI backend.)
2437
2438 This function is optimized to perform multiple compression operations
2439 as as possible with as little overhead as possible.
2440
2441 Data to be compressed can be passed as a ``BufferWithSegmentsCollection``,
2442 a ``BufferWithSegments``, or a list containing byte like objects. Each
2443 element of the container will be compressed individually using the
2444 configured parameters on the ``ZstdCompressor`` instance.
2445
2446 The ``threads`` argument controls how many threads to use for
2447 compression. The default is ``0`` which means to use a single thread.
2448 Negative values use the number of logical CPUs in the machine.
2449
2450 The function returns a ``BufferWithSegmentsCollection``. This type
2451 represents N discrete memory allocations, each holding 1 or more
2452 compressed frames.
2453
2454 Output data is written to shared memory buffers. This means that unlike
2455 regular Python objects, a reference to *any* object within the collection
2456 keeps the shared buffer and therefore memory backing it alive. This can
2457 have undesirable effects on process memory usage.
2458
2459 The API and behavior of this function is experimental and will likely
2460 change. Known deficiencies include:
2461
2462 * If asked to use multiple threads, it will always spawn that many
2463 threads, even if the input is too small to use them. It should
2464 automatically lower the thread count when the extra threads would
2465 just add overhead.
2466 * The buffer allocation strategy is fixed. There is room to make it
2467 dynamic, perhaps even to allow one output buffer per input,
2468 facilitating a variation of the API to return a list without the
2469 adverse effects of shared memory buffers.
2470
2471 :param data:
2472 Source to read discrete pieces of data to compress.
2473
2474 Can be a ``BufferWithSegmentsCollection``, a ``BufferWithSegments``,
2475 or a ``list[bytes]``.
2476 :return:
2477 BufferWithSegmentsCollection holding compressed data.
2478 """
2479 raise NotImplementedError()
2480
2481 def frame_progression(self):
2482 """
2483 Return information on how much work the compressor has done.
2484
2485 Returns a 3-tuple of (ingested, consumed, produced).
2486
2487 >>> cctx = zstandard.ZstdCompressor()
2488 >>> (ingested, consumed, produced) = cctx.frame_progression()
2489 """
2490 progression = lib.ZSTD_getFrameProgression(self._cctx)
2491
2492 return progression.ingested, progression.consumed, progression.produced
2493
2494
2495 class FrameParameters(object):
2496 """Information about a zstd frame.
2497
2498 Instances have the following attributes:
2499
2500 ``content_size``
2501 Integer size of original, uncompressed content. This will be ``0`` if the
2502 original content size isn't written to the frame (controlled with the
2503 ``write_content_size`` argument to ``ZstdCompressor``) or if the input
2504 content size was ``0``.
2505
2506 ``window_size``
2507 Integer size of maximum back-reference distance in compressed data.
2508
2509 ``dict_id``
2510 Integer of dictionary ID used for compression. ``0`` if no dictionary
2511 ID was used or if the dictionary ID was ``0``.
2512
2513 ``has_checksum``
2514 Bool indicating whether a 4 byte content checksum is stored at the end
2515 of the frame.
2516 """
2517
2518 def __init__(self, fparams):
2519 self.content_size = fparams.frameContentSize
2520 self.window_size = fparams.windowSize
2521 self.dict_id = fparams.dictID
2522 self.has_checksum = bool(fparams.checksumFlag)
2523
2524
2525 def frame_content_size(data):
2526 """Obtain the decompressed size of a frame.
2527
2528 The returned value is usually accurate. But strictly speaking it should
2529 not be trusted.
2530
2531 :return:
2532 ``-1`` if size unknown and a non-negative integer otherwise.
2533 """
2534 data_buffer = ffi.from_buffer(data)
2535
2536 size = lib.ZSTD_getFrameContentSize(data_buffer, len(data_buffer))
2537
2538 if size == lib.ZSTD_CONTENTSIZE_ERROR:
2539 raise ZstdError("error when determining content size")
2540 elif size == lib.ZSTD_CONTENTSIZE_UNKNOWN:
2541 return -1
2542 else:
2543 return size
2544
2545
2546 def frame_header_size(data):
2547 """Obtain the size of a frame header.
2548
2549 :return:
2550 Integer size in bytes.
2551 """
2552 data_buffer = ffi.from_buffer(data)
2553
2554 zresult = lib.ZSTD_frameHeaderSize(data_buffer, len(data_buffer))
2555 if lib.ZSTD_isError(zresult):
2556 raise ZstdError(
2557 "could not determine frame header size: %s" % _zstd_error(zresult)
2558 )
2559
2560 return zresult
2561
2562
2563 def get_frame_parameters(data):
2564 """
2565 Parse a zstd frame header into frame parameters.
2566
2567 Depending on which fields are present in the frame and their values, the
2568 length of the frame parameters varies. If insufficient bytes are passed
2569 in to fully parse the frame parameters, ``ZstdError`` is raised. To ensure
2570 frame parameters can be parsed, pass in at least 18 bytes.
2571
2572 :param data:
2573 Data from which to read frame parameters.
2574 :return:
2575 :py:class:`FrameParameters`
2576 """
2577 params = ffi.new("ZSTD_frameHeader *")
2578
2579 data_buffer = ffi.from_buffer(data)
2580 zresult = lib.ZSTD_getFrameHeader(params, data_buffer, len(data_buffer))
2581 if lib.ZSTD_isError(zresult):
2582 raise ZstdError(
2583 "cannot get frame parameters: %s" % _zstd_error(zresult)
2584 )
2585
2586 if zresult:
2587 raise ZstdError(
2588 "not enough data for frame parameters; need %d bytes" % zresult
2589 )
2590
2591 return FrameParameters(params[0])
2592
2593
2594 class ZstdCompressionDict(object):
2595 """Represents a computed compression dictionary.
2596
2597 Instances are obtained by calling :py:func:`train_dictionary` or by
2598 passing bytes obtained from another source into the constructor.
2599
2600 Instances can be constructed from bytes:
2601
2602 >>> dict_data = zstandard.ZstdCompressionDict(data)
2603
2604 It is possible to construct a dictionary from *any* data. If the data
2605 doesn't begin with a magic header, it will be treated as a *prefix*
2606 dictionary. *Prefix* dictionaries allow compression operations to
2607 reference raw data within the dictionary.
2608
2609 It is possible to force the use of *prefix* dictionaries or to require
2610 a dictionary header:
2611
2612 >>> dict_data = zstandard.ZstdCompressionDict(data, dict_type=zstandard.DICT_TYPE_RAWCONTENT)
2613 >>> dict_data = zstandard.ZstdCompressionDict(data, dict_type=zstandard.DICT_TYPE_FULLDICT)
2614
2615 You can see how many bytes are in the dictionary by calling ``len()``:
2616
2617 >>> dict_data = zstandard.train_dictionary(size, samples)
2618 >>> dict_size = len(dict_data) # will not be larger than ``size``
2619
2620 Once you have a dictionary, you can pass it to the objects performing
2621 compression and decompression:
2622
2623 >>> dict_data = zstandard.train_dictionary(131072, samples)
2624 >>> cctx = zstandard.ZstdCompressor(dict_data=dict_data)
2625 >>> for source_data in input_data:
2626 ... compressed = cctx.compress(source_data)
2627 ... # Do something with compressed data.
2628 ...
2629 >>> dctx = zstandard.ZstdDecompressor(dict_data=dict_data)
2630 >>> for compressed_data in input_data:
2631 ... buffer = io.BytesIO()
2632 ... with dctx.stream_writer(buffer) as decompressor:
2633 ... decompressor.write(compressed_data)
2634 ... # Do something with raw data in ``buffer``.
2635
2636 Dictionaries have unique integer IDs. You can retrieve this ID via:
2637
2638 >>> dict_id = zstandard.dictionary_id(dict_data)
2639
2640 You can obtain the raw data in the dict (useful for persisting and constructing
2641 a ``ZstdCompressionDict`` later) via ``as_bytes()``:
2642
2643 >>> dict_data = zstandard.train_dictionary(size, samples)
2644 >>> raw_data = dict_data.as_bytes()
2645
2646 By default, when a ``ZstdCompressionDict`` is *attached* to a
2647 ``ZstdCompressor``, each ``ZstdCompressor`` performs work to prepare the
2648 dictionary for use. This is fine if only 1 compression operation is being
2649 performed or if the ``ZstdCompressor`` is being reused for multiple operations.
2650 But if multiple ``ZstdCompressor`` instances are being used with the dictionary,
2651 this can add overhead.
2652
2653 It is possible to *precompute* the dictionary so it can readily be consumed
2654 by multiple ``ZstdCompressor`` instances:
2655
2656 >>> d = zstandard.ZstdCompressionDict(data)
2657 >>> # Precompute for compression level 3.
2658 >>> d.precompute_compress(level=3)
2659 >>> # Precompute with specific compression parameters.
2660 >>> params = zstandard.ZstdCompressionParameters(...)
2661 >>> d.precompute_compress(compression_params=params)
2662
2663 .. note::
2664
2665 When a dictionary is precomputed, the compression parameters used to
2666 precompute the dictionary overwrite some of the compression parameters
2667 specified to ``ZstdCompressor``.
2668
2669 :param data:
2670 Dictionary data.
2671 :param dict_type:
2672 Type of dictionary. One of the ``DICT_TYPE_*`` constants.
2673 """
2674
2675 def __init__(self, data, dict_type=DICT_TYPE_AUTO, k=0, d=0):
2676 assert isinstance(data, bytes)
2677 self._data = data
2678 self.k = k
2679 self.d = d
2680
2681 if dict_type not in (
2682 DICT_TYPE_AUTO,
2683 DICT_TYPE_RAWCONTENT,
2684 DICT_TYPE_FULLDICT,
2685 ):
2686 raise ValueError(
2687 "invalid dictionary load mode: %d; must use "
2688 "DICT_TYPE_* constants"
2689 )
2690
2691 self._dict_type = dict_type
2692 self._cdict = None
2693
2694 def __len__(self):
2695 return len(self._data)
2696
2697 def dict_id(self):
2698 """Obtain the integer ID of the dictionary."""
2699 return int(lib.ZDICT_getDictID(self._data, len(self._data)))
2700
2701 def as_bytes(self):
2702 """Obtain the ``bytes`` representation of the dictionary."""
2703 return self._data
2704
2705 def precompute_compress(self, level=0, compression_params=None):
2706 """Precompute a dictionary os it can be used by multiple compressors.
2707
2708 Calling this method on an instance that will be used by multiple
2709 :py:class:`ZstdCompressor` instances will improve performance.
2710 """
2711 if level and compression_params:
2712 raise ValueError(
2713 "must only specify one of level or " "compression_params"
2714 )
2715
2716 if not level and not compression_params:
2717 raise ValueError("must specify one of level or compression_params")
2718
2719 if level:
2720 cparams = lib.ZSTD_getCParams(level, 0, len(self._data))
2721 else:
2722 cparams = ffi.new("ZSTD_compressionParameters")
2723 cparams.chainLog = compression_params.chain_log
2724 cparams.hashLog = compression_params.hash_log
2725 cparams.minMatch = compression_params.min_match
2726 cparams.searchLog = compression_params.search_log
2727 cparams.strategy = compression_params.strategy
2728 cparams.targetLength = compression_params.target_length
2729 cparams.windowLog = compression_params.window_log
2730
2731 cdict = lib.ZSTD_createCDict_advanced(
2732 self._data,
2733 len(self._data),
2734 lib.ZSTD_dlm_byRef,
2735 self._dict_type,
2736 cparams,
2737 lib.ZSTD_defaultCMem,
2738 )
2739 if cdict == ffi.NULL:
2740 raise ZstdError("unable to precompute dictionary")
2741
2742 self._cdict = ffi.gc(
2743 cdict, lib.ZSTD_freeCDict, size=lib.ZSTD_sizeof_CDict(cdict)
2744 )
2745
2746 @property
2747 def _ddict(self):
2748 ddict = lib.ZSTD_createDDict_advanced(
2749 self._data,
2750 len(self._data),
2751 lib.ZSTD_dlm_byRef,
2752 self._dict_type,
2753 lib.ZSTD_defaultCMem,
2754 )
2755
2756 if ddict == ffi.NULL:
2757 raise ZstdError("could not create decompression dict")
2758
2759 ddict = ffi.gc(
2760 ddict, lib.ZSTD_freeDDict, size=lib.ZSTD_sizeof_DDict(ddict)
2761 )
2762 self.__dict__["_ddict"] = ddict
2763
2764 return ddict
2765
2766
2767 def train_dictionary(
2768 dict_size,
2769 samples,
2770 k=0,
2771 d=0,
2772 f=0,
2773 split_point=0.0,
2774 accel=0,
2775 notifications=0,
2776 dict_id=0,
2777 level=0,
2778 steps=0,
2779 threads=0,
2780 ):
2781 """Train a dictionary from sample data using the COVER algorithm.
2782
2783 A compression dictionary of size ``dict_size`` will be created from the
2784 iterable of ``samples``. The raw dictionary bytes will be returned.
2785
2786 The dictionary training mechanism is known as *cover*. More details about it
2787 are available in the paper *Effective Construction of Relative Lempel-Ziv
2788 Dictionaries* (authors: Liao, Petri, Moffat, Wirth).
2789
2790 The cover algorithm takes parameters ``k`` and ``d``. These are the
2791 *segment size* and *dmer size*, respectively. The returned dictionary
2792 instance created by this function has ``k`` and ``d`` attributes
2793 containing the values for these parameters. If a ``ZstdCompressionDict``
2794 is constructed from raw bytes data (a content-only dictionary), the
2795 ``k`` and ``d`` attributes will be ``0``.
2796
2797 The segment and dmer size parameters to the cover algorithm can either be
2798 specified manually or ``train_dictionary()`` can try multiple values
2799 and pick the best one, where *best* means the smallest compressed data size.
2800 This later mode is called *optimization* mode.
2801
2802 Under the hood, this function always calls
2803 ``ZDICT_optimizeTrainFromBuffer_fastCover()``. See the corresponding C library
2804 documentation for more.
2805
2806 If neither ``steps`` nor ``threads`` is defined, defaults for ``d``, ``steps``,
2807 and ``level`` will be used that are equivalent with what
2808 ``ZDICT_trainFromBuffer()`` would use.
2809
2810
2811 :param dict_size:
2812 Target size in bytes of the dictionary to generate.
2813 :param samples:
2814 A list of bytes holding samples the dictionary will be trained from.
2815 :param k:
2816 Segment size : constraint: 0 < k : Reasonable range [16, 2048+]
2817 :param d:
2818 dmer size : constraint: 0 < d <= k : Reasonable range [6, 16]
2819 :param f:
2820 log of size of frequency array : constraint: 0 < f <= 31 : 1 means
2821 default(20)
2822 :param split_point:
2823 Percentage of samples used for training: Only used for optimization.
2824 The first # samples * ``split_point`` samples will be used to training.
2825 The last # samples * (1 - split_point) samples will be used for testing.
2826 0 means default (0.75), 1.0 when all samples are used for both training
2827 and testing.
2828 :param accel:
2829 Acceleration level: constraint: 0 < accel <= 10. Higher means faster
2830 and less accurate, 0 means default(1).
2831 :param dict_id:
2832 Integer dictionary ID for the produced dictionary. Default is 0, which uses
2833 a random value.
2834 :param steps:
2835 Number of steps through ``k`` values to perform when trying parameter
2836 variations.
2837 :param threads:
2838 Number of threads to use when trying parameter variations. Default is 0,
2839 which means to use a single thread. A negative value can be specified to
2840 use as many threads as there are detected logical CPUs.
2841 :param level:
2842 Integer target compression level when trying parameter variations.
2843 :param notifications:
2844 Controls writing of informational messages to ``stderr``. ``0`` (the
2845 default) means to write nothing. ``1`` writes errors. ``2`` writes
2846 progression info. ``3`` writes more details. And ``4`` writes all info.
2847 """
2848
2849 if not isinstance(samples, list):
2850 raise TypeError("samples must be a list")
2851
2852 if threads < 0:
2853 threads = _cpu_count()
2854
2855 if not steps and not threads:
2856 d = d or 8
2857 steps = steps or 4
2858 level = level or 3
2859
2860 total_size = sum(map(len, samples))
2861
2862 samples_buffer = new_nonzero("char[]", total_size)
2863 sample_sizes = new_nonzero("size_t[]", len(samples))
2864
2865 offset = 0
2866 for i, sample in enumerate(samples):
2867 if not isinstance(sample, bytes):
2868 raise ValueError("samples must be bytes")
2869
2870 l = len(sample)
2871 ffi.memmove(samples_buffer + offset, sample, l)
2872 offset += l
2873 sample_sizes[i] = l
2874
2875 dict_data = new_nonzero("char[]", dict_size)
2876
2877 dparams = ffi.new("ZDICT_fastCover_params_t *")[0]
2878 dparams.k = k
2879 dparams.d = d
2880 dparams.f = f
2881 dparams.steps = steps
2882 dparams.nbThreads = threads
2883 dparams.splitPoint = split_point
2884 dparams.accel = accel
2885 dparams.zParams.notificationLevel = notifications
2886 dparams.zParams.dictID = dict_id
2887 dparams.zParams.compressionLevel = level
2888
2889 zresult = lib.ZDICT_optimizeTrainFromBuffer_fastCover(
2890 ffi.addressof(dict_data),
2891 dict_size,
2892 ffi.addressof(samples_buffer),
2893 ffi.addressof(sample_sizes, 0),
2894 len(samples),
2895 ffi.addressof(dparams),
2896 )
2897
2898 if lib.ZDICT_isError(zresult):
2899 msg = ffi.string(lib.ZDICT_getErrorName(zresult)).decode("utf-8")
2900 raise ZstdError("cannot train dict: %s" % msg)
2901
2902 return ZstdCompressionDict(
2903 ffi.buffer(dict_data, zresult)[:],
2904 dict_type=DICT_TYPE_FULLDICT,
2905 k=dparams.k,
2906 d=dparams.d,
2907 )
2908
2909
2910 class ZstdDecompressionObj(object):
2911 """A standard library API compatible decompressor.
2912
2913 This type implements a compressor that conforms to the API by other
2914 decompressors in Python's standard library. e.g. ``zlib.decompressobj``
2915 or ``bz2.BZ2Decompressor``. This allows callers to use zstd compression
2916 while conforming to a similar API.
2917
2918 Compressed data chunks are fed into ``decompress(data)`` and
2919 uncompressed output (or an empty bytes) is returned. Output from
2920 subsequent calls needs to be concatenated to reassemble the full
2921 decompressed byte sequence.
2922
2923 If ``read_across_frames=False``, each instance is single use: once an
2924 input frame is decoded, ``decompress()`` will raise an exception. If
2925 ``read_across_frames=True``, instances can decode multiple frames.
2926
2927 >>> dctx = zstandard.ZstdDecompressor()
2928 >>> dobj = dctx.decompressobj()
2929 >>> data = dobj.decompress(compressed_chunk_0)
2930 >>> data = dobj.decompress(compressed_chunk_1)
2931
2932 By default, calls to ``decompress()`` write output data in chunks of size
2933 ``DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE``. These chunks are concatenated
2934 before being returned to the caller. It is possible to define the size of
2935 these temporary chunks by passing ``write_size`` to ``decompressobj()``:
2936
2937 >>> dctx = zstandard.ZstdDecompressor()
2938 >>> dobj = dctx.decompressobj(write_size=1048576)
2939
2940 .. note::
2941
2942 Because calls to ``decompress()`` may need to perform multiple
2943 memory (re)allocations, this streaming decompression API isn't as
2944 efficient as other APIs.
2945 """
2946
2947 def __init__(self, decompressor, write_size, read_across_frames):
2948 self._decompressor = decompressor
2949 self._write_size = write_size
2950 self._finished = False
2951 self._read_across_frames = read_across_frames
2952 self._unused_input = b""
2953
2954 def decompress(self, data):
2955 """Send compressed data to the decompressor and obtain decompressed data.
2956
2957 :param data:
2958 Data to feed into the decompressor.
2959 :return:
2960 Decompressed bytes.
2961 """
2962 if self._finished:
2963 raise ZstdError("cannot use a decompressobj multiple times")
2964
2965 in_buffer = ffi.new("ZSTD_inBuffer *")
2966 out_buffer = ffi.new("ZSTD_outBuffer *")
2967
2968 data_buffer = ffi.from_buffer(data)
2969
2970 if len(data_buffer) == 0:
2971 return b""
2972
2973 in_buffer.src = data_buffer
2974 in_buffer.size = len(data_buffer)
2975 in_buffer.pos = 0
2976
2977 dst_buffer = ffi.new("char[]", self._write_size)
2978 out_buffer.dst = dst_buffer
2979 out_buffer.size = len(dst_buffer)
2980 out_buffer.pos = 0
2981
2982 chunks = []
2983
2984 while True:
2985 zresult = lib.ZSTD_decompressStream(
2986 self._decompressor._dctx, out_buffer, in_buffer
2987 )
2988 if lib.ZSTD_isError(zresult):
2989 raise ZstdError(
2990 "zstd decompressor error: %s" % _zstd_error(zresult)
2991 )
2992
2993 # Always record any output from decompressor.
2994 if out_buffer.pos:
2995 chunks.append(ffi.buffer(out_buffer.dst, out_buffer.pos)[:])
2996
2997 # 0 is only seen when a frame is fully decoded *and* fully flushed.
2998 # Behavior depends on whether we're in single or multiple frame
2999 # mode.
3000 if zresult == 0 and not self._read_across_frames:
3001 # Mark the instance as done and make any unconsumed input available
3002 # for retrieval.
3003 self._finished = True
3004 self._decompressor = None
3005 self._unused_input = data[in_buffer.pos : in_buffer.size]
3006 break
3007 elif zresult == 0 and self._read_across_frames:
3008 # We're at the end of a fully flushed frame and we can read more.
3009 # Try to read more if there's any more input.
3010 if in_buffer.pos == in_buffer.size:
3011 break
3012 else:
3013 out_buffer.pos = 0
3014
3015 # We're not at the end of the frame *or* we're not fully flushed.
3016
3017 # The decompressor will write out all the bytes it can to the output
3018 # buffer. So if the output buffer is partially filled and the input
3019 # is exhausted, there's nothing more to write. So we've done all we
3020 # can.
3021 elif (
3022 in_buffer.pos == in_buffer.size
3023 and out_buffer.pos < out_buffer.size
3024 ):
3025 break
3026 else:
3027 out_buffer.pos = 0
3028
3029 return b"".join(chunks)
3030
3031 def flush(self, length=0):
3032 """Effectively a no-op.
3033
3034 Implemented for compatibility with the standard library APIs.
3035
3036 Safe to call at any time.
3037
3038 :return:
3039 Empty bytes.
3040 """
3041 return b""
3042
3043 @property
3044 def unused_data(self):
3045 """Bytes past the end of compressed data.
3046
3047 If ``decompress()`` is fed additional data beyond the end of a zstd
3048 frame, this value will be non-empty once ``decompress()`` fully decodes
3049 the input frame.
3050 """
3051 return self._unused_input
3052
3053 @property
3054 def unconsumed_tail(self):
3055 """Data that has not yet been fed into the decompressor."""
3056 return b""
3057
3058 @property
3059 def eof(self):
3060 """Whether the end of the compressed data stream has been reached."""
3061 return self._finished
3062
3063
3064 class ZstdDecompressionReader(object):
3065 """Read only decompressor that pull uncompressed data from another stream.
3066
3067 This type provides a read-only stream interface for performing transparent
3068 decompression from another stream or data source. It conforms to the
3069 ``io.RawIOBase`` interface. Only methods relevant to reading are
3070 implemented.
3071
3072 >>> with open(path, 'rb') as fh:
3073 >>> dctx = zstandard.ZstdDecompressor()
3074 >>> reader = dctx.stream_reader(fh)
3075 >>> while True:
3076 ... chunk = reader.read(16384)
3077 ... if not chunk:
3078 ... break
3079 ... # Do something with decompressed chunk.
3080
3081 The stream can also be used as a context manager:
3082
3083 >>> with open(path, 'rb') as fh:
3084 ... dctx = zstandard.ZstdDecompressor()
3085 ... with dctx.stream_reader(fh) as reader:
3086 ... ...
3087
3088 When used as a context manager, the stream is closed and the underlying
3089 resources are released when the context manager exits. Future operations
3090 against the stream will fail.
3091
3092 The ``source`` argument to ``stream_reader()`` can be any object with a
3093 ``read(size)`` method or any object implementing the *buffer protocol*.
3094
3095 If the ``source`` is a stream, you can specify how large ``read()`` requests
3096 to that stream should be via the ``read_size`` argument. It defaults to
3097 ``zstandard.DECOMPRESSION_RECOMMENDED_INPUT_SIZE``.:
3098
3099 >>> with open(path, 'rb') as fh:
3100 ... dctx = zstandard.ZstdDecompressor()
3101 ... # Will perform fh.read(8192) when obtaining data for the decompressor.
3102 ... with dctx.stream_reader(fh, read_size=8192) as reader:
3103 ... ...
3104
3105 Instances are *partially* seekable. Absolute and relative positions
3106 (``SEEK_SET`` and ``SEEK_CUR``) forward of the current position are
3107 allowed. Offsets behind the current read position and offsets relative
3108 to the end of stream are not allowed and will raise ``ValueError``
3109 if attempted.
3110
3111 ``tell()`` returns the number of decompressed bytes read so far.
3112
3113 Not all I/O methods are implemented. Notably missing is support for
3114 ``readline()``, ``readlines()``, and linewise iteration support. This is
3115 because streams operate on binary data - not text data. If you want to
3116 convert decompressed output to text, you can chain an ``io.TextIOWrapper``
3117 to the stream:
3118
3119 >>> with open(path, 'rb') as fh:
3120 ... dctx = zstandard.ZstdDecompressor()
3121 ... stream_reader = dctx.stream_reader(fh)
3122 ... text_stream = io.TextIOWrapper(stream_reader, encoding='utf-8')
3123 ... for line in text_stream:
3124 ... ...
3125 """
3126
3127 def __init__(
3128 self,
3129 decompressor,
3130 source,
3131 read_size,
3132 read_across_frames,
3133 closefd=True,
3134 ):
3135 self._decompressor = decompressor
3136 self._source = source
3137 self._read_size = read_size
3138 self._read_across_frames = bool(read_across_frames)
3139 self._closefd = bool(closefd)
3140 self._entered = False
3141 self._closed = False
3142 self._bytes_decompressed = 0
3143 self._finished_input = False
3144 self._finished_output = False
3145 self._in_buffer = ffi.new("ZSTD_inBuffer *")
3146 # Holds a ref to self._in_buffer.src.
3147 self._source_buffer = None
3148
3149 def __enter__(self):
3150 if self._entered:
3151 raise ValueError("cannot __enter__ multiple times")
3152
3153 if self._closed:
3154 raise ValueError("stream is closed")
3155
3156 self._entered = True
3157 return self
3158
3159 def __exit__(self, exc_type, exc_value, exc_tb):
3160 self._entered = False
3161 self._decompressor = None
3162 self.close()
3163 self._source = None
3164
3165 return False
3166
3167 def readable(self):
3168 return True
3169
3170 def writable(self):
3171 return False
3172
3173 def seekable(self):
3174 return False
3175
3176 def readline(self, size=-1):
3177 raise io.UnsupportedOperation()
3178
3179 def readlines(self, hint=-1):
3180 raise io.UnsupportedOperation()
3181
3182 def write(self, data):
3183 raise io.UnsupportedOperation()
3184
3185 def writelines(self, lines):
3186 raise io.UnsupportedOperation()
3187
3188 def isatty(self):
3189 return False
3190
3191 def flush(self):
3192 return None
3193
3194 def close(self):
3195 if self._closed:
3196 return None
3197
3198 self._closed = True
3199
3200 f = getattr(self._source, "close", None)
3201 if self._closefd and f:
3202 f()
3203
3204 @property
3205 def closed(self):
3206 return self._closed
3207
3208 def tell(self):
3209 return self._bytes_decompressed
3210
3211 def readall(self):
3212 chunks = []
3213
3214 while True:
3215 chunk = self.read(1048576)
3216 if not chunk:
3217 break
3218
3219 chunks.append(chunk)
3220
3221 return b"".join(chunks)
3222
3223 def __iter__(self):
3224 raise io.UnsupportedOperation()
3225
3226 def __next__(self):
3227 raise io.UnsupportedOperation()
3228
3229 next = __next__
3230
3231 def _read_input(self):
3232 # We have data left over in the input buffer. Use it.
3233 if self._in_buffer.pos < self._in_buffer.size:
3234 return
3235
3236 # All input data exhausted. Nothing to do.
3237 if self._finished_input:
3238 return
3239
3240 # Else populate the input buffer from our source.
3241 if hasattr(self._source, "read"):
3242 data = self._source.read(self._read_size)
3243
3244 if not data:
3245 self._finished_input = True
3246 return
3247
3248 self._source_buffer = ffi.from_buffer(data)
3249 self._in_buffer.src = self._source_buffer
3250 self._in_buffer.size = len(self._source_buffer)
3251 self._in_buffer.pos = 0
3252 else:
3253 self._source_buffer = ffi.from_buffer(self._source)
3254 self._in_buffer.src = self._source_buffer
3255 self._in_buffer.size = len(self._source_buffer)
3256 self._in_buffer.pos = 0
3257
3258 def _decompress_into_buffer(self, out_buffer):
3259 """Decompress available input into an output buffer.
3260
3261 Returns True if data in output buffer should be emitted.
3262 """
3263 zresult = lib.ZSTD_decompressStream(
3264 self._decompressor._dctx, out_buffer, self._in_buffer
3265 )
3266
3267 if self._in_buffer.pos == self._in_buffer.size:
3268 self._in_buffer.src = ffi.NULL
3269 self._in_buffer.pos = 0
3270 self._in_buffer.size = 0
3271 self._source_buffer = None
3272
3273 if not hasattr(self._source, "read"):
3274 self._finished_input = True
3275
3276 if lib.ZSTD_isError(zresult):
3277 raise ZstdError("zstd decompress error: %s" % _zstd_error(zresult))
3278
3279 # Emit data if there is data AND either:
3280 # a) output buffer is full (read amount is satisfied)
3281 # b) we're at end of a frame and not in frame spanning mode
3282 return out_buffer.pos and (
3283 out_buffer.pos == out_buffer.size
3284 or zresult == 0
3285 and not self._read_across_frames
3286 )
3287
3288 def read(self, size=-1):
3289 if self._closed:
3290 raise ValueError("stream is closed")
3291
3292 if size < -1:
3293 raise ValueError("cannot read negative amounts less than -1")
3294
3295 if size == -1:
3296 # This is recursive. But it gets the job done.
3297 return self.readall()
3298
3299 if self._finished_output or size == 0:
3300 return b""
3301
3302 # We /could/ call into readinto() here. But that introduces more
3303 # overhead.
3304 dst_buffer = ffi.new("char[]", size)
3305 out_buffer = ffi.new("ZSTD_outBuffer *")
3306 out_buffer.dst = dst_buffer
3307 out_buffer.size = size
3308 out_buffer.pos = 0
3309
3310 self._read_input()
3311 if self._decompress_into_buffer(out_buffer):
3312 self._bytes_decompressed += out_buffer.pos
3313 return ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
3314
3315 while not self._finished_input:
3316 self._read_input()
3317 if self._decompress_into_buffer(out_buffer):
3318 self._bytes_decompressed += out_buffer.pos
3319 return ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
3320
3321 self._bytes_decompressed += out_buffer.pos
3322 return ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
3323
3324 def readinto(self, b):
3325 if self._closed:
3326 raise ValueError("stream is closed")
3327
3328 if self._finished_output:
3329 return 0
3330
3331 # TODO use writable=True once we require CFFI >= 1.12.
3332 dest_buffer = ffi.from_buffer(b)
3333 ffi.memmove(b, b"", 0)
3334 out_buffer = ffi.new("ZSTD_outBuffer *")
3335 out_buffer.dst = dest_buffer
3336 out_buffer.size = len(dest_buffer)
3337 out_buffer.pos = 0
3338
3339 self._read_input()
3340 if self._decompress_into_buffer(out_buffer):
3341 self._bytes_decompressed += out_buffer.pos
3342 return out_buffer.pos
3343
3344 while not self._finished_input:
3345 self._read_input()
3346 if self._decompress_into_buffer(out_buffer):
3347 self._bytes_decompressed += out_buffer.pos
3348 return out_buffer.pos
3349
3350 self._bytes_decompressed += out_buffer.pos
3351 return out_buffer.pos
3352
3353 def read1(self, size=-1):
3354 if self._closed:
3355 raise ValueError("stream is closed")
3356
3357 if size < -1:
3358 raise ValueError("cannot read negative amounts less than -1")
3359
3360 if self._finished_output or size == 0:
3361 return b""
3362
3363 # -1 returns arbitrary number of bytes.
3364 if size == -1:
3365 size = DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE
3366
3367 dst_buffer = ffi.new("char[]", size)
3368 out_buffer = ffi.new("ZSTD_outBuffer *")
3369 out_buffer.dst = dst_buffer
3370 out_buffer.size = size
3371 out_buffer.pos = 0
3372
3373 # read1() dictates that we can perform at most 1 call to underlying
3374 # stream to get input. However, we can't satisfy this restriction with
3375 # decompression because not all input generates output. So we allow
3376 # multiple read(). But unlike read(), we stop once we have any output.
3377 while not self._finished_input:
3378 self._read_input()
3379 self._decompress_into_buffer(out_buffer)
3380
3381 if out_buffer.pos:
3382 break
3383
3384 self._bytes_decompressed += out_buffer.pos
3385 return ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
3386
3387 def readinto1(self, b):
3388 if self._closed:
3389 raise ValueError("stream is closed")
3390
3391 if self._finished_output:
3392 return 0
3393
3394 # TODO use writable=True once we require CFFI >= 1.12.
3395 dest_buffer = ffi.from_buffer(b)
3396 ffi.memmove(b, b"", 0)
3397
3398 out_buffer = ffi.new("ZSTD_outBuffer *")
3399 out_buffer.dst = dest_buffer
3400 out_buffer.size = len(dest_buffer)
3401 out_buffer.pos = 0
3402
3403 while not self._finished_input and not self._finished_output:
3404 self._read_input()
3405 self._decompress_into_buffer(out_buffer)
3406
3407 if out_buffer.pos:
3408 break
3409
3410 self._bytes_decompressed += out_buffer.pos
3411 return out_buffer.pos
3412
3413 def seek(self, pos, whence=os.SEEK_SET):
3414 if self._closed:
3415 raise ValueError("stream is closed")
3416
3417 read_amount = 0
3418
3419 if whence == os.SEEK_SET:
3420 if pos < 0:
3421 raise OSError("cannot seek to negative position with SEEK_SET")
3422
3423 if pos < self._bytes_decompressed:
3424 raise OSError(
3425 "cannot seek zstd decompression stream " "backwards"
3426 )
3427
3428 read_amount = pos - self._bytes_decompressed
3429
3430 elif whence == os.SEEK_CUR:
3431 if pos < 0:
3432 raise OSError(
3433 "cannot seek zstd decompression stream " "backwards"
3434 )
3435
3436 read_amount = pos
3437 elif whence == os.SEEK_END:
3438 raise OSError(
3439 "zstd decompression streams cannot be seeked " "with SEEK_END"
3440 )
3441
3442 while read_amount:
3443 result = self.read(
3444 min(read_amount, DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE)
3445 )
3446
3447 if not result:
3448 break
3449
3450 read_amount -= len(result)
3451
3452 return self._bytes_decompressed
3453
3454
3455 class ZstdDecompressionWriter(object):
3456 """
3457 Write-only stream wrapper that performs decompression.
3458
3459 This type provides a writable stream that performs decompression and writes
3460 decompressed data to another stream.
3461
3462 This type implements the ``io.RawIOBase`` interface. Only methods that
3463 involve writing will do useful things.
3464
3465 Behavior is similar to :py:meth:`ZstdCompressor.stream_writer`: compressed
3466 data is sent to the decompressor by calling ``write(data)`` and decompressed
3467 output is written to the inner stream by calling its ``write(data)``
3468 method:
3469
3470 >>> dctx = zstandard.ZstdDecompressor()
3471 >>> decompressor = dctx.stream_writer(fh)
3472 >>> # Will call fh.write() with uncompressed data.
3473 >>> decompressor.write(compressed_data)
3474
3475 Instances can be used as context managers. However, context managers add no
3476 extra special behavior other than automatically calling ``close()`` when
3477 they exit.
3478
3479 Calling ``close()`` will mark the stream as closed and subsequent I/O
3480 operations will raise ``ValueError`` (per the documented behavior of
3481 ``io.RawIOBase``). ``close()`` will also call ``close()`` on the
3482 underlying stream if such a method exists and the instance was created with
3483 ``closefd=True``.
3484
3485 The size of chunks to ``write()`` to the destination can be specified:
3486
3487 >>> dctx = zstandard.ZstdDecompressor()
3488 >>> with dctx.stream_writer(fh, write_size=16384) as decompressor:
3489 >>> pass
3490
3491 You can see how much memory is being used by the decompressor:
3492
3493 >>> dctx = zstandard.ZstdDecompressor()
3494 >>> with dctx.stream_writer(fh) as decompressor:
3495 >>> byte_size = decompressor.memory_size()
3496
3497 ``stream_writer()`` accepts a ``write_return_read`` boolean argument to control
3498 the return value of ``write()``. When ``True`` (the default)``, ``write()``
3499 returns the number of bytes that were read from the input. When ``False``,
3500 ``write()`` returns the number of bytes that were ``write()`` to the inner
3501 stream.
3502 """
3503
3504 def __init__(
3505 self,
3506 decompressor,
3507 writer,
3508 write_size,
3509 write_return_read,
3510 closefd=True,
3511 ):
3512 decompressor._ensure_dctx()
3513
3514 self._decompressor = decompressor
3515 self._writer = writer
3516 self._write_size = write_size
3517 self._write_return_read = bool(write_return_read)
3518 self._closefd = bool(closefd)
3519 self._entered = False
3520 self._closing = False
3521 self._closed = False
3522
3523 def __enter__(self):
3524 if self._closed:
3525 raise ValueError("stream is closed")
3526
3527 if self._entered:
3528 raise ZstdError("cannot __enter__ multiple times")
3529
3530 self._entered = True
3531
3532 return self
3533
3534 def __exit__(self, exc_type, exc_value, exc_tb):
3535 self._entered = False
3536 self.close()
3537
3538 return False
3539
3540 def __iter__(self):
3541 raise io.UnsupportedOperation()
3542
3543 def __next__(self):
3544 raise io.UnsupportedOperation()
3545
3546 def memory_size(self):
3547 return lib.ZSTD_sizeof_DCtx(self._decompressor._dctx)
3548
3549 def close(self):
3550 if self._closed:
3551 return
3552
3553 try:
3554 self._closing = True
3555 self.flush()
3556 finally:
3557 self._closing = False
3558 self._closed = True
3559
3560 f = getattr(self._writer, "close", None)
3561 if self._closefd and f:
3562 f()
3563
3564 @property
3565 def closed(self):
3566 return self._closed
3567
3568 def fileno(self):
3569 f = getattr(self._writer, "fileno", None)
3570 if f:
3571 return f()
3572 else:
3573 raise OSError("fileno not available on underlying writer")
3574
3575 def flush(self):
3576 if self._closed:
3577 raise ValueError("stream is closed")
3578
3579 f = getattr(self._writer, "flush", None)
3580 if f and not self._closing:
3581 return f()
3582
3583 def isatty(self):
3584 return False
3585
3586 def readable(self):
3587 return False
3588
3589 def readline(self, size=-1):
3590 raise io.UnsupportedOperation()
3591
3592 def readlines(self, hint=-1):
3593 raise io.UnsupportedOperation()
3594
3595 def seek(self, offset, whence=None):
3596 raise io.UnsupportedOperation()
3597
3598 def seekable(self):
3599 return False
3600
3601 def tell(self):
3602 raise io.UnsupportedOperation()
3603
3604 def truncate(self, size=None):
3605 raise io.UnsupportedOperation()
3606
3607 def writable(self):
3608 return True
3609
3610 def writelines(self, lines):
3611 raise io.UnsupportedOperation()
3612
3613 def read(self, size=-1):
3614 raise io.UnsupportedOperation()
3615
3616 def readall(self):
3617 raise io.UnsupportedOperation()
3618
3619 def readinto(self, b):
3620 raise io.UnsupportedOperation()
3621
3622 def write(self, data):
3623 if self._closed:
3624 raise ValueError("stream is closed")
3625
3626 total_write = 0
3627
3628 in_buffer = ffi.new("ZSTD_inBuffer *")
3629 out_buffer = ffi.new("ZSTD_outBuffer *")
3630
3631 data_buffer = ffi.from_buffer(data)
3632 in_buffer.src = data_buffer
3633 in_buffer.size = len(data_buffer)
3634 in_buffer.pos = 0
3635
3636 dst_buffer = ffi.new("char[]", self._write_size)
3637 out_buffer.dst = dst_buffer
3638 out_buffer.size = len(dst_buffer)
3639 out_buffer.pos = 0
3640
3641 dctx = self._decompressor._dctx
3642
3643 while in_buffer.pos < in_buffer.size:
3644 zresult = lib.ZSTD_decompressStream(dctx, out_buffer, in_buffer)
3645 if lib.ZSTD_isError(zresult):
3646 raise ZstdError(
3647 "zstd decompress error: %s" % _zstd_error(zresult)
3648 )
3649
3650 if out_buffer.pos:
3651 self._writer.write(
3652 ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
3653 )
3654 total_write += out_buffer.pos
3655 out_buffer.pos = 0
3656
3657 if self._write_return_read:
3658 return in_buffer.pos
3659 else:
3660 return total_write
3661
3662
3663 class ZstdDecompressor(object):
3664 """
3665 Context for performing zstandard decompression.
3666
3667 Each instance is essentially a wrapper around a ``ZSTD_DCtx`` from zstd's
3668 C API.
3669
3670 An instance can compress data various ways. Instances can be used multiple
3671 times.
3672
3673 The interface of this class is very similar to
3674 :py:class:`zstandard.ZstdCompressor` (by design).
3675
3676 Assume that each ``ZstdDecompressor`` instance can only handle a single
3677 logical compression operation at the same time. i.e. if you call a method
3678 like ``decompressobj()`` to obtain multiple objects derived from the same
3679 ``ZstdDecompressor`` instance and attempt to use them simultaneously, errors
3680 will likely occur.
3681
3682 If you need to perform multiple logical decompression operations and you
3683 can't guarantee those operations are temporally non-overlapping, you need
3684 to obtain multiple ``ZstdDecompressor`` instances.
3685
3686 Unless specified otherwise, assume that no two methods of
3687 ``ZstdDecompressor`` instances can be called from multiple Python
3688 threads simultaneously. In other words, assume instances are not thread safe
3689 unless stated otherwise.
3690
3691 :param dict_data:
3692 Compression dictionary to use.
3693 :param max_window_size:
3694 Sets an upper limit on the window size for decompression operations in
3695 kibibytes. This setting can be used to prevent large memory allocations
3696 for inputs using large compression windows.
3697 :param format:
3698 Set the format of data for the decoder.
3699
3700 By default this is ``zstandard.FORMAT_ZSTD1``. It can be set to
3701 ``zstandard.FORMAT_ZSTD1_MAGICLESS`` to allow decoding frames without
3702 the 4 byte magic header. Not all decompression APIs support this mode.
3703 """
3704
3705 def __init__(self, dict_data=None, max_window_size=0, format=FORMAT_ZSTD1):
3706 self._dict_data = dict_data
3707 self._max_window_size = max_window_size
3708 self._format = format
3709
3710 dctx = lib.ZSTD_createDCtx()
3711 if dctx == ffi.NULL:
3712 raise MemoryError()
3713
3714 self._dctx = dctx
3715
3716 # Defer setting up garbage collection until full state is loaded so
3717 # the memory size is more accurate.
3718 try:
3719 self._ensure_dctx()
3720 finally:
3721 self._dctx = ffi.gc(
3722 dctx, lib.ZSTD_freeDCtx, size=lib.ZSTD_sizeof_DCtx(dctx)
3723 )
3724
3725 def memory_size(self):
3726 """Size of decompression context, in bytes.
3727
3728 >>> dctx = zstandard.ZstdDecompressor()
3729 >>> size = dctx.memory_size()
3730 """
3731 return lib.ZSTD_sizeof_DCtx(self._dctx)
3732
3733 def decompress(
3734 self,
3735 data,
3736 max_output_size=0,
3737 read_across_frames=False,
3738 allow_extra_data=True,
3739 ):
3740 """
3741 Decompress data in a single operation.
3742
3743 This method will decompress the input data in a single operation and
3744 return the decompressed data.
3745
3746 The input bytes are expected to contain at least 1 full Zstandard frame
3747 (something compressed with :py:meth:`ZstdCompressor.compress` or
3748 similar). If the input does not contain a full frame, an exception will
3749 be raised.
3750
3751 ``read_across_frames`` controls whether to read multiple zstandard
3752 frames in the input. When False, decompression stops after reading the
3753 first frame. This feature is not yet implemented but the argument is
3754 provided for forward API compatibility when the default is changed to
3755 True in a future release. For now, if you need to decompress multiple
3756 frames, use an API like :py:meth:`ZstdCompressor.stream_reader` with
3757 ``read_across_frames=True``.
3758
3759 ``allow_extra_data`` controls how to handle extra input data after a
3760 fully decoded frame. If False, any extra data (which could be a valid
3761 zstd frame) will result in ``ZstdError`` being raised. If True, extra
3762 data is silently ignored. The default will likely change to False in a
3763 future release when ``read_across_frames`` defaults to True.
3764
3765 If the input contains extra data after a full frame, that extra input
3766 data is silently ignored. This behavior is undesirable in many scenarios
3767 and will likely be changed or controllable in a future release (see
3768 #181).
3769
3770 If the frame header of the compressed data does not contain the content
3771 size, ``max_output_size`` must be specified or ``ZstdError`` will be
3772 raised. An allocation of size ``max_output_size`` will be performed and an
3773 attempt will be made to perform decompression into that buffer. If the
3774 buffer is too small or cannot be allocated, ``ZstdError`` will be
3775 raised. The buffer will be resized if it is too large.
3776
3777 Uncompressed data could be much larger than compressed data. As a result,
3778 calling this function could result in a very large memory allocation
3779 being performed to hold the uncompressed data. This could potentially
3780 result in ``MemoryError`` or system memory swapping. If you don't need
3781 the full output data in a single contiguous array in memory, consider
3782 using streaming decompression for more resilient memory behavior.
3783
3784 Usage:
3785
3786 >>> dctx = zstandard.ZstdDecompressor()
3787 >>> decompressed = dctx.decompress(data)
3788
3789 If the compressed data doesn't have its content size embedded within it,
3790 decompression can be attempted by specifying the ``max_output_size``
3791 argument:
3792
3793 >>> dctx = zstandard.ZstdDecompressor()
3794 >>> uncompressed = dctx.decompress(data, max_output_size=1048576)
3795
3796 Ideally, ``max_output_size`` will be identical to the decompressed
3797 output size.
3798
3799 .. important::
3800
3801 If the exact size of decompressed data is unknown (not passed in
3802 explicitly and not stored in the zstd frame), for performance
3803 reasons it is encouraged to use a streaming API.
3804
3805 :param data:
3806 Compressed data to decompress.
3807 :param max_output_size:
3808 Integer max size of response.
3809
3810 If ``0``, there is no limit and we can attempt to allocate an output
3811 buffer of infinite size.
3812 :return:
3813 ``bytes`` representing decompressed output.
3814 """
3815
3816 if read_across_frames:
3817 raise ZstdError(
3818 "ZstdDecompressor.read_across_frames=True is not yet implemented"
3819 )
3820
3821 self._ensure_dctx()
3822
3823 data_buffer = ffi.from_buffer(data)
3824
3825 output_size = lib.ZSTD_getFrameContentSize(
3826 data_buffer, len(data_buffer)
3827 )
3828
3829 if output_size == lib.ZSTD_CONTENTSIZE_ERROR:
3830 raise ZstdError("error determining content size from frame header")
3831 elif output_size == 0:
3832 return b""
3833 elif output_size == lib.ZSTD_CONTENTSIZE_UNKNOWN:
3834 if not max_output_size:
3835 raise ZstdError(
3836 "could not determine content size in frame header"
3837 )
3838
3839 result_buffer = ffi.new("char[]", max_output_size)
3840 result_size = max_output_size
3841 output_size = 0
3842 else:
3843 result_buffer = ffi.new("char[]", output_size)
3844 result_size = output_size
3845
3846 out_buffer = ffi.new("ZSTD_outBuffer *")
3847 out_buffer.dst = result_buffer
3848 out_buffer.size = result_size
3849 out_buffer.pos = 0
3850
3851 in_buffer = ffi.new("ZSTD_inBuffer *")
3852 in_buffer.src = data_buffer
3853 in_buffer.size = len(data_buffer)
3854 in_buffer.pos = 0
3855
3856 zresult = lib.ZSTD_decompressStream(self._dctx, out_buffer, in_buffer)
3857 if lib.ZSTD_isError(zresult):
3858 raise ZstdError("decompression error: %s" % _zstd_error(zresult))
3859 elif zresult:
3860 raise ZstdError(
3861 "decompression error: did not decompress full frame"
3862 )
3863 elif output_size and out_buffer.pos != output_size:
3864 raise ZstdError(
3865 "decompression error: decompressed %d bytes; expected %d"
3866 % (zresult, output_size)
3867 )
3868 elif not allow_extra_data and in_buffer.pos < in_buffer.size:
3869 count = in_buffer.size - in_buffer.pos
3870
3871 raise ZstdError(
3872 "compressed input contains %d bytes of unused data, which is disallowed"
3873 % count
3874 )
3875
3876 return ffi.buffer(result_buffer, out_buffer.pos)[:]
3877
3878 def stream_reader(
3879 self,
3880 source,
3881 read_size=DECOMPRESSION_RECOMMENDED_INPUT_SIZE,
3882 read_across_frames=False,
3883 closefd=True,
3884 ):
3885 """
3886 Read-only stream wrapper that performs decompression.
3887
3888 This method obtains an object that conforms to the ``io.RawIOBase``
3889 interface and performs transparent decompression via ``read()``
3890 operations. Source data is obtained by calling ``read()`` on a
3891 source stream or object implementing the buffer protocol.
3892
3893 See :py:class:`zstandard.ZstdDecompressionReader` for more documentation
3894 and usage examples.
3895
3896 :param source:
3897 Source of compressed data to decompress. Can be any object
3898 with a ``read(size)`` method or that conforms to the buffer protocol.
3899 :param read_size:
3900 Integer number of bytes to read from the source and feed into the
3901 compressor at a time.
3902 :param read_across_frames:
3903 Whether to read data across multiple zstd frames. If False,
3904 decompression is stopped at frame boundaries.
3905 :param closefd:
3906 Whether to close the source stream when this instance is closed.
3907 :return:
3908 :py:class:`zstandard.ZstdDecompressionReader`.
3909 """
3910 self._ensure_dctx()
3911 return ZstdDecompressionReader(
3912 self, source, read_size, read_across_frames, closefd=closefd
3913 )
3914
3915 def decompressobj(
3916 self,
3917 write_size=DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE,
3918 read_across_frames=False,
3919 ):
3920 """Obtain a standard library compatible incremental decompressor.
3921
3922 See :py:class:`ZstdDecompressionObj` for more documentation
3923 and usage examples.
3924
3925 :param write_size: size of internal output buffer to collect decompressed
3926 chunks in.
3927 :param read_across_frames: whether to read across multiple zstd frames.
3928 If False, reading stops after 1 frame and subsequent decompress
3929 attempts will raise an exception.
3930 :return:
3931 :py:class:`zstandard.ZstdDecompressionObj`
3932 """
3933 if write_size < 1:
3934 raise ValueError("write_size must be positive")
3935
3936 self._ensure_dctx()
3937 return ZstdDecompressionObj(
3938 self, write_size=write_size, read_across_frames=read_across_frames
3939 )
3940
3941 def read_to_iter(
3942 self,
3943 reader,
3944 read_size=DECOMPRESSION_RECOMMENDED_INPUT_SIZE,
3945 write_size=DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE,
3946 skip_bytes=0,
3947 ):
3948 """Read compressed data to an iterator of uncompressed chunks.
3949
3950 This method will read data from ``reader``, feed it to a decompressor,
3951 and emit ``bytes`` chunks representing the decompressed result.
3952
3953 >>> dctx = zstandard.ZstdDecompressor()
3954 >>> for chunk in dctx.read_to_iter(fh):
3955 ... # Do something with original data.
3956
3957 ``read_to_iter()`` accepts an object with a ``read(size)`` method that
3958 will return compressed bytes or an object conforming to the buffer
3959 protocol.
3960
3961 ``read_to_iter()`` returns an iterator whose elements are chunks of the
3962 decompressed data.
3963
3964 The size of requested ``read()`` from the source can be specified:
3965
3966 >>> dctx = zstandard.ZstdDecompressor()
3967 >>> for chunk in dctx.read_to_iter(fh, read_size=16384):
3968 ... pass
3969
3970 It is also possible to skip leading bytes in the input data:
3971
3972 >>> dctx = zstandard.ZstdDecompressor()
3973 >>> for chunk in dctx.read_to_iter(fh, skip_bytes=1):
3974 ... pass
3975
3976 .. tip::
3977
3978 Skipping leading bytes is useful if the source data contains extra
3979 *header* data. Traditionally, you would need to create a slice or
3980 ``memoryview`` of the data you want to decompress. This would create
3981 overhead. It is more efficient to pass the offset into this API.
3982
3983 Similarly to :py:meth:`ZstdCompressor.read_to_iter`, the consumer of the
3984 iterator controls when data is decompressed. If the iterator isn't consumed,
3985 decompression is put on hold.
3986
3987 When ``read_to_iter()`` is passed an object conforming to the buffer protocol,
3988 the behavior may seem similar to what occurs when the simple decompression
3989 API is used. However, this API works when the decompressed size is unknown.
3990 Furthermore, if feeding large inputs, the decompressor will work in chunks
3991 instead of performing a single operation.
3992
3993 :param reader:
3994 Source of compressed data. Can be any object with a
3995 ``read(size)`` method or any object conforming to the buffer
3996 protocol.
3997 :param read_size:
3998 Integer size of data chunks to read from ``reader`` and feed into
3999 the decompressor.
4000 :param write_size:
4001 Integer size of data chunks to emit from iterator.
4002 :param skip_bytes:
4003 Integer number of bytes to skip over before sending data into
4004 the decompressor.
4005 :return:
4006 Iterator of ``bytes`` representing uncompressed data.
4007 """
4008
4009 if skip_bytes >= read_size:
4010 raise ValueError("skip_bytes must be smaller than read_size")
4011
4012 if hasattr(reader, "read"):
4013 have_read = True
4014 elif hasattr(reader, "__getitem__"):
4015 have_read = False
4016 buffer_offset = 0
4017 size = len(reader)
4018 else:
4019 raise ValueError(
4020 "must pass an object with a read() method or "
4021 "conforms to buffer protocol"
4022 )
4023
4024 if skip_bytes:
4025 if have_read:
4026 reader.read(skip_bytes)
4027 else:
4028 if skip_bytes > size:
4029 raise ValueError("skip_bytes larger than first input chunk")
4030
4031 buffer_offset = skip_bytes
4032
4033 self._ensure_dctx()
4034
4035 in_buffer = ffi.new("ZSTD_inBuffer *")
4036 out_buffer = ffi.new("ZSTD_outBuffer *")
4037
4038 dst_buffer = ffi.new("char[]", write_size)
4039 out_buffer.dst = dst_buffer
4040 out_buffer.size = len(dst_buffer)
4041 out_buffer.pos = 0
4042
4043 while True:
4044 assert out_buffer.pos == 0
4045
4046 if have_read:
4047 read_result = reader.read(read_size)
4048 else:
4049 remaining = size - buffer_offset
4050 slice_size = min(remaining, read_size)
4051 read_result = reader[buffer_offset : buffer_offset + slice_size]
4052 buffer_offset += slice_size
4053
4054 # No new input. Break out of read loop.
4055 if not read_result:
4056 break
4057
4058 # Feed all read data into decompressor and emit output until
4059 # exhausted.
4060 read_buffer = ffi.from_buffer(read_result)
4061 in_buffer.src = read_buffer
4062 in_buffer.size = len(read_buffer)
4063 in_buffer.pos = 0
4064
4065 while in_buffer.pos < in_buffer.size:
4066 assert out_buffer.pos == 0
4067
4068 zresult = lib.ZSTD_decompressStream(
4069 self._dctx, out_buffer, in_buffer
4070 )
4071 if lib.ZSTD_isError(zresult):
4072 raise ZstdError(
4073 "zstd decompress error: %s" % _zstd_error(zresult)
4074 )
4075
4076 if out_buffer.pos:
4077 data = ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
4078 out_buffer.pos = 0
4079 yield data
4080
4081 if zresult == 0:
4082 return
4083
4084 # Repeat loop to collect more input data.
4085 continue
4086
4087 # If we get here, input is exhausted.
4088
4089 def stream_writer(
4090 self,
4091 writer,
4092 write_size=DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE,
4093 write_return_read=True,
4094 closefd=True,
4095 ):
4096 """
4097 Push-based stream wrapper that performs decompression.
4098
4099 This method constructs a stream wrapper that conforms to the
4100 ``io.RawIOBase`` interface and performs transparent decompression
4101 when writing to a wrapper stream.
4102
4103 See :py:class:`zstandard.ZstdDecompressionWriter` for more documentation
4104 and usage examples.
4105
4106 :param writer:
4107 Destination for decompressed output. Can be any object with a
4108 ``write(data)``.
4109 :param write_size:
4110 Integer size of chunks to ``write()`` to ``writer``.
4111 :param write_return_read:
4112 Whether ``write()`` should return the number of bytes of input
4113 consumed. If False, ``write()`` returns the number of bytes sent
4114 to the inner stream.
4115 :param closefd:
4116 Whether to ``close()`` the inner stream when this stream is closed.
4117 :return:
4118 :py:class:`zstandard.ZstdDecompressionWriter`
4119 """
4120 if not hasattr(writer, "write"):
4121 raise ValueError("must pass an object with a write() method")
4122
4123 return ZstdDecompressionWriter(
4124 self,
4125 writer,
4126 write_size,
4127 write_return_read,
4128 closefd=closefd,
4129 )
4130
4131 def copy_stream(
4132 self,
4133 ifh,
4134 ofh,
4135 read_size=DECOMPRESSION_RECOMMENDED_INPUT_SIZE,
4136 write_size=DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE,
4137 ):
4138 """
4139 Copy data between streams, decompressing in the process.
4140
4141 Compressed data will be read from ``ifh``, decompressed, and written
4142 to ``ofh``.
4143
4144 >>> dctx = zstandard.ZstdDecompressor()
4145 >>> dctx.copy_stream(ifh, ofh)
4146
4147 e.g. to decompress a file to another file:
4148
4149 >>> dctx = zstandard.ZstdDecompressor()
4150 >>> with open(input_path, 'rb') as ifh, open(output_path, 'wb') as ofh:
4151 ... dctx.copy_stream(ifh, ofh)
4152
4153 The size of chunks being ``read()`` and ``write()`` from and to the
4154 streams can be specified:
4155
4156 >>> dctx = zstandard.ZstdDecompressor()
4157 >>> dctx.copy_stream(ifh, ofh, read_size=8192, write_size=16384)
4158
4159 :param ifh:
4160 Source stream to read compressed data from.
4161
4162 Must have a ``read()`` method.
4163 :param ofh:
4164 Destination stream to write uncompressed data to.
4165
4166 Must have a ``write()`` method.
4167 :param read_size:
4168 The number of bytes to ``read()`` from the source in a single
4169 operation.
4170 :param write_size:
4171 The number of bytes to ``write()`` to the destination in a single
4172 operation.
4173 :return:
4174 2-tuple of integers representing the number of bytes read and
4175 written, respectively.
4176 """
4177
4178 if not hasattr(ifh, "read"):
4179 raise ValueError("first argument must have a read() method")
4180 if not hasattr(ofh, "write"):
4181 raise ValueError("second argument must have a write() method")
4182
4183 self._ensure_dctx()
4184
4185 in_buffer = ffi.new("ZSTD_inBuffer *")
4186 out_buffer = ffi.new("ZSTD_outBuffer *")
4187
4188 dst_buffer = ffi.new("char[]", write_size)
4189 out_buffer.dst = dst_buffer
4190 out_buffer.size = write_size
4191 out_buffer.pos = 0
4192
4193 total_read, total_write = 0, 0
4194
4195 # Read all available input.
4196 while True:
4197 data = ifh.read(read_size)
4198 if not data:
4199 break
4200
4201 data_buffer = ffi.from_buffer(data)
4202 total_read += len(data_buffer)
4203 in_buffer.src = data_buffer
4204 in_buffer.size = len(data_buffer)
4205 in_buffer.pos = 0
4206
4207 # Flush all read data to output.
4208 while in_buffer.pos < in_buffer.size:
4209 zresult = lib.ZSTD_decompressStream(
4210 self._dctx, out_buffer, in_buffer
4211 )
4212 if lib.ZSTD_isError(zresult):
4213 raise ZstdError(
4214 "zstd decompressor error: %s" % _zstd_error(zresult)
4215 )
4216
4217 if out_buffer.pos:
4218 ofh.write(ffi.buffer(out_buffer.dst, out_buffer.pos))
4219 total_write += out_buffer.pos
4220 out_buffer.pos = 0
4221
4222 # Continue loop to keep reading.
4223
4224 return total_read, total_write
4225
4226 def decompress_content_dict_chain(self, frames):
4227 """
4228 Decompress a series of frames using the content dictionary chaining technique.
4229
4230 Such a list of frames is produced by compressing discrete inputs where
4231 each non-initial input is compressed with a *prefix* dictionary consisting
4232 of the content of the previous input.
4233
4234 For example, say you have the following inputs:
4235
4236 >>> inputs = [b"input 1", b"input 2", b"input 3"]
4237
4238 The zstd frame chain consists of:
4239
4240 1. ``b"input 1"`` compressed in standalone/discrete mode
4241 2. ``b"input 2"`` compressed using ``b"input 1"`` as a *prefix* dictionary
4242 3. ``b"input 3"`` compressed using ``b"input 2"`` as a *prefix* dictionary
4243
4244 Each zstd frame **must** have the content size written.
4245
4246 The following Python code can be used to produce a *prefix dictionary chain*:
4247
4248 >>> def make_chain(inputs):
4249 ... frames = []
4250 ...
4251 ... # First frame is compressed in standalone/discrete mode.
4252 ... zctx = zstandard.ZstdCompressor()
4253 ... frames.append(zctx.compress(inputs[0]))
4254 ...
4255 ... # Subsequent frames use the previous fulltext as a prefix dictionary
4256 ... for i, raw in enumerate(inputs[1:]):
4257 ... dict_data = zstandard.ZstdCompressionDict(
4258 ... inputs[i], dict_type=zstandard.DICT_TYPE_RAWCONTENT)
4259 ... zctx = zstandard.ZstdCompressor(dict_data=dict_data)
4260 ... frames.append(zctx.compress(raw))
4261 ...
4262 ... return frames
4263
4264 ``decompress_content_dict_chain()`` returns the uncompressed data of the last
4265 element in the input chain.
4266
4267 .. note::
4268
4269 It is possible to implement *prefix dictionary chain* decompression
4270 on top of other APIs. However, this function will likely be faster -
4271 especially for long input chains - as it avoids the overhead of
4272 instantiating and passing around intermediate objects between
4273 multiple functions.
4274
4275 :param frames:
4276 List of ``bytes`` holding compressed zstd frames.
4277 :return:
4278 """
4279 if not isinstance(frames, list):
4280 raise TypeError("argument must be a list")
4281
4282 if not frames:
4283 raise ValueError("empty input chain")
4284
4285 # First chunk should not be using a dictionary. We handle it specially.
4286 chunk = frames[0]
4287 if not isinstance(chunk, bytes):
4288 raise ValueError("chunk 0 must be bytes")
4289
4290 # All chunks should be zstd frames and should have content size set.
4291 chunk_buffer = ffi.from_buffer(chunk)
4292 params = ffi.new("ZSTD_frameHeader *")
4293 zresult = lib.ZSTD_getFrameHeader(
4294 params, chunk_buffer, len(chunk_buffer)
4295 )
4296 if lib.ZSTD_isError(zresult):
4297 raise ValueError("chunk 0 is not a valid zstd frame")
4298 elif zresult:
4299 raise ValueError("chunk 0 is too small to contain a zstd frame")
4300
4301 if params.frameContentSize == lib.ZSTD_CONTENTSIZE_UNKNOWN:
4302 raise ValueError("chunk 0 missing content size in frame")
4303
4304 self._ensure_dctx(load_dict=False)
4305
4306 last_buffer = ffi.new("char[]", params.frameContentSize)
4307
4308 out_buffer = ffi.new("ZSTD_outBuffer *")
4309 out_buffer.dst = last_buffer
4310 out_buffer.size = len(last_buffer)
4311 out_buffer.pos = 0
4312
4313 in_buffer = ffi.new("ZSTD_inBuffer *")
4314 in_buffer.src = chunk_buffer
4315 in_buffer.size = len(chunk_buffer)
4316 in_buffer.pos = 0
4317
4318 zresult = lib.ZSTD_decompressStream(self._dctx, out_buffer, in_buffer)
4319 if lib.ZSTD_isError(zresult):
4320 raise ZstdError(
4321 "could not decompress chunk 0: %s" % _zstd_error(zresult)
4322 )
4323 elif zresult:
4324 raise ZstdError("chunk 0 did not decompress full frame")
4325
4326 # Special case of chain length of 1
4327 if len(frames) == 1:
4328 return ffi.buffer(last_buffer, len(last_buffer))[:]
4329
4330 i = 1
4331 while i < len(frames):
4332 chunk = frames[i]
4333 if not isinstance(chunk, bytes):
4334 raise ValueError("chunk %d must be bytes" % i)
4335
4336 chunk_buffer = ffi.from_buffer(chunk)
4337 zresult = lib.ZSTD_getFrameHeader(
4338 params, chunk_buffer, len(chunk_buffer)
4339 )
4340 if lib.ZSTD_isError(zresult):
4341 raise ValueError("chunk %d is not a valid zstd frame" % i)
4342 elif zresult:
4343 raise ValueError(
4344 "chunk %d is too small to contain a zstd frame" % i
4345 )
4346
4347 if params.frameContentSize == lib.ZSTD_CONTENTSIZE_UNKNOWN:
4348 raise ValueError("chunk %d missing content size in frame" % i)
4349
4350 dest_buffer = ffi.new("char[]", params.frameContentSize)
4351
4352 out_buffer.dst = dest_buffer
4353 out_buffer.size = len(dest_buffer)
4354 out_buffer.pos = 0
4355
4356 in_buffer.src = chunk_buffer
4357 in_buffer.size = len(chunk_buffer)
4358 in_buffer.pos = 0
4359
4360 zresult = lib.ZSTD_decompressStream(
4361 self._dctx, out_buffer, in_buffer
4362 )
4363 if lib.ZSTD_isError(zresult):
4364 raise ZstdError(
4365 "could not decompress chunk %d: %s" % _zstd_error(zresult)
4366 )
4367 elif zresult:
4368 raise ZstdError("chunk %d did not decompress full frame" % i)
4369
4370 last_buffer = dest_buffer
4371 i += 1
4372
4373 return ffi.buffer(last_buffer, len(last_buffer))[:]
4374
4375 def multi_decompress_to_buffer(
4376 self, frames, decompressed_sizes=None, threads=0
4377 ):
4378 """
4379 Decompress multiple zstd frames to output buffers as a single operation.
4380
4381 (Experimental. Not available in CFFI backend.)
4382
4383 Compressed frames can be passed to the function as a
4384 ``BufferWithSegments``, a ``BufferWithSegmentsCollection``, or as a
4385 list containing objects that conform to the buffer protocol. For best
4386 performance, pass a ``BufferWithSegmentsCollection`` or a
4387 ``BufferWithSegments``, as minimal input validation will be done for
4388 that type. If calling from Python (as opposed to C), constructing one
4389 of these instances may add overhead cancelling out the performance
4390 overhead of validation for list inputs.
4391
4392 Returns a ``BufferWithSegmentsCollection`` containing the decompressed
4393 data. All decompressed data is allocated in a single memory buffer. The
4394 ``BufferWithSegments`` instance tracks which objects are at which offsets
4395 and their respective lengths.
4396
4397 >>> dctx = zstandard.ZstdDecompressor()
4398 >>> results = dctx.multi_decompress_to_buffer([b'...', b'...'])
4399
4400 The decompressed size of each frame MUST be discoverable. It can either be
4401 embedded within the zstd frame or passed in via the ``decompressed_sizes``
4402 argument.
4403
4404 The ``decompressed_sizes`` argument is an object conforming to the buffer
4405 protocol which holds an array of 64-bit unsigned integers in the machine's
4406 native format defining the decompressed sizes of each frame. If this argument
4407 is passed, it avoids having to scan each frame for its decompressed size.
4408 This frame scanning can add noticeable overhead in some scenarios.
4409
4410 >>> frames = [...]
4411 >>> sizes = struct.pack('=QQQQ', len0, len1, len2, len3)
4412 >>>
4413 >>> dctx = zstandard.ZstdDecompressor()
4414 >>> results = dctx.multi_decompress_to_buffer(frames, decompressed_sizes=sizes)
4415
4416 .. note::
4417
4418 It is possible to pass a ``mmap.mmap()`` instance into this function by
4419 wrapping it with a ``BufferWithSegments`` instance (which will define the
4420 offsets of frames within the memory mapped region).
4421
4422 This function is logically equivalent to performing
4423 :py:meth:`ZstdCompressor.decompress` on each input frame and returning the
4424 result.
4425
4426 This function exists to perform decompression on multiple frames as fast
4427 as possible by having as little overhead as possible. Since decompression is
4428 performed as a single operation and since the decompressed output is stored in
4429 a single buffer, extra memory allocations, Python objects, and Python function
4430 calls are avoided. This is ideal for scenarios where callers know up front that
4431 they need to access data for multiple frames, such as when *delta chains* are
4432 being used.
4433
4434 Currently, the implementation always spawns multiple threads when requested,
4435 even if the amount of work to do is small. In the future, it will be smarter
4436 about avoiding threads and their associated overhead when the amount of
4437 work to do is small.
4438
4439 :param frames:
4440 Source defining zstd frames to decompress.
4441 :param decompressed_sizes:
4442 Array of integers representing sizes of decompressed zstd frames.
4443 :param threads:
4444 How many threads to use for decompression operations.
4445
4446 Negative values will use the same number of threads as logical CPUs
4447 on the machine. Values ``0`` or ``1`` use a single thread.
4448 :return:
4449 ``BufferWithSegmentsCollection``
4450 """
4451 raise NotImplementedError()
4452
4453 def _ensure_dctx(self, load_dict=True):
4454 lib.ZSTD_DCtx_reset(self._dctx, lib.ZSTD_reset_session_only)
4455
4456 if self._max_window_size:
4457 zresult = lib.ZSTD_DCtx_setMaxWindowSize(
4458 self._dctx, self._max_window_size
4459 )
4460 if lib.ZSTD_isError(zresult):
4461 raise ZstdError(
4462 "unable to set max window size: %s" % _zstd_error(zresult)
4463 )
4464
4465 zresult = lib.ZSTD_DCtx_setParameter(
4466 self._dctx, lib.ZSTD_d_format, self._format
4467 )
4468 if lib.ZSTD_isError(zresult):
4469 raise ZstdError(
4470 "unable to set decoding format: %s" % _zstd_error(zresult)
4471 )
4472
4473 if self._dict_data and load_dict:
4474 zresult = lib.ZSTD_DCtx_refDDict(self._dctx, self._dict_data._ddict)
4475 if lib.ZSTD_isError(zresult):
4476 raise ZstdError(
4477 "unable to reference prepared dictionary: %s"
4478 % _zstd_error(zresult)
4479 )