| 1 |
import sys |
| 2 |
from pypy.interpreter.gateway import interp2app, unwrap_spec |
| 3 |
from pypy.interpreter.baseobjspace import W_Root |
| 4 |
from pypy.interpreter.typedef import TypeDef, interp_attrproperty |
| 5 |
from pypy.interpreter.error import OperationError, oefmt |
| 6 |
from rpython.rlib.rarithmetic import intmask, r_uint, r_uint32 |
| 7 |
from rpython.rlib.objectmodel import keepalive_until_here |
| 8 |
from rpython.rtyper.tool import rffi_platform |
| 9 |
|
| 10 |
from rpython.rlib import rzlib |
| 11 |
|
| 12 |
|
| 13 |
constantnames = ''' |
| 14 |
Z_NO_COMPRESSION Z_RLE Z_PARTIAL_FLUSH Z_FIXED Z_BLOCK Z_TREES |
| 15 |
'''.split() |
| 16 |
class SimpleCConfig: |
| 17 |
""" |
| 18 |
Definitions for additional constants in python3.11+. |
| 19 |
""" |
| 20 |
_compilation_info_ = rzlib.eci |
| 21 |
|
| 22 |
for _name in constantnames: |
| 23 |
setattr(SimpleCConfig, _name, rffi_platform.ConstantInteger(_name)) |
| 24 |
|
| 25 |
config = rffi_platform.configure(SimpleCConfig) |
| 26 |
for _name in constantnames: |
| 27 |
globals()[_name] = config[_name] |
| 28 |
|
| 29 |
|
| 30 |
@unwrap_spec(string='bufferstr', start='truncatedint_w') |
| 31 |
def crc32(space, string, start = rzlib.CRC32_DEFAULT_START): |
| 32 |
""" |
| 33 |
crc32(string[, start]) -- Compute a CRC-32 checksum of string. |
| 34 |
|
| 35 |
An optional starting value can be specified. The returned checksum is |
| 36 |
an integer. |
| 37 |
""" |
| 38 |
ustart = r_uint(r_uint32(start)) |
| 39 |
checksum = rzlib.crc32(string, ustart) |
| 40 |
return space.newint(checksum) |
| 41 |
|
| 42 |
|
| 43 |
@unwrap_spec(string='bufferstr', start='truncatedint_w') |
| 44 |
def adler32(space, string, start=rzlib.ADLER32_DEFAULT_START): |
| 45 |
""" |
| 46 |
adler32(string[, start]) -- Compute an Adler-32 checksum of string. |
| 47 |
|
| 48 |
An optional starting value can be specified. The returned checksum is |
| 49 |
an integer. |
| 50 |
""" |
| 51 |
ustart = r_uint(r_uint32(start)) |
| 52 |
checksum = rzlib.adler32(string, ustart) |
| 53 |
return space.newint(checksum) |
| 54 |
|
| 55 |
|
| 56 |
class Cache: |
| 57 |
def __init__(self, space): |
| 58 |
self.w_error = space.new_exception_class("zlib.error") |
| 59 |
|
| 60 |
def zlib_error(space, msg): |
| 61 |
w_error = space.fromcache(Cache).w_error |
| 62 |
return OperationError(w_error, space.newtext(msg)) |
| 63 |
|
| 64 |
|
| 65 |
@unwrap_spec(data='bufferstr', level=int, wbits=int) |
| 66 |
def compress(space, data, __posonly__=None, level=rzlib.Z_DEFAULT_COMPRESSION, wbits=rzlib.MAX_WBITS): |
| 67 |
""" |
| 68 |
Returns a bytes object containing compressed data. |
| 69 |
|
| 70 |
data |
| 71 |
Binary data to be compressed. |
| 72 |
level |
| 73 |
Compression level, in 0-9 or -1. |
| 74 |
wbits |
| 75 |
The window buffer size and container format. |
| 76 |
""" |
| 77 |
try: |
| 78 |
try: |
| 79 |
stream = rzlib.deflateInit(level=level, wbits=wbits) |
| 80 |
except ValueError: |
| 81 |
raise zlib_error(space, "Bad compression level") |
| 82 |
try: |
| 83 |
result = rzlib.compress(stream, data, rzlib.Z_FINISH) |
| 84 |
finally: |
| 85 |
rzlib.deflateEnd(stream) |
| 86 |
except rzlib.RZlibError as e: |
| 87 |
raise zlib_error(space, e.msg) |
| 88 |
return space.newbytes(result) |
| 89 |
|
| 90 |
|
| 91 |
@unwrap_spec(string='bufferstr', wbits="c_int", bufsize=int) |
| 92 |
def decompress(space, string, __posonly__=None, wbits=rzlib.MAX_WBITS, bufsize=0): |
| 93 |
""" |
| 94 |
decompress(string[, wbits[, bufsize]]) -- Return decompressed string. |
| 95 |
|
| 96 |
Optional arg wbits is the window buffer size. Optional arg bufsize is |
| 97 |
only for compatibility with CPython and is ignored. |
| 98 |
""" |
| 99 |
try: |
| 100 |
try: |
| 101 |
stream = rzlib.inflateInit(wbits) |
| 102 |
except ValueError: |
| 103 |
raise zlib_error(space, "Bad window buffer size") |
| 104 |
try: |
| 105 |
result, _, _ = rzlib.decompress(stream, string, rzlib.Z_FINISH) |
| 106 |
finally: |
| 107 |
rzlib.inflateEnd(stream) |
| 108 |
except rzlib.RZlibError as e: |
| 109 |
raise zlib_error(space, e.msg) |
| 110 |
return space.newbytes(result) |
| 111 |
|
| 112 |
|
| 113 |
class ZLibObject(W_Root): |
| 114 |
""" |
| 115 |
Common base class for Compress and Decompress. |
| 116 |
""" |
| 117 |
stream = rzlib.null_stream |
| 118 |
|
| 119 |
def __init__(self, space): |
| 120 |
self._lock = space.allocate_lock() |
| 121 |
|
| 122 |
def lock(self): |
| 123 |
"""To call before using self.stream.""" |
| 124 |
self._lock.acquire(True) |
| 125 |
|
| 126 |
def unlock(self): |
| 127 |
"""To call after using self.stream.""" |
| 128 |
self._lock.release() |
| 129 |
keepalive_until_here(self) |
| 130 |
|
| 131 |
|
| 132 |
|
| 133 |
|
| 134 |
class Compress(ZLibObject): |
| 135 |
""" |
| 136 |
Wrapper around zlib's z_stream structure which provides convenient |
| 137 |
compression functionality. |
| 138 |
""" |
| 139 |
def __init__(self, space, stream): |
| 140 |
ZLibObject.__init__(self, space) |
| 141 |
self.stream = stream |
| 142 |
self.register_finalizer(space) |
| 143 |
|
| 144 |
def _finalize_(self): |
| 145 |
"""Automatically free the resources used by the stream.""" |
| 146 |
if self.stream: |
| 147 |
rzlib.deflateEnd(self.stream) |
| 148 |
self.stream = rzlib.null_stream |
| 149 |
|
| 150 |
@unwrap_spec(data='bufferstr') |
| 151 |
def compress(self, space, data, __posonly__=None): |
| 152 |
""" |
| 153 |
compress(data) -- Return a string containing data compressed. |
| 154 |
|
| 155 |
After calling this function, some of the input data may still be stored |
| 156 |
in internal buffers for later processing. |
| 157 |
|
| 158 |
Call the flush() method to clear these buffers. |
| 159 |
""" |
| 160 |
try: |
| 161 |
self.lock() |
| 162 |
try: |
| 163 |
if not self.stream: |
| 164 |
raise zlib_error(space, |
| 165 |
"compressor object already flushed") |
| 166 |
result = rzlib.compress(self.stream, data) |
| 167 |
finally: |
| 168 |
self.unlock() |
| 169 |
except rzlib.RZlibError as e: |
| 170 |
raise zlib_error(space, e.msg) |
| 171 |
return space.newbytes(result) |
| 172 |
|
| 173 |
def copy(self, space): |
| 174 |
""" |
| 175 |
copy() -- Return a copy of the compression object. |
| 176 |
""" |
| 177 |
try: |
| 178 |
self.lock() |
| 179 |
try: |
| 180 |
if not self.stream: |
| 181 |
raise oefmt( |
| 182 |
space.w_ValueError, |
| 183 |
"Compressor was already flushed", |
| 184 |
) |
| 185 |
copied = rzlib.deflateCopy(self.stream) |
| 186 |
finally: |
| 187 |
self.unlock() |
| 188 |
except rzlib.RZlibError as e: |
| 189 |
raise zlib_error(space, e.msg) |
| 190 |
return Compress(space=space, stream=copied) |
| 191 |
|
| 192 |
def descr_deepcopy(self, space, w_memo): |
| 193 |
return self.copy(space) |
| 194 |
|
| 195 |
|
| 196 |
@unwrap_spec(mode="c_int") |
| 197 |
def flush(self, space, mode=rzlib.Z_FINISH): |
| 198 |
""" |
| 199 |
flush( [mode] ) -- Return a string containing any remaining compressed |
| 200 |
data. |
| 201 |
|
| 202 |
mode can be one of the constants Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH; |
| 203 |
the default value used when mode is not specified is Z_FINISH. |
| 204 |
|
| 205 |
If mode == Z_FINISH, the compressor object can no longer be used after |
| 206 |
calling the flush() method. Otherwise, more data can still be |
| 207 |
compressed. |
| 208 |
""" |
| 209 |
try: |
| 210 |
self.lock() |
| 211 |
try: |
| 212 |
if not self.stream: |
| 213 |
raise zlib_error(space, |
| 214 |
"compressor object already flushed") |
| 215 |
result = rzlib.compress(self.stream, '', mode) |
| 216 |
if mode == rzlib.Z_FINISH: |
| 217 |
rzlib.deflateEnd(self.stream) |
| 218 |
self.stream = rzlib.null_stream |
| 219 |
self.may_unregister_rpython_finalizer(space) |
| 220 |
finally: |
| 221 |
self.unlock() |
| 222 |
except rzlib.RZlibError as e: |
| 223 |
raise zlib_error(space, e.msg) |
| 224 |
return space.newbytes(result) |
| 225 |
|
| 226 |
|
| 227 |
@unwrap_spec(level=int, method=int, wbits=int, memLevel=int, strategy=int) |
| 228 |
def Compress___new__(space, w_subtype, level=rzlib.Z_DEFAULT_COMPRESSION, |
| 229 |
method=rzlib.Z_DEFLATED, |
| 230 |
wbits=rzlib.MAX_WBITS, |
| 231 |
memLevel=rzlib.DEF_MEM_LEVEL, |
| 232 |
strategy=rzlib.Z_DEFAULT_STRATEGY, |
| 233 |
w_zdict=None): |
| 234 |
""" |
| 235 |
Create a new z_stream and call its initializer. |
| 236 |
""" |
| 237 |
if space.is_none(w_zdict): |
| 238 |
zdict = None |
| 239 |
else: |
| 240 |
zdict = space.charbuf_w(w_zdict) |
| 241 |
w_stream = space.allocate_instance(Compress, w_subtype) |
| 242 |
w_stream = space.interp_w(Compress, w_stream) |
| 243 |
try: |
| 244 |
stream = rzlib.deflateInit(level, method, wbits, memLevel, strategy, |
| 245 |
zdict=zdict) |
| 246 |
except rzlib.RZlibError as e: |
| 247 |
raise zlib_error(space, e.msg) |
| 248 |
except ValueError: |
| 249 |
raise oefmt(space.w_ValueError, "Invalid initialization option") |
| 250 |
Compress.__init__(w_stream, space, stream) |
| 251 |
return w_stream |
| 252 |
|
| 253 |
|
| 254 |
Compress.typedef = TypeDef( |
| 255 |
'Compress', |
| 256 |
__new__ = interp2app(Compress___new__), |
| 257 |
copy = interp2app(Compress.copy), |
| 258 |
__copy__ = interp2app(Compress.copy), |
| 259 |
__deepcopy__ = interp2app(Compress.descr_deepcopy), |
| 260 |
compress = interp2app(Compress.compress), |
| 261 |
flush = interp2app(Compress.flush), |
| 262 |
__doc__ = """compressobj([level]) -- Return a compressor object. |
| 263 |
|
| 264 |
Optional arg level is the compression level, in 1-9. |
| 265 |
""") |
| 266 |
|
| 267 |
|
| 268 |
class Decompress(ZLibObject): |
| 269 |
""" |
| 270 |
Wrapper around zlib's z_stream structure which provides convenient |
| 271 |
decompression functionality. |
| 272 |
""" |
| 273 |
def __init__(self, space, stream, zdict, unused_data, unconsumed_tail): |
| 274 |
""" |
| 275 |
Initialize a new decompression object. |
| 276 |
|
| 277 |
wbits is an integer between 8 and MAX_WBITS or -8 and -MAX_WBITS |
| 278 |
(inclusive) giving the number of "window bits" to use for compression |
| 279 |
and decompression. See the documentation for deflateInit2 and |
| 280 |
inflateInit2. |
| 281 |
""" |
| 282 |
ZLibObject.__init__(self, space) |
| 283 |
|
| 284 |
self.stream = stream |
| 285 |
self.zdict = zdict |
| 286 |
self.unused_data = unused_data |
| 287 |
self.unconsumed_tail = unconsumed_tail |
| 288 |
self.eof = False |
| 289 |
self.register_finalizer(space) |
| 290 |
|
| 291 |
def _finalize_(self): |
| 292 |
"""Automatically free the resources used by the stream.""" |
| 293 |
if self.stream: |
| 294 |
rzlib.inflateEnd(self.stream) |
| 295 |
self.stream = rzlib.null_stream |
| 296 |
|
| 297 |
def _save_unconsumed_input(self, data, finished, unused_len): |
| 298 |
unused_start = len(data) - unused_len |
| 299 |
assert unused_start >= 0 |
| 300 |
tail = data[unused_start:] |
| 301 |
if finished: |
| 302 |
self.unconsumed_tail = '' |
| 303 |
self.unused_data += tail |
| 304 |
else: |
| 305 |
self.unconsumed_tail = tail |
| 306 |
|
| 307 |
@unwrap_spec(data='bufferstr', max_length=int) |
| 308 |
def decompress(self, space, data, __posonly__=None, max_length=0): |
| 309 |
""" |
| 310 |
decompress(data[, max_length]) -- Return a string containing the |
| 311 |
decompressed version of the data. |
| 312 |
|
| 313 |
If the max_length parameter is specified then the return value will be |
| 314 |
no longer than max_length. Unconsumed input data will be stored in the |
| 315 |
unconsumed_tail attribute. |
| 316 |
""" |
| 317 |
if max_length == 0: |
| 318 |
max_length = sys.maxint |
| 319 |
elif max_length < 0: |
| 320 |
raise oefmt(space.w_ValueError, |
| 321 |
"max_length must be greater than zero") |
| 322 |
try: |
| 323 |
self.lock() |
| 324 |
try: |
| 325 |
result = rzlib.decompress(self.stream, data, |
| 326 |
max_length=max_length, |
| 327 |
zdict=self.zdict) |
| 328 |
finally: |
| 329 |
self.unlock() |
| 330 |
except rzlib.RZlibError as e: |
| 331 |
raise zlib_error(space, e.msg) |
| 332 |
|
| 333 |
string, finished, unused_len = result |
| 334 |
self.eof = finished |
| 335 |
self._save_unconsumed_input(data, finished, unused_len) |
| 336 |
return space.newbytes(string) |
| 337 |
|
| 338 |
def copy(self, space): |
| 339 |
""" |
| 340 |
copy() -- Return a copy of the decompression object. |
| 341 |
""" |
| 342 |
try: |
| 343 |
self.lock() |
| 344 |
try: |
| 345 |
if not self.stream: |
| 346 |
raise oefmt( |
| 347 |
space.w_ValueError, |
| 348 |
"Decompressor was already flushed", |
| 349 |
) |
| 350 |
copied = rzlib.inflateCopy(self.stream) |
| 351 |
finally: |
| 352 |
self.unlock() |
| 353 |
except rzlib.RZlibError as e: |
| 354 |
raise zlib_error(space, e.msg) |
| 355 |
|
| 356 |
return Decompress( |
| 357 |
space=space, |
| 358 |
stream=copied, |
| 359 |
unused_data=self.unused_data, |
| 360 |
unconsumed_tail=self.unconsumed_tail, |
| 361 |
zdict=self.zdict, |
| 362 |
) |
| 363 |
|
| 364 |
def descr_deepcopy(self, space, w_memo): |
| 365 |
return self.copy(space) |
| 366 |
|
| 367 |
def flush(self, space, w_length=None): |
| 368 |
""" |
| 369 |
flush( [length] ) -- This is kept for backward compatibility, |
| 370 |
because each call to decompress() immediately returns as much |
| 371 |
data as possible. |
| 372 |
""" |
| 373 |
if w_length is not None: |
| 374 |
length = space.int_w(w_length) |
| 375 |
if length <= 0: |
| 376 |
raise oefmt(space.w_ValueError, |
| 377 |
"length must be greater than zero") |
| 378 |
if not self.stream: |
| 379 |
return space.newbytes('') |
| 380 |
data = self.unconsumed_tail |
| 381 |
try: |
| 382 |
self.lock() |
| 383 |
try: |
| 384 |
result = rzlib.decompress(self.stream, data, rzlib.Z_FINISH, |
| 385 |
zdict=self.zdict) |
| 386 |
finally: |
| 387 |
self.unlock() |
| 388 |
except rzlib.RZlibError: |
| 389 |
string = "" |
| 390 |
else: |
| 391 |
string, finished, unused_len = result |
| 392 |
self._save_unconsumed_input(data, finished, unused_len) |
| 393 |
if finished: |
| 394 |
rzlib.inflateEnd(self.stream) |
| 395 |
self.stream = rzlib.null_stream |
| 396 |
return space.newbytes(string) |
| 397 |
|
| 398 |
|
| 399 |
@unwrap_spec(wbits=int) |
| 400 |
def Decompress___new__(space, w_subtype, wbits=rzlib.MAX_WBITS, w_zdict=None): |
| 401 |
""" |
| 402 |
Create a new Decompress and call its initializer. |
| 403 |
""" |
| 404 |
if space.is_none(w_zdict): |
| 405 |
zdict = None |
| 406 |
else: |
| 407 |
zdict = space.charbuf_w(w_zdict) |
| 408 |
w_stream = space.allocate_instance(Decompress, w_subtype) |
| 409 |
w_stream = space.interp_w(Decompress, w_stream) |
| 410 |
try: |
| 411 |
stream = rzlib.inflateInit(wbits, zdict=zdict) |
| 412 |
except rzlib.RZlibError as e: |
| 413 |
raise zlib_error(space, e.msg) |
| 414 |
except ValueError: |
| 415 |
raise oefmt(space.w_ValueError, "Invalid initialization option") |
| 416 |
Decompress.__init__(w_stream, space, stream, zdict, '', '') |
| 417 |
return w_stream |
| 418 |
|
| 419 |
def default_buffer_size(space): |
| 420 |
return space.newint(rzlib.OUTPUT_BUFFER_SIZE) |
| 421 |
|
| 422 |
Decompress.typedef = TypeDef( |
| 423 |
'Decompress', |
| 424 |
__new__ = interp2app(Decompress___new__), |
| 425 |
copy = interp2app(Decompress.copy), |
| 426 |
__copy__ = interp2app(Decompress.copy), |
| 427 |
__deepcopy__ = interp2app(Decompress.descr_deepcopy), |
| 428 |
decompress = interp2app(Decompress.decompress), |
| 429 |
flush = interp2app(Decompress.flush), |
| 430 |
unused_data = interp_attrproperty('unused_data', Decompress, wrapfn="newbytes"), |
| 431 |
unconsumed_tail = interp_attrproperty('unconsumed_tail', Decompress, wrapfn="newbytes"), |
| 432 |
eof = interp_attrproperty('eof', Decompress, wrapfn="newbool"), |
| 433 |
__doc__ = """decompressobj([wbits]) -- Return a decompressor object. |
| 434 |
|
| 435 |
Optional arg wbits is the window buffer size. |
| 436 |
""") |