/
cffi.py
2615 lines (2013 loc) · 78.9 KB
/
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',
"CompressionParameters",
"ZstdCompressionDict",
"ZstdCompressionParameters",
"ZstdCompressor",
"ZstdError",
"ZstdDecompressor",
"FrameParameters",
"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
import sys
from _zstd_cffi import (
ffi,
lib,
)
if sys.version_info[0] == 2:
bytes_type = str
int_type = long
else:
bytes_type = bytes
int_type = int
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:
if sys.version_info[0] == 2:
return os.sysconf(b"SC_NPROCESSORS_ONLN")
else:
return os.sysconf("SC_NPROCESSORS_ONLN")
except (AttributeError, ValueError):
pass
# TODO implement on other platforms.
return 0
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.compression_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):
@staticmethod
def from_level(level, source_size=0, dict_size=0, **kwargs):
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",
"compression_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,
compression_strategy=-1,
write_content_size=1,
write_checksum=0,
write_dict_id=0,
job_size=0,
overlap_log=-1,
overlap_size_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,
ldm_hash_every_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 and compression_strategy != -1:
raise ValueError("cannot specify both compression_strategy and strategy")
if compression_strategy != -1:
strategy = compression_strategy
elif 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 and overlap_size_log != -1:
raise ValueError("cannot specify both overlap_log and overlap_size_log")
if overlap_size_log != -1:
overlap_log = overlap_size_log
elif 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 and ldm_hash_every_log != -1:
raise ValueError(
"cannot specify both ldm_hash_rate_log and ldm_hash_every_log"
)
if ldm_hash_every_log != -1:
ldm_hash_rate_log = ldm_hash_every_log
elif 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 compression_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 overlap_size_log(self):
return self.overlap_log
@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 ldm_hash_every_log(self):
return self.ldm_hash_rate_log
@property
def threads(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_nbWorkers)
def estimated_compression_context_size(self):
return lib.ZSTD_estimateCCtxSize_usingCCtxParams(self._params)
CompressionParameters = ZstdCompressionParameters
def estimate_decompression_context_size():
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):
def __init__(self, compressor, writer, source_size, write_size, write_return_read):
self._compressor = compressor
self._writer = writer
self._write_size = write_size
self._write_return_read = bool(write_return_read)
self._entered = 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
if not exc_type and not exc_value and not exc_tb:
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.flush(FLUSH_FRAME)
finally:
self._closed = True
# Call close() on underlying stream as well.
f = getattr(self._writer, "close", None)
if 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):
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):
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
return total_write
def tell(self):
return self._bytes_compressed
class ZstdCompressionObj(object):
def compress(self, data):
if self._finished:
raise ZstdError("cannot call compress() after compressor finished")
data_buffer = ffi.from_buffer(data)
source = ffi.new("ZSTD_inBuffer *")
source.src = data_buffer
source.size = len(data_buffer)
source.pos = 0
chunks = []
while source.pos < len(data):
zresult = lib.ZSTD_compressStream2(
self._compressor._cctx, self._out, source, lib.ZSTD_e_continue
)
if lib.ZSTD_isError(zresult):
raise ZstdError("zstd compress error: %s" % _zstd_error(zresult))
if self._out.pos:
chunks.append(ffi.buffer(self._out.dst, self._out.pos)[:])
self._out.pos = 0
return b"".join(chunks)
def flush(self, flush_mode=COMPRESSOBJ_FLUSH_FINISH):
if flush_mode not in (COMPRESSOBJ_FLUSH_FINISH, COMPRESSOBJ_FLUSH_BLOCK):
raise ValueError("flush mode not recognized")
if self._finished:
raise ZstdError("compressor object already finished")
if flush_mode == COMPRESSOBJ_FLUSH_BLOCK:
z_flush_mode = lib.ZSTD_e_flush
elif flush_mode == COMPRESSOBJ_FLUSH_FINISH:
z_flush_mode = lib.ZSTD_e_end
self._finished = True
else:
raise ZstdError("unhandled flush mode")
assert self._out.pos == 0
in_buffer = ffi.new("ZSTD_inBuffer *")
in_buffer.src = ffi.NULL
in_buffer.size = 0
in_buffer.pos = 0
chunks = []
while True:
zresult = lib.ZSTD_compressStream2(
self._compressor._cctx, self._out, in_buffer, z_flush_mode
)
if lib.ZSTD_isError(zresult):
raise ZstdError(
"error ending compression stream: %s" % _zstd_error(zresult)
)
if self._out.pos:
chunks.append(ffi.buffer(self._out.dst, self._out.pos)[:])
self._out.pos = 0
if not zresult:
break
return b"".join(chunks)
class ZstdCompressionChunker(object):
def __init__(self, compressor, chunk_size):
self._compressor = compressor
self._out = ffi.new("ZSTD_outBuffer *")
self._dst_buffer = ffi.new("char[]", chunk_size)
self._out.dst = self._dst_buffer
self._out.size = chunk_size
self._out.pos = 0
self._in = ffi.new("ZSTD_inBuffer *")
self._in.src = ffi.NULL
self._in.size = 0
self._in.pos = 0
self._finished = False
def compress(self, data):
if self._finished:
raise ZstdError("cannot call compress() after compression finished")
if self._in.src != ffi.NULL:
raise ZstdError(
"cannot perform operation before consuming output "
"from previous operation"
)
data_buffer = ffi.from_buffer(data)
if not len(data_buffer):
return
self._in.src = data_buffer
self._in.size = len(data_buffer)
self._in.pos = 0
while self._in.pos < self._in.size:
zresult = lib.ZSTD_compressStream2(
self._compressor._cctx, self._out, self._in, lib.ZSTD_e_continue
)
if self._in.pos == self._in.size:
self._in.src = ffi.NULL
self._in.size = 0
self._in.pos = 0
if lib.ZSTD_isError(zresult):
raise ZstdError("zstd compress error: %s" % _zstd_error(zresult))
if self._out.pos == self._out.size:
yield ffi.buffer(self._out.dst, self._out.pos)[:]
self._out.pos = 0
def flush(self):
if self._finished:
raise ZstdError("cannot call flush() after compression finished")
if self._in.src != ffi.NULL:
raise ZstdError(
"cannot call flush() before consuming output from " "previous operation"
)
while True:
zresult = lib.ZSTD_compressStream2(
self._compressor._cctx, self._out, self._in, lib.ZSTD_e_flush
)
if lib.ZSTD_isError(zresult):
raise ZstdError("zstd compress error: %s" % _zstd_error(zresult))
if self._out.pos:
yield ffi.buffer(self._out.dst, self._out.pos)[:]
self._out.pos = 0
if not zresult:
return
def finish(self):
if self._finished:
raise ZstdError("cannot call finish() after compression finished")
if self._in.src != ffi.NULL:
raise ZstdError(
"cannot call finish() before consuming output from "
"previous operation"
)
while True:
zresult = lib.ZSTD_compressStream2(
self._compressor._cctx, self._out, self._in, lib.ZSTD_e_end
)
if lib.ZSTD_isError(zresult):
raise ZstdError("zstd compress error: %s" % _zstd_error(zresult))
if self._out.pos:
yield ffi.buffer(self._out.dst, self._out.pos)[:]
self._out.pos = 0
if not zresult:
self._finished = True
return
class ZstdCompressionReader(object):
def __init__(self, compressor, source, read_size):
self._compressor = compressor
self._source = source
self._read_size = read_size
self._entered = False
self._closed = False
self._bytes_compressed = 0
self._finished_input = False
self._finished_output = False
self._in_buffer = ffi.new("ZSTD_inBuffer *")
# Holds a ref so backing bytes in self._in_buffer stay alive.
self._source_buffer = None
def __enter__(self):
if self._entered:
raise ValueError("cannot __enter__ multiple times")
self._entered = True
return self
def __exit__(self, exc_type, exc_value, exc_tb):
self._entered = False
self._closed = True
self._source = None
self._compressor = None
return False
def readable(self):
return True
def writable(self):
return False
def seekable(self):
return False
def readline(self):
raise io.UnsupportedOperation()
def readlines(self):
raise io.UnsupportedOperation()
def write(self, data):
raise OSError("stream is not writable")
def writelines(self, ignored):
raise OSError("stream is not writable")
def isatty(self):
return False
def flush(self):
return None
def close(self):
self._closed = True
return None
@property
def closed(self):
return self._closed
def tell(self):
return self._bytes_compressed
def readall(self):
chunks = []
while True:
chunk = self.read(1048576)
if not chunk:
break
chunks.append(chunk)
return b"".join(chunks)
def __iter__(self):
raise io.UnsupportedOperation()
def __next__(self):
raise io.UnsupportedOperation()
next = __next__
def _read_input(self):
if self._finished_input:
return
if hasattr(self._source, "read"):
data = self._source.read(self._read_size)
if not data:
self._finished_input = True
return
self._source_buffer = ffi.from_buffer(data)
self._in_buffer.src = self._source_buffer
self._in_buffer.size = len(self._source_buffer)
self._in_buffer.pos = 0
else:
self._source_buffer = ffi.from_buffer(self._source)
self._in_buffer.src = self._source_buffer
self._in_buffer.size = len(self._source_buffer)
self._in_buffer.pos = 0
def _compress_into_buffer(self, out_buffer):
if self._in_buffer.pos >= self._in_buffer.size:
return
old_pos = out_buffer.pos
zresult = lib.ZSTD_compressStream2(
self._compressor._cctx, out_buffer, self._in_buffer, lib.ZSTD_e_continue
)
self._bytes_compressed += out_buffer.pos - old_pos
if self._in_buffer.pos == self._in_buffer.size:
self._in_buffer.src = ffi.NULL
self._in_buffer.pos = 0
self._in_buffer.size = 0
self._source_buffer = None
if not hasattr(self._source, "read"):
self._finished_input = True
if lib.ZSTD_isError(zresult):
raise ZstdError("zstd compress error: %s", _zstd_error(zresult))
return out_buffer.pos and out_buffer.pos == out_buffer.size
def read(self, size=-1):
if self._closed:
raise ValueError("stream is closed")
if size < -1:
raise ValueError("cannot read negative amounts less than -1")
if size == -1:
return self.readall()
if self._finished_output or size == 0:
return b""
# Need a dedicated ref to dest buffer otherwise it gets collected.
dst_buffer = ffi.new("char[]", size)
out_buffer = ffi.new("ZSTD_outBuffer *")
out_buffer.dst = dst_buffer
out_buffer.size = size
out_buffer.pos = 0
if self._compress_into_buffer(out_buffer):
return ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
while not self._finished_input:
self._read_input()
if self._compress_into_buffer(out_buffer):
return ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
# EOF
old_pos = out_buffer.pos
zresult = lib.ZSTD_compressStream2(
self._compressor._cctx, out_buffer, self._in_buffer, lib.ZSTD_e_end
)
self._bytes_compressed += out_buffer.pos - old_pos
if lib.ZSTD_isError(zresult):
raise ZstdError("error ending compression stream: %s", _zstd_error(zresult))