Debian Codegraph @

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

raw
1 import enum
2
3 from backports.zstd._zstd_cffi import ffi as _ffi
4 from backports.zstd._zstd_cffi import lib as _lib
5
6 _new_nonzero = _ffi.new_allocator(should_clear_after_alloc=False)
7
8
9 class ZstdError(Exception):
10 "An error occurred in the zstd library."
11
12
13 def _nbytes(dat, /):
14 if isinstance(dat, (bytes, bytearray)):
15 return len(dat)
16 with memoryview(dat) as mv:
17 return mv.nbytes
18
19
20 class _ErrorType(enum.IntEnum):
21 ERR_DECOMPRESS = 0
22 ERR_COMPRESS = enum.auto()
23 ERR_SET_PLEDGED_INPUT_SIZE = enum.auto()
24 ERR_LOAD_D_DICT = enum.auto()
25 ERR_LOAD_C_DICT = enum.auto()
26 ERR_GET_C_BOUNDS = enum.auto()
27 ERR_GET_D_BOUNDS = enum.auto()
28 ERR_SET_C_LEVEL = enum.auto()
29 ERR_TRAIN_DICT = enum.auto()
30 ERR_FINALIZE_DICT = enum.auto()
31
32
33 class _DictionaryType(enum.IntEnum):
34 DICT_TYPE_DIGESTED = 0
35 DICT_TYPE_UNDIGESTED = enum.auto()
36 DICT_TYPE_PREFIX = enum.auto()
37
38
39 _ErrorTypeMessages = {
40 _ErrorType.ERR_DECOMPRESS: "Unable to decompress Zstandard data: %s",
41 _ErrorType.ERR_COMPRESS: "Unable to compress Zstandard data: %s",
42 _ErrorType.ERR_SET_PLEDGED_INPUT_SIZE: "Unable to set pledged uncompressed content size: %s",
43 _ErrorType.ERR_LOAD_D_DICT: "Unable to load Zstandard dictionary or prefix for decompression: %s",
44 _ErrorType.ERR_LOAD_C_DICT: "Unable to load Zstandard dictionary or prefix for compression: %s",
45 _ErrorType.ERR_GET_C_BOUNDS: "Unable to get zstd compression parameter bounds: %s",
46 _ErrorType.ERR_GET_D_BOUNDS: "Unable to get zstd decompression parameter bounds: %s",
47 _ErrorType.ERR_SET_C_LEVEL: "Unable to set zstd compression level: %s",
48 _ErrorType.ERR_TRAIN_DICT: "Unable to train the Zstandard dictionary: %s",
49 _ErrorType.ERR_FINALIZE_DICT: "Unable to finalize the Zstandard dictionary: %s",
50 }
51
52
53 def _set_zstd_error(type_, zstd_ret):
54 raise ZstdError(
55 _ErrorTypeMessages[type_]
56 % _ffi.string(_lib.ZSTD_getErrorName(zstd_ret)).decode()
57 )
58
59
60 _CpItems = {
61 _lib.ZSTD_c_compressionLevel: "compression_level",
62 _lib.ZSTD_c_windowLog: "window_log",
63 _lib.ZSTD_c_hashLog: "hash_log",
64 _lib.ZSTD_c_chainLog: "chain_log",
65 _lib.ZSTD_c_searchLog: "search_log",
66 _lib.ZSTD_c_minMatch: "min_match",
67 _lib.ZSTD_c_targetLength: "target_length",
68 _lib.ZSTD_c_strategy: "strategy",
69 _lib.ZSTD_c_enableLongDistanceMatching: "enable_long_distance_matching",
70 _lib.ZSTD_c_ldmHashLog: "ldm_hash_log",
71 _lib.ZSTD_c_ldmMinMatch: "ldm_min_match",
72 _lib.ZSTD_c_ldmBucketSizeLog: "ldm_bucket_size_log",
73 _lib.ZSTD_c_ldmHashRateLog: "ldm_hash_rate_log",
74 _lib.ZSTD_c_contentSizeFlag: "content_size_flag",
75 _lib.ZSTD_c_checksumFlag: "checksum_flag",
76 _lib.ZSTD_c_dictIDFlag: "dict_id_flag",
77 _lib.ZSTD_c_nbWorkers: "nb_workers",
78 _lib.ZSTD_c_jobSize: "job_size",
79 _lib.ZSTD_c_overlapLog: "overlap_log",
80 }
81 _DpItems = {
82 _lib.ZSTD_d_windowLogMax: "window_log_max",
83 }
84
85
86 def _set_parameter_error(is_compress, key, value):
87 if is_compress:
88 items = _CpItems
89 type_ = "compression"
90 else:
91 items = _DpItems
92 type_ = "decompression"
93
94 # Find parameter's name
95 try:
96 name = items[key]
97 # Unknown parameter
98 except KeyError:
99 name = "unknown parameter (key %d)" % key
100
101 # Get parameter bounds
102 try:
103 if is_compress:
104 bounds = _lib.ZSTD_cParam_getBounds(key)
105 else:
106 bounds = _lib.ZSTD_dParam_getBounds(key)
107 except OverflowError:
108 raise ValueError("invalid %s parameter '%s'" % (type_, name)) from None
109 if _lib.ZSTD_isError(bounds.error):
110 raise ValueError("invalid %s parameter '%s'" % (type_, name))
111
112 # Error message
113 raise ValueError(
114 "%s parameter '%s' received an illegal value %d; "
115 "the valid range is [%d, %d]"
116 % (type_, name, value, bounds.lowerBound, bounds.upperBound)
117 )
118
119
120 _PARAMETER_TYPES = {}
121
122
123 def set_parameter_types(c_parameter_type, d_parameter_type):
124 """Set CompressionParameter and DecompressionParameter types for validity check.
125
126 c_parameter_type
127 CompressionParameter IntEnum type object
128 d_parameter_type
129 DecompressionParameter IntEnum type object"""
130 _PARAMETER_TYPES["compression"] = c_parameter_type
131 _PARAMETER_TYPES["decompression"] = d_parameter_type
132
133
134 def _check_int(value):
135 if not isinstance(value, int):
136 raise TypeError(
137 f"'{value.__class__.__name__}' object cannot be interpreted as an integer"
138 )
139 if value > 2147483647 or value < -2147483648:
140 raise OverflowError("Python int too large to convert to C int")
141
142
143 def _clinic_check(fname, args, pos, expected):
144 got = type(args[pos])
145 if got != expected:
146 raise TypeError(
147 f"{fname}() argument {pos + 1} must be {expected.__name__}, not {got.__name__}"
148 )