File: interp_zlib.py

package info (click to toggle)
pypy3 7.3.19%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 212,236 kB
  • sloc: python: 2,098,316; ansic: 540,565; sh: 21,462; asm: 14,419; cpp: 4,451; makefile: 4,209; objc: 761; xml: 530; exp: 499; javascript: 314; pascal: 244; lisp: 45; csh: 12; awk: 4
file content (418 lines) | stat: -rw-r--r-- 14,382 bytes parent folder | download
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
import sys
from pypy.interpreter.gateway import interp2app, unwrap_spec
from pypy.interpreter.baseobjspace import W_Root
from pypy.interpreter.typedef import TypeDef, interp_attrproperty
from pypy.interpreter.error import OperationError, oefmt
from rpython.rlib.rarithmetic import intmask, r_uint, r_uint32
from rpython.rlib.objectmodel import keepalive_until_here

from rpython.rlib import rzlib


@unwrap_spec(string='bufferstr', start='truncatedint_w')
def crc32(space, string, start = rzlib.CRC32_DEFAULT_START):
    """
    crc32(string[, start]) -- Compute a CRC-32 checksum of string.

    An optional starting value can be specified.  The returned checksum is
    an integer.
    """
    ustart = r_uint(r_uint32(start))
    checksum = rzlib.crc32(string, ustart)
    return space.newint(checksum)


@unwrap_spec(string='bufferstr', start='truncatedint_w')
def adler32(space, string, start=rzlib.ADLER32_DEFAULT_START):
    """
    adler32(string[, start]) -- Compute an Adler-32 checksum of string.

    An optional starting value can be specified.  The returned checksum is
    an integer.
    """
    ustart = r_uint(r_uint32(start))
    checksum = rzlib.adler32(string, ustart)
    return space.newint(checksum)


class Cache:
    def __init__(self, space):
        self.w_error = space.new_exception_class("zlib.error")

def zlib_error(space, msg):
    w_error = space.fromcache(Cache).w_error
    return OperationError(w_error, space.newtext(msg))


@unwrap_spec(data='bufferstr', level=int, wbits=int)
def compress(space, data, __posonly__=None, level=rzlib.Z_DEFAULT_COMPRESSION, wbits=rzlib.MAX_WBITS):
    """
    Returns a bytes object containing compressed data.

    data
      Binary data to be compressed.
    level
      Compression level, in 0-9 or -1.
    wbits
      The window buffer size and container format.
    """
    try:
        try:
            stream = rzlib.deflateInit(level=level, wbits=wbits)
        except ValueError:
            raise zlib_error(space, "Bad compression level")
        try:
            result = rzlib.compress(stream, data, rzlib.Z_FINISH)
        finally:
            rzlib.deflateEnd(stream)
    except rzlib.RZlibError as e:
        raise zlib_error(space, e.msg)
    return space.newbytes(result)


@unwrap_spec(string='bufferstr', wbits="c_int", bufsize=int)
def decompress(space, string, __posonly__=None, wbits=rzlib.MAX_WBITS, bufsize=0):
    """
    decompress(string[, wbits[, bufsize]]) -- Return decompressed string.

    Optional arg wbits is the window buffer size.  Optional arg bufsize is
    only for compatibility with CPython and is ignored.
    """
    try:
        try:
            stream = rzlib.inflateInit(wbits)
        except ValueError:
            raise zlib_error(space, "Bad window buffer size")
        try:
            result, _, _ = rzlib.decompress(stream, string, rzlib.Z_FINISH)
        finally:
            rzlib.inflateEnd(stream)
    except rzlib.RZlibError as e:
        raise zlib_error(space, e.msg)
    return space.newbytes(result)


class ZLibObject(W_Root):
    """
    Common base class for Compress and Decompress.
    """
    stream = rzlib.null_stream

    def __init__(self, space):
        self._lock = space.allocate_lock()

    def lock(self):
        """To call before using self.stream."""
        self._lock.acquire(True)

    def unlock(self):
        """To call after using self.stream."""
        self._lock.release()
        keepalive_until_here(self)
        # subtle: we have to make sure that 'self' is not garbage-collected
        # while we are still using 'self.stream' - hence the keepalive.


