-
-
Notifications
You must be signed in to change notification settings - Fork 90
/
backend_cffi.py
4335 lines (3392 loc) · 143 KB
/
backend_cffi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2016-present, Gregory Szorc
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the BSD license. See the LICENSE file for details.
"""Python interface to the Zstandard (zstd) compression library."""
from __future__ import absolute_import, unicode_literals
# This should match what the C extension exports.
__all__ = [
"BufferSegment",
"BufferSegments",
"BufferWithSegments",
"BufferWithSegmentsCollection",
"ZstdCompressionChunker",
"ZstdCompressionDict",
"ZstdCompressionObj",
"ZstdCompressionParameters",
"ZstdCompressionReader",
"ZstdCompressionWriter",
"ZstdCompressor",
"ZstdDecompressionObj",
"ZstdDecompressionReader",
"ZstdDecompressionWriter",
"ZstdDecompressor",
"ZstdError",
"FrameParameters",
"backend_features",
"estimate_decompression_context_size",
"frame_content_size",
"frame_header_size",
"get_frame_parameters",
"train_dictionary",
# Constants.
"FLUSH_BLOCK",
"FLUSH_FRAME",
"COMPRESSOBJ_FLUSH_FINISH",
"COMPRESSOBJ_FLUSH_BLOCK",
"ZSTD_VERSION",
"FRAME_HEADER",
"CONTENTSIZE_UNKNOWN",
"CONTENTSIZE_ERROR",
"MAX_COMPRESSION_LEVEL",
"COMPRESSION_RECOMMENDED_INPUT_SIZE",
"COMPRESSION_RECOMMENDED_OUTPUT_SIZE",
"DECOMPRESSION_RECOMMENDED_INPUT_SIZE",
"DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE",
"MAGIC_NUMBER",
"BLOCKSIZELOG_MAX",
"BLOCKSIZE_MAX",
"WINDOWLOG_MIN",
"WINDOWLOG_MAX",
"CHAINLOG_MIN",
"CHAINLOG_MAX",
"HASHLOG_MIN",
"HASHLOG_MAX",
"HASHLOG3_MAX",
"MINMATCH_MIN",
"MINMATCH_MAX",
"SEARCHLOG_MIN",
"SEARCHLOG_MAX",
"SEARCHLENGTH_MIN",
"SEARCHLENGTH_MAX",
"TARGETLENGTH_MIN",
"TARGETLENGTH_MAX",
"LDM_MINMATCH_MIN",
"LDM_MINMATCH_MAX",
"LDM_BUCKETSIZELOG_MAX",
"STRATEGY_FAST",
"STRATEGY_DFAST",
"STRATEGY_GREEDY",
"STRATEGY_LAZY",
"STRATEGY_LAZY2",
"STRATEGY_BTLAZY2",
"STRATEGY_BTOPT",
"STRATEGY_BTULTRA",
"STRATEGY_BTULTRA2",
"DICT_TYPE_AUTO",
"DICT_TYPE_RAWCONTENT",
"DICT_TYPE_FULLDICT",
"FORMAT_ZSTD1",
"FORMAT_ZSTD1_MAGICLESS",
]
import io
import os
from ._cffi import ( # type: ignore
ffi,
lib,
)
backend_features = set() # type: ignore
COMPRESSION_RECOMMENDED_INPUT_SIZE = lib.ZSTD_CStreamInSize()
COMPRESSION_RECOMMENDED_OUTPUT_SIZE = lib.ZSTD_CStreamOutSize()
DECOMPRESSION_RECOMMENDED_INPUT_SIZE = lib.ZSTD_DStreamInSize()
DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE = lib.ZSTD_DStreamOutSize()
new_nonzero = ffi.new_allocator(should_clear_after_alloc=False)
MAX_COMPRESSION_LEVEL = lib.ZSTD_maxCLevel()
MAGIC_NUMBER = lib.ZSTD_MAGICNUMBER
FRAME_HEADER = b"\x28\xb5\x2f\xfd"
CONTENTSIZE_UNKNOWN = lib.ZSTD_CONTENTSIZE_UNKNOWN
CONTENTSIZE_ERROR = lib.ZSTD_CONTENTSIZE_ERROR
ZSTD_VERSION = (
lib.ZSTD_VERSION_MAJOR,
lib.ZSTD_VERSION_MINOR,
lib.ZSTD_VERSION_RELEASE,
)
BLOCKSIZELOG_MAX = lib.ZSTD_BLOCKSIZELOG_MAX
BLOCKSIZE_MAX = lib.ZSTD_BLOCKSIZE_MAX
WINDOWLOG_MIN = lib.ZSTD_WINDOWLOG_MIN
WINDOWLOG_MAX = lib.ZSTD_WINDOWLOG_MAX
CHAINLOG_MIN = lib.ZSTD_CHAINLOG_MIN
CHAINLOG_MAX = lib.ZSTD_CHAINLOG_MAX
HASHLOG_MIN = lib.ZSTD_HASHLOG_MIN
HASHLOG_MAX = lib.ZSTD_HASHLOG_MAX
HASHLOG3_MAX = lib.ZSTD_HASHLOG3_MAX
MINMATCH_MIN = lib.ZSTD_MINMATCH_MIN
MINMATCH_MAX = lib.ZSTD_MINMATCH_MAX
SEARCHLOG_MIN = lib.ZSTD_SEARCHLOG_MIN
SEARCHLOG_MAX = lib.ZSTD_SEARCHLOG_MAX
SEARCHLENGTH_MIN = lib.ZSTD_MINMATCH_MIN
SEARCHLENGTH_MAX = lib.ZSTD_MINMATCH_MAX
TARGETLENGTH_MIN = lib.ZSTD_TARGETLENGTH_MIN
TARGETLENGTH_MAX = lib.ZSTD_TARGETLENGTH_MAX
LDM_MINMATCH_MIN = lib.ZSTD_LDM_MINMATCH_MIN
LDM_MINMATCH_MAX = lib.ZSTD_LDM_MINMATCH_MAX
LDM_BUCKETSIZELOG_MAX = lib.ZSTD_LDM_BUCKETSIZELOG_MAX
STRATEGY_FAST = lib.ZSTD_fast
STRATEGY_DFAST = lib.ZSTD_dfast
STRATEGY_GREEDY = lib.ZSTD_greedy
STRATEGY_LAZY = lib.ZSTD_lazy
STRATEGY_LAZY2 = lib.ZSTD_lazy2
STRATEGY_BTLAZY2 = lib.ZSTD_btlazy2
STRATEGY_BTOPT = lib.ZSTD_btopt
STRATEGY_BTULTRA = lib.ZSTD_btultra
STRATEGY_BTULTRA2 = lib.ZSTD_btultra2
DICT_TYPE_AUTO = lib.ZSTD_dct_auto
DICT_TYPE_RAWCONTENT = lib.ZSTD_dct_rawContent
DICT_TYPE_FULLDICT = lib.ZSTD_dct_fullDict
FORMAT_ZSTD1 = lib.ZSTD_f_zstd1
FORMAT_ZSTD1_MAGICLESS = lib.ZSTD_f_zstd1_magicless
FLUSH_BLOCK = 0
FLUSH_FRAME = 1
COMPRESSOBJ_FLUSH_FINISH = 0
COMPRESSOBJ_FLUSH_BLOCK = 1
def _cpu_count():
# os.cpu_count() was introducd in Python 3.4.
try:
return os.cpu_count() or 0
except AttributeError:
pass
# Linux.
try:
return os.sysconf("SC_NPROCESSORS_ONLN")
except (AttributeError, ValueError):
pass
# TODO implement on other platforms.
return 0
class BufferSegment:
"""Represents a segment within a ``BufferWithSegments``.
This type is essentially a reference to N bytes within a
``BufferWithSegments``.
The object conforms to the buffer protocol.
"""
@property
def offset(self):
"""The byte offset of this segment within its parent buffer."""
raise NotImplementedError()
def __len__(self):
"""Obtain the length of the segment, in bytes."""
raise NotImplementedError()
def tobytes(self):
"""Obtain bytes copy of this segment."""
raise NotImplementedError()
class BufferSegments:
"""Represents an array of ``(offset, length)`` integers.
This type is effectively an index used by :py:class:`BufferWithSegments`.
The array members are 64-bit unsigned integers using host/native bit order.
Instances conform to the buffer protocol.
"""
class BufferWithSegments:
"""A memory buffer containing N discrete items of known lengths.
This type is essentially a fixed size memory address and an array
of 2-tuples of ``(offset, length)`` 64-bit unsigned native-endian
integers defining the byte offset and length of each segment within
the buffer.
Instances behave like containers.
Instances also conform to the buffer protocol. So a reference to the
backing bytes can be obtained via ``memoryview(o)``. A *copy* of the
backing bytes can be obtained via ``.tobytes()``.
This type exists to facilitate operations against N>1 items without
the overhead of Python object creation and management. Used with
APIs like :py:meth:`ZstdDecompressor.multi_decompress_to_buffer`, it
is possible to decompress many objects in parallel without the GIL
held, leading to even better performance.
"""
@property
def size(self):
"""Total sizein bytes of the backing buffer."""
raise NotImplementedError()
def __len__(self):
raise NotImplementedError()
def __getitem__(self, i):
"""Obtains a segment within the buffer.
The returned object references memory within this buffer.
:param i:
Integer index of segment to retrieve.
:return:
:py:class:`BufferSegment`
"""
raise NotImplementedError()
def segments(self):
"""Obtain the array of ``(offset, length)`` segments in the buffer.
:return:
:py:class:`BufferSegments`
"""
raise NotImplementedError()
def tobytes(self):
"""Obtain bytes copy of this instance."""
raise NotImplementedError()
class BufferWithSegmentsCollection:
"""A virtual spanning view over multiple BufferWithSegments.
Instances are constructed from 1 or more :py:class:`BufferWithSegments`
instances. The resulting object behaves like an ordered sequence whose
members are the segments within each ``BufferWithSegments``.
If the object is composed of 2 ``BufferWithSegments`` instances with the
first having 2 segments and the second have 3 segments, then ``b[0]``
and ``b[1]`` access segments in the first object and ``b[2]``, ``b[3]``,
and ``b[4]`` access segments from the second.
"""
def __len__(self):
"""The number of segments within all ``BufferWithSegments``."""
raise NotImplementedError()
def __getitem__(self, i):
"""Obtain the ``BufferSegment`` at an offset."""
raise NotImplementedError()
class ZstdError(Exception):
pass
def _zstd_error(zresult):
# Resolves to bytes on Python 2 and 3. We use the string for formatting
# into error messages, which will be literal unicode. So convert it to
# unicode.
return ffi.string(lib.ZSTD_getErrorName(zresult)).decode("utf-8")
def _make_cctx_params(params):
res = lib.ZSTD_createCCtxParams()
if res == ffi.NULL:
raise MemoryError()
res = ffi.gc(res, lib.ZSTD_freeCCtxParams)
attrs = [
(lib.ZSTD_c_format, params.format),
(lib.ZSTD_c_compressionLevel, params.compression_level),
(lib.ZSTD_c_windowLog, params.window_log),
(lib.ZSTD_c_hashLog, params.hash_log),
(lib.ZSTD_c_chainLog, params.chain_log),
(lib.ZSTD_c_searchLog, params.search_log),
(lib.ZSTD_c_minMatch, params.min_match),
(lib.ZSTD_c_targetLength, params.target_length),
(lib.ZSTD_c_strategy, params.strategy),
(lib.ZSTD_c_contentSizeFlag, params.write_content_size),
(lib.ZSTD_c_checksumFlag, params.write_checksum),
(lib.ZSTD_c_dictIDFlag, params.write_dict_id),
(lib.ZSTD_c_nbWorkers, params.threads),
(lib.ZSTD_c_jobSize, params.job_size),
(lib.ZSTD_c_overlapLog, params.overlap_log),
(lib.ZSTD_c_forceMaxWindow, params.force_max_window),
(lib.ZSTD_c_enableLongDistanceMatching, params.enable_ldm),
(lib.ZSTD_c_ldmHashLog, params.ldm_hash_log),
(lib.ZSTD_c_ldmMinMatch, params.ldm_min_match),
(lib.ZSTD_c_ldmBucketSizeLog, params.ldm_bucket_size_log),
(lib.ZSTD_c_ldmHashRateLog, params.ldm_hash_rate_log),
]
for param, value in attrs:
_set_compression_parameter(res, param, value)
return res
class ZstdCompressionParameters(object):
"""Low-level zstd compression parameters.
This type represents a collection of parameters to control how zstd
compression is performed.
Instances can be constructed from raw parameters or derived from a
base set of defaults specified from a compression level (recommended)
via :py:meth:`ZstdCompressionParameters.from_level`.
>>> # Derive compression settings for compression level 7.
>>> params = zstandard.ZstdCompressionParameters.from_level(7)
>>> # With an input size of 1MB
>>> params = zstandard.ZstdCompressionParameters.from_level(7, source_size=1048576)
Using ``from_level()``, it is also possible to override individual compression
parameters or to define additional settings that aren't automatically derived.
e.g.:
>>> params = zstandard.ZstdCompressionParameters.from_level(4, window_log=10)
>>> params = zstandard.ZstdCompressionParameters.from_level(5, threads=4)
Or you can define low-level compression settings directly:
>>> params = zstandard.ZstdCompressionParameters(window_log=12, enable_ldm=True)
Once a ``ZstdCompressionParameters`` instance is obtained, it can be used to
configure a compressor:
>>> cctx = zstandard.ZstdCompressor(compression_params=params)
Some of these are very low-level settings. It may help to consult the official
zstandard documentation for their behavior. Look for the ``ZSTD_p_*`` constants
in ``zstd.h`` (https://github.com/facebook/zstd/blob/dev/lib/zstd.h).
"""
@staticmethod
def from_level(level, source_size=0, dict_size=0, **kwargs):
"""Create compression parameters from a compression level.
:param level:
Integer compression level.
:param source_size:
Integer size in bytes of source to be compressed.
:param dict_size:
Integer size in bytes of compression dictionary to use.
:return:
:py:class:`ZstdCompressionParameters`
"""
params = lib.ZSTD_getCParams(level, source_size, dict_size)
args = {
"window_log": "windowLog",
"chain_log": "chainLog",
"hash_log": "hashLog",
"search_log": "searchLog",
"min_match": "minMatch",
"target_length": "targetLength",
"strategy": "strategy",
}
for arg, attr in args.items():
if arg not in kwargs:
kwargs[arg] = getattr(params, attr)
return ZstdCompressionParameters(**kwargs)
def __init__(
self,
format=0,
compression_level=0,
window_log=0,
hash_log=0,
chain_log=0,
search_log=0,
min_match=0,
target_length=0,
strategy=-1,
write_content_size=1,
write_checksum=0,
write_dict_id=0,
job_size=0,
overlap_log=-1,
force_max_window=0,
enable_ldm=0,
ldm_hash_log=0,
ldm_min_match=0,
ldm_bucket_size_log=0,
ldm_hash_rate_log=-1,
threads=0,
):
params = lib.ZSTD_createCCtxParams()
if params == ffi.NULL:
raise MemoryError()
params = ffi.gc(params, lib.ZSTD_freeCCtxParams)
self._params = params
if threads < 0:
threads = _cpu_count()
# We need to set ZSTD_c_nbWorkers before ZSTD_c_jobSize and ZSTD_c_overlapLog
# because setting ZSTD_c_nbWorkers resets the other parameters.
_set_compression_parameter(params, lib.ZSTD_c_nbWorkers, threads)
_set_compression_parameter(params, lib.ZSTD_c_format, format)
_set_compression_parameter(
params, lib.ZSTD_c_compressionLevel, compression_level
)
_set_compression_parameter(params, lib.ZSTD_c_windowLog, window_log)
_set_compression_parameter(params, lib.ZSTD_c_hashLog, hash_log)
_set_compression_parameter(params, lib.ZSTD_c_chainLog, chain_log)
_set_compression_parameter(params, lib.ZSTD_c_searchLog, search_log)
_set_compression_parameter(params, lib.ZSTD_c_minMatch, min_match)
_set_compression_parameter(
params, lib.ZSTD_c_targetLength, target_length
)
if strategy == -1:
strategy = 0
_set_compression_parameter(params, lib.ZSTD_c_strategy, strategy)
_set_compression_parameter(
params, lib.ZSTD_c_contentSizeFlag, write_content_size
)
_set_compression_parameter(
params, lib.ZSTD_c_checksumFlag, write_checksum
)
_set_compression_parameter(params, lib.ZSTD_c_dictIDFlag, write_dict_id)
_set_compression_parameter(params, lib.ZSTD_c_jobSize, job_size)
if overlap_log == -1:
overlap_log = 0
_set_compression_parameter(params, lib.ZSTD_c_overlapLog, overlap_log)
_set_compression_parameter(
params, lib.ZSTD_c_forceMaxWindow, force_max_window
)
_set_compression_parameter(
params, lib.ZSTD_c_enableLongDistanceMatching, enable_ldm
)
_set_compression_parameter(params, lib.ZSTD_c_ldmHashLog, ldm_hash_log)
_set_compression_parameter(
params, lib.ZSTD_c_ldmMinMatch, ldm_min_match
)
_set_compression_parameter(
params, lib.ZSTD_c_ldmBucketSizeLog, ldm_bucket_size_log
)
if ldm_hash_rate_log == -1:
ldm_hash_rate_log = 0
_set_compression_parameter(
params, lib.ZSTD_c_ldmHashRateLog, ldm_hash_rate_log
)
@property
def format(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_format)
@property
def compression_level(self):
return _get_compression_parameter(
self._params, lib.ZSTD_c_compressionLevel
)
@property
def window_log(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_windowLog)
@property
def hash_log(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_hashLog)
@property
def chain_log(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_chainLog)
@property
def search_log(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_searchLog)
@property
def min_match(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_minMatch)
@property
def target_length(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_targetLength)
@property
def strategy(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_strategy)
@property
def write_content_size(self):
return _get_compression_parameter(
self._params, lib.ZSTD_c_contentSizeFlag
)
@property
def write_checksum(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_checksumFlag)
@property
def write_dict_id(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_dictIDFlag)
@property
def job_size(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_jobSize)
@property
def overlap_log(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_overlapLog)
@property
def force_max_window(self):
return _get_compression_parameter(
self._params, lib.ZSTD_c_forceMaxWindow
)
@property
def enable_ldm(self):
return _get_compression_parameter(
self._params, lib.ZSTD_c_enableLongDistanceMatching
)
@property
def ldm_hash_log(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_ldmHashLog)
@property
def ldm_min_match(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_ldmMinMatch)
@property
def ldm_bucket_size_log(self):
return _get_compression_parameter(
self._params, lib.ZSTD_c_ldmBucketSizeLog
)
@property
def ldm_hash_rate_log(self):
return _get_compression_parameter(
self._params, lib.ZSTD_c_ldmHashRateLog
)
@property
def threads(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_nbWorkers)
def estimated_compression_context_size(self):
"""Estimated size in bytes needed to compress with these parameters."""
return lib.ZSTD_estimateCCtxSize_usingCCtxParams(self._params)
def estimate_decompression_context_size():
"""Estimate the memory size requirements for a decompressor instance.
:return:
Integer number of bytes.
"""
return lib.ZSTD_estimateDCtxSize()
def _set_compression_parameter(params, param, value):
zresult = lib.ZSTD_CCtxParams_setParameter(params, param, value)
if lib.ZSTD_isError(zresult):
raise ZstdError(
"unable to set compression context parameter: %s"
% _zstd_error(zresult)
)
def _get_compression_parameter(params, param):
result = ffi.new("int *")
zresult = lib.ZSTD_CCtxParams_getParameter(params, param, result)
if lib.ZSTD_isError(zresult):
raise ZstdError(
"unable to get compression context parameter: %s"
% _zstd_error(zresult)
)
return result[0]
class ZstdCompressionWriter(object):
"""Writable compressing stream wrapper.
``ZstdCompressionWriter`` is a write-only stream interface for writing
compressed data to another stream.
This type conforms to the ``io.RawIOBase`` interface and should be usable
by any type that operates against a *file-object* (``typing.BinaryIO``
in Python type hinting speak). Only methods that involve writing will do
useful things.
As data is written to this stream (e.g. via ``write()``), that data
is sent to the compressor. As compressed data becomes available from
the compressor, it is sent to the underlying stream by calling its
``write()`` method.
Both ``write()`` and ``flush()`` return the number of bytes written to the
object's ``write()``. In many cases, small inputs do not accumulate enough
data to cause a write and ``write()`` will return ``0``.
Calling ``close()`` will mark the stream as closed and subsequent I/O
operations will raise ``ValueError`` (per the documented behavior of
``io.RawIOBase``). ``close()`` will also call ``close()`` on the underlying
stream if such a method exists and the instance was constructed with
``closefd=True``
Instances are obtained by calling :py:meth:`ZstdCompressor.stream_writer`.
Typically usage is as follows:
>>> cctx = zstandard.ZstdCompressor(level=10)
>>> compressor = cctx.stream_writer(fh)
>>> compressor.write(b"chunk 0\\n")
>>> compressor.write(b"chunk 1\\n")
>>> compressor.flush()
>>> # Receiver will be able to decode ``chunk 0\\nchunk 1\\n`` at this point.
>>> # Receiver is also expecting more data in the zstd *frame*.
>>>
>>> compressor.write(b"chunk 2\\n")
>>> compressor.flush(zstandard.FLUSH_FRAME)
>>> # Receiver will be able to decode ``chunk 0\\nchunk 1\\nchunk 2``.
>>> # Receiver is expecting no more data, as the zstd frame is closed.
>>> # Any future calls to ``write()`` at this point will construct a new
>>> # zstd frame.
Instances can be used as context managers. Exiting the context manager is
the equivalent of calling ``close()``, which is equivalent to calling
``flush(zstandard.FLUSH_FRAME)``:
>>> cctx = zstandard.ZstdCompressor(level=10)
>>> with cctx.stream_writer(fh) as compressor:
... compressor.write(b'chunk 0')
... compressor.write(b'chunk 1')
... ...
.. important::
If ``flush(FLUSH_FRAME)`` is not called, emitted data doesn't
constitute a full zstd *frame* and consumers of this data may complain
about malformed input. It is recommended to use instances as a context
manager to ensure *frames* are properly finished.
If the size of the data being fed to this streaming compressor is known,
you can declare it before compression begins:
>>> cctx = zstandard.ZstdCompressor()
>>> with cctx.stream_writer(fh, size=data_len) as compressor:
... compressor.write(chunk0)
... compressor.write(chunk1)
... ...
Declaring the size of the source data allows compression parameters to
be tuned. And if ``write_content_size`` is used, it also results in the
content size being written into the frame header of the output data.
The size of chunks being ``write()`` to the destination can be specified:
>>> cctx = zstandard.ZstdCompressor()
>>> with cctx.stream_writer(fh, write_size=32768) as compressor:
... ...
To see how much memory is being used by the streaming compressor:
>>> cctx = zstandard.ZstdCompressor()
>>> with cctx.stream_writer(fh) as compressor:
... ...
... byte_size = compressor.memory_size()
Thte total number of bytes written so far are exposed via ``tell()``:
>>> cctx = zstandard.ZstdCompressor()
>>> with cctx.stream_writer(fh) as compressor:
... ...
... total_written = compressor.tell()
``stream_writer()`` accepts a ``write_return_read`` boolean argument to
control the return value of ``write()``. When ``False`` (the default),
``write()`` returns the number of bytes that were ``write()``'en to the
underlying object. When ``True``, ``write()`` returns the number of bytes
read from the input that were subsequently written to the compressor.
``True`` is the *proper* behavior for ``write()`` as specified by the
``io.RawIOBase`` interface and will become the default value in a future
release.
"""
def __init__(
self,
compressor,
writer,
source_size,
write_size,
write_return_read,
closefd=True,
):
self._compressor = compressor
self._writer = writer
self._write_size = write_size
self._write_return_read = bool(write_return_read)
self._closefd = bool(closefd)
self._entered = False
self._closing = False
self._closed = False
self._bytes_compressed = 0
self._dst_buffer = ffi.new("char[]", write_size)
self._out_buffer = ffi.new("ZSTD_outBuffer *")
self._out_buffer.dst = self._dst_buffer
self._out_buffer.size = len(self._dst_buffer)
self._out_buffer.pos = 0
zresult = lib.ZSTD_CCtx_setPledgedSrcSize(compressor._cctx, source_size)
if lib.ZSTD_isError(zresult):
raise ZstdError(
"error setting source size: %s" % _zstd_error(zresult)
)
def __enter__(self):
if self._closed:
raise ValueError("stream is closed")
if self._entered:
raise ZstdError("cannot __enter__ multiple times")
self._entered = True
return self
def __exit__(self, exc_type, exc_value, exc_tb):
self._entered = False
self.close()
self._compressor = None
return False
def memory_size(self):
return lib.ZSTD_sizeof_CCtx(self._compressor._cctx)
def fileno(self):
f = getattr(self._writer, "fileno", None)
if f:
return f()
else:
raise OSError("fileno not available on underlying writer")
def close(self):
if self._closed:
return
try:
self._closing = True
self.flush(FLUSH_FRAME)
finally:
self._closing = False
self._closed = True
# Call close() on underlying stream as well.
f = getattr(self._writer, "close", None)
if self._closefd and f:
f()
@property
def closed(self):
return self._closed
def isatty(self):
return False
def readable(self):
return False
def readline(self, size=-1):
raise io.UnsupportedOperation()
def readlines(self, hint=-1):
raise io.UnsupportedOperation()
def seek(self, offset, whence=None):
raise io.UnsupportedOperation()
def seekable(self):
return False
def truncate(self, size=None):
raise io.UnsupportedOperation()
def writable(self):
return True
def writelines(self, lines):
raise NotImplementedError("writelines() is not yet implemented")
def read(self, size=-1):
raise io.UnsupportedOperation()
def readall(self):
raise io.UnsupportedOperation()
def readinto(self, b):
raise io.UnsupportedOperation()
def write(self, data):
"""Send data to the compressor and possibly to the inner stream."""
if self._closed:
raise ValueError("stream is closed")
total_write = 0
data_buffer = ffi.from_buffer(data)
in_buffer = ffi.new("ZSTD_inBuffer *")
in_buffer.src = data_buffer
in_buffer.size = len(data_buffer)
in_buffer.pos = 0
out_buffer = self._out_buffer
out_buffer.pos = 0
while in_buffer.pos < in_buffer.size:
zresult = lib.ZSTD_compressStream2(
self._compressor._cctx,
out_buffer,
in_buffer,
lib.ZSTD_e_continue,
)
if lib.ZSTD_isError(zresult):
raise ZstdError(
"zstd compress error: %s" % _zstd_error(zresult)
)
if out_buffer.pos:
self._writer.write(
ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
)
total_write += out_buffer.pos
self._bytes_compressed += out_buffer.pos
out_buffer.pos = 0
if self._write_return_read:
return in_buffer.pos
else:
return total_write
def flush(self, flush_mode=FLUSH_BLOCK):
"""Evict data from compressor's internal state and write it to inner stream.
Calling this method may result in 0 or more ``write()`` calls to the
inner stream.
This method will also call ``flush()`` on the inner stream, if such a
method exists.
:param flush_mode:
How to flush the zstd compressor.
``zstandard.FLUSH_BLOCK`` will flush data already sent to the
compressor but not emitted to the inner stream. The stream is still
writable after calling this. This is the default behavior.
See documentation for other ``zstandard.FLUSH_*`` constants for more
flushing options.
:return:
Integer number of bytes written to the inner stream.
"""
if flush_mode == FLUSH_BLOCK:
flush = lib.ZSTD_e_flush
elif flush_mode == FLUSH_FRAME:
flush = lib.ZSTD_e_end
else:
raise ValueError("unknown flush_mode: %r" % flush_mode)
if self._closed:
raise ValueError("stream is closed")
total_write = 0
out_buffer = self._out_buffer
out_buffer.pos = 0
in_buffer = ffi.new("ZSTD_inBuffer *")
in_buffer.src = ffi.NULL
in_buffer.size = 0
in_buffer.pos = 0
while True:
zresult = lib.ZSTD_compressStream2(
self._compressor._cctx, out_buffer, in_buffer, flush
)
if lib.ZSTD_isError(zresult):
raise ZstdError(
"zstd compress error: %s" % _zstd_error(zresult)
)
if out_buffer.pos:
self._writer.write(
ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
)
total_write += out_buffer.pos
self._bytes_compressed += out_buffer.pos
out_buffer.pos = 0
if not zresult:
break
f = getattr(self._writer, "flush", None)
if f and not self._closing:
f()
return total_write
def tell(self):
return self._bytes_compressed
class ZstdCompressionObj(object):
"""A compressor conforming to the API in Python's standard library.
This type implements an API similar to compression types in Python's
standard library such as ``zlib.compressobj`` and ``bz2.BZ2Compressor``.
This enables existing code targeting the standard library API to swap
in this type to achieve zstd compression.
.. important::
The design of this API is not ideal for optimal performance.
The reason performance is not optimal is because the API is limited to
returning a single buffer holding compressed data. When compressing
data, we don't know how much data will be emitted. So in order to
capture all this data in a single buffer, we need to perform buffer
reallocations and/or extra memory copies. This can add significant
overhead depending on the size or nature of the compressed data how
much your application calls this type.
If performance is critical, consider an API like
:py:meth:`ZstdCompressor.stream_reader`,
:py:meth:`ZstdCompressor.stream_writer`,
:py:meth:`ZstdCompressor.chunker`, or
:py:meth:`ZstdCompressor.read_to_iter`, which result in less overhead
managing buffers.
Instances are obtained by calling :py:meth:`ZstdCompressor.compressobj`.
Here is how this API should be used:
>>> cctx = zstandard.ZstdCompressor()
>>> cobj = cctx.compressobj()
>>> data = cobj.compress(b"raw input 0")
>>> data = cobj.compress(b"raw input 1")
>>> data = cobj.flush()
Or to flush blocks:
>>> cctx.zstandard.ZstdCompressor()