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 | class CompressorMixin(Mixin, ABC):
"""Compressor mixin.
Adds compressing capabilities to a subclass.
"""
# ToDo: D417 is a false positive, see https://github.com/PyCQA/pydocstyle/issues/514
def __init__(
self,
*args: typing.Any,
compressor: type[CompressorInterface] = ZlibCompressor,
compression_flag: typing.Union[str, bytes] = b'.',
compression_ratio: typing.Union[int, float] = 5.0,
**kwargs: typing.Any,
) -> None: # noqa: D417
"""Add compressing capabilities.
Args:
*args: Additional positional arguments.
Keyword Args:
compressor (optional): Compressor class to use (defaults to a Zlib
compressor).
compression_flag (optional): Character to mark the payload as compressed.
It must not belong to the encoder alphabet and be ASCII (defaults
to ".").
compression_ratio (optional): Desired minimal compression ratio, between
0 and below 100 (defaults to 5). It is used to calculate when
to consider a payload sufficiently compressed to detect detrimental
compression. By default, if compression achieves less than 5% of
size reduction, it is considered detrimental.
**kwargs: Additional keyword only arguments.
"""
self._compressor = compressor()
personalisation = self._force_bytes(kwargs.get('personalisation', b''))
personalisation += self._compressor.__class__.__name__.encode()
kwargs['personalisation'] = personalisation
self._compression_flag: bytes = self._validate_comp_flag(compression_flag)
self._compression_ratio: float = self._validate_comp_ratio(compression_ratio)
super().__init__(*args, **kwargs)
def _validate_comp_flag(self, flag: typing.Union[str, bytes]) -> bytes:
"""Validate the compression flag value and return it clean.
Args:
flag: Compression flag to validate.
Returns:
Validated compression flag as bytes.
Raises:
InvalidOptionError: The compression flag is not valid.
"""
if not flag:
raise InvalidOptionError('the compression flag character must have a value')
if not flag.isascii():
raise InvalidOptionError('the compression flag character must be ASCII')
return self._force_bytes(flag)
@staticmethod
def _validate_comp_ratio(ratio: float) -> float:
"""Validate the compression ratio value and return it clean.
Args:
ratio: Compression ratio to validate.
Returns:
Validated compression ratio as float.
Raises:
InvalidOptionError: The compression ratio is out of bounds.
"""
if 0.0 <= ratio < 100.0:
return float(ratio)
raise InvalidOptionError('the compression ratio must be between 0 and less than 100')
def _add_compression_flag(self, data: bytes) -> bytes:
"""Add the compression flag to given data."""
return self._compression_flag + data # prevents zip bombs
def _is_compressed(self, data: bytes) -> bool:
"""Return True if given data is compressed, checking the compression flag."""
return data.startswith(self._compression_flag, 0, len(self._compression_flag))
def _remove_compression_flag(self, data: bytes) -> bytes:
"""Remove the compression flag from given data."""
return data[len(self._compression_flag):]
def _remove_compression_flag_if_compressed(
self,
data: bytes,
) -> tuple[bytes, bool]:
"""Remove the compression flag from given data if it is compressed.
Args:
data: Data to process.
Returns:
A tuple of given data without the flag, and a boolean indicating
if it is compressed or not.
"""
if self._is_compressed(data):
return self._remove_compression_flag(data), True
return data, False
def _is_significantly_compressed(
self,
data_size: int,
compressed_size: int,
) -> bool:
"""Return True if the compressed size is significantly lower than data size."""
return compressed_size < (data_size * (1 - (self._compression_ratio / 100)))
def _compress(
self,
data: bytes,
*,
level: typing.Optional[int] = None,
force: bool = False,
) -> tuple[bytes, bool]:
"""Compress given data if convenient or forced, otherwise do nothing.
A check is done to verify if compressed data is significantly smaller than
given data, and if not, then it returns given data as-is, unless compression
is forced.
Args:
data: Data to compress.
Keyword Args:
level (optional): Compression level wanted from 1 (least compressed)
to 9 (most compressed), or None for the default.
force (optional): Force compression without checking if convenient.
Returns:
A tuple containing data, and a flag indicating if data is compressed
(True) or not.
Raises:
CompressionError: Data can't be compressed.
"""
compression_level = self._compressor.get_compression_level(level)
try:
compressed = self._compressor.compress(data, level=compression_level)
except Exception as exc:
raise CompressionError('data can not be compressed') from exc
if force or self._is_significantly_compressed(len(data), len(compressed)):
return compressed, True
# Compression isn't reducing size so do nothing.
return data, False
def _decompress(self, data: bytes) -> bytes:
"""Decompress given data.
Args:
data: Compressed data to decompress.
Returns:
Original data.
Raises:
DecompressionError: Data can't be decompressed.
"""
try:
return self._compressor.decompress(data)
except Exception as exc:
raise DecompressionError('data can not be decompressed') from exc
|