class Compress(ZLibObject):
    """
    Wrapper around zlib's z_stream structure which provides convenient
    compression functionality.
    """
    def __init__(self, space, stream):
        ZLibObject.__init__(self, space)
        self.stream = stream
        self.register_finalizer(space)

    def _finalize_(self):
        """Automatically free the resources used by the stream."""
        if self.stream:
            rzlib.deflateEnd(self.stream)
            self.stream = rzlib.null_stream

    @unwrap_spec(data='bufferstr')
    def compress(self, space, data, __posonly__=None):
        """
        compress(data) -- Return a string containing data compressed.

        After calling this function, some of the input data may still be stored
        in internal buffers for later processing.

        Call the flush() method to clear these buffers.
        """
        try:
            self.lock()
            try:
                if not self.stream:
                    raise zlib_error(space,
                                     "compressor object already flushed")
                result = rzlib.compress(self.stream, data)
            finally:
                self.unlock()
        except rzlib.RZlibError as e:
            raise zlib_error(space, e.msg)
        return space.newbytes(result)

    def copy(self, space):
        """
        copy() -- Return a copy of the compression object.
        """
        try:
            self.lock()
            try:
                if not self.stream:
                    raise oefmt(
                        space.w_ValueError,
                        "Compressor was already flushed",
                    )
                copied = rzlib.deflateCopy(self.stream)
            finally:
                self.unlock()
        except rzlib.RZlibError as e:
            raise zlib_error(space, e.msg)
        return Compress(space=space, stream=copied)

    def descr_deepcopy(self, space, w_memo):
        return self.copy(space)


    @unwrap_spec(mode="c_int")
    def flush(self, space, mode=rzlib.Z_FINISH):
        """
        flush( [mode] ) -- Return a string containing any remaining compressed
        data.

        mode can be one of the constants Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH;
        the default value used when mode is not specified is Z_FINISH.

        If mode == Z_FINISH, the compressor object can no longer be used after
        calling the flush() method.  Otherwise, more data can still be
        compressed.
        """
        try:
            self.lock()
            try:
                if not self.stream:
                    raise zlib_error(space,
                                     "compressor object already flushed")
                result = rzlib.compress(self.stream, '', mode)
                if mode == rzlib.Z_FINISH:    # release the data structures now
                    rzlib.deflateEnd(self.stream)
                    self.stream = rzlib.null_stream
                    self.may_unregister_rpython_finalizer(space)
            finally:
                self.unlock()
        except rzlib.RZlibError as e:
            raise zlib_error(space, e.msg)
        return space.newbytes(result)


@unwrap_spec(level=int, method=int, wbits=int, memLevel=int, strategy=int)
def Compress___new__(space, w_subtype, level=rzlib.Z_DEFAULT_COMPRESSION,
                     method=rzlib.Z_DEFLATED,             # \
                     wbits=rzlib.MAX_WBITS,               #  \   undocumented
                     memLevel=rzlib.DEF_MEM_LEVEL,        #  /    parameters
                     strategy=rzlib.Z_DEFAULT_STRATEGY,   # /
                     w_zdict=None):
    """
    Create a new z_stream and call its initializer.
    """
    if space.is_none(w_zdict):
        zdict = None
    else:
        zdict = space.charbuf_w(w_zdict)
    w_stream = space.allocate_instance(Compress, w_subtype)
    w_stream = space.interp_w(Compress, w_stream)
    try:
        stream = rzlib.deflateInit(level, method, wbits, memLevel, strategy,
                                   zdict=zdict)
    except rzlib.RZlibError as e:
        raise zlib_error(space, e.msg)
    except ValueError:
        raise oefmt(space.w_ValueError, "Invalid initialization option")
    Compress.__init__(w_stream, space, stream)
    return w_stream


Compress.typedef = TypeDef(
    'Compress',
    __new__ = interp2app(Compress___new__),
    copy = interp2app(Compress.copy),
    __copy__ = interp2app(Compress.copy),
    __deepcopy__ = interp2app(Compress.descr_deepcopy),
    compress = interp2app(Compress.compress),
    flush = interp2app(Compress.flush),
    __doc__ = """compressobj([level]) -- Return a compressor object.

Optional arg level is the compression level, in 1-9.
""")


class Decompress(ZLibObject):
    """
    Wrapper around zlib's z_stream structure which provides convenient
    decompression functionality.
    """
    def __init__(self, space, stream, zdict, unused_data, unconsumed_tail):
        """
        Initialize a new decompression object.

        wbits is an integer between 8 and MAX_WBITS or -8 and -MAX_WBITS
        (inclusive) giving the number of "window bits" to use for compression
        and decompression.  See the documentation for deflateInit2 and
        inflateInit2.
        """
        ZLibObject.__init__(self, space)

        self.stream = stream
        self.zdict = zdict
        self.unused_data = unused_data
        self.unconsumed_tail = unconsumed_tail
        self.eof = False
        self.register_finalizer(space)

    def _finalize_(self):
        """Automatically free the resources used by the stream."""
        if self.stream:
            rzlib.inflateEnd(self.stream)
            self.stream = rzlib.null_stream

    def _save_unconsumed_input(self, data, finished, unused_len):
        unused_start = len(data) - unused_len
        assert unused_start >= 0
        tail = data[unused_start:]
        if finished:
            self.unconsumed_tail = ''
            self.unused_data += tail
        else:
            self.unconsumed_tail = tail

    @unwrap_spec(data='bufferstr', max_length=int)
    def decompress(self, space, data, __posonly__=None, max_length=0):
        """
        decompress(data[, max_length]) -- Return a string containing the
        decompressed version of the data.

        If the max_length parameter is specified then the return value will be
        no longer than max_length.  Unconsumed input data will be stored in the
        unconsumed_tail attribute.
        """
        if max_length == 0:
            max_length = sys.maxint
        elif max_length < 0:
            raise oefmt(space.w_ValueError,
                        "max_length must be greater than zero")
        try:
            self.lock()
            try:
                result = rzlib.decompress(self.stream, data,
                                          max_length=max_length,
                                          zdict=self.zdict)
            finally:
                self.unlock()
        except rzlib.RZlibError as e:
            raise zlib_error(space, e.msg)

        string, finished, unused_len = result
        self.eof = finished
        self._save_unconsumed_input(data, finished, unused_len)
        return space.newbytes(string)

    def copy(self, space):
        """
        copy() -- Return a copy of the decompression object.
        """
        try:
            self.lock()
            try:
                if not self.stream:
                    raise oefmt(
                        space.w_ValueError,
                        "Decompressor was already flushed",
                    )
                copied = rzlib.inflateCopy(self.stream)
            finally:
                self.unlock()
        except rzlib.RZlibError as e:
            raise zlib_error(space, e.msg)

        return Decompress(
            space=space,
            stream=copied,
            unused_data=self.unused_data,
            unconsumed_tail=self.unconsumed_tail,
            zdict=self.zdict,
        )

    def descr_deepcopy(self, space, w_memo):
        return self.copy(space)

    def flush(self, space, w_length=None):
        """
        flush( [length] ) -- This is kept for backward compatibility,
        because each call to decompress() immediately returns as much
        data as possible.
        """
        if w_length is not None:
            length = space.int_w(w_length)
            if length <= 0:
                raise oefmt(space.w_ValueError,
                            "length must be greater than zero")
        if not self.stream:
            return space.newbytes('')
        data = self.unconsumed_tail
        try:
            self.lock()
            try:
                result = rzlib.decompress(self.stream, data, rzlib.Z_FINISH,
                                          zdict=self.zdict)
            finally:
                self.unlock()
        except rzlib.RZlibError:
            string = ""
        else:
            string, finished, unused_len = result
            self._save_unconsumed_input(data, finished, unused_len)
            if finished:
                rzlib.inflateEnd(self.stream)
                self.stream = rzlib.null_stream
        return space.newbytes(string)


@unwrap_spec(wbits=int)
def Decompress___new__(space, w_subtype, wbits=rzlib.MAX_WBITS, w_zdict=None):
    """
    Create a new Decompress and call its initializer.
    """
    if space.is_none(w_zdict):
        zdict = None
    else:
        zdict = space.charbuf_w(w_zdict)
    w_stream = space.allocate_instance(Decompress, w_subtype)
    w_stream = space.interp_w(Decompress, w_stream)
    try:
        stream = rzlib.inflateInit(wbits, zdict=zdict)
    except rzlib.RZlibError as e:
        raise zlib_error(space, e.msg)
    except ValueError:
        raise oefmt(space.w_ValueError, "Invalid initialization option")
    Decompress.__init__(w_stream, space, stream, zdict, '', '')
    return w_stream

def default_buffer_size(space):
    return space.newint(rzlib.OUTPUT_BUFFER_SIZE)

Decompress.typedef = TypeDef(
    'Decompress',
    __new__ = interp2app(Decompress___new__),
    copy = interp2app(Decompress.copy),
    __copy__ = interp2app(Decompress.copy),
    __deepcopy__ = interp2app(Decompress.descr_deepcopy),
    decompress = interp2app(Decompress.decompress),
    flush = interp2app(Decompress.flush),
    unused_data = interp_attrproperty('unused_data', Decompress, wrapfn="newbytes"),
    unconsumed_tail = interp_attrproperty('unconsumed_tail', Decompress, wrapfn="newbytes"),
    eof = interp_attrproperty('eof', Decompress, wrapfn="newbool"),
    __doc__ = """decompressobj([wbits]) -- Return a decompressor object.

Optional arg wbits is the window buffer size.
""")