Debian Codegraph @

lib_pypy/_lzma.py

raw symbols SCIP
1 # This file is based on lzmaffi/_lzmamodule2.py from lzmaffi version 0.3.0.
2 # The original license is
3 # Copyright (c) 2010-2011, Per Øyvind Karlsen.
4 # Copyright (c) 2011-2012, Nadeem Vawda.
5 # Copyright (c) 2012-2013, Peter J. A. Cock.
6 # Copyright (c) 2013-2014, Tomer Chachamu.
7 # All rights reserved.
8 #
9 # Redistribution and use in source and binary forms, with or without
10 # modification, are permitted provided that the following conditions are met:
11 #
12 # Redistributions of source code must retain the above copyright notice, this
13 # list of conditions and the following disclaimer.
14 #
15 # Redistributions in binary form must reproduce the above copyright notice, this
16 # list of conditions and the following disclaimer in the documentation and/or
17 # other materials provided with the distribution.
18 #
19 # Neither the name of the copyright holders nor the names of its contributors
20 # may be used to endorse or promote products derived from this software without
21 # specific prior written permission.
22
23 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
24 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
27 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
33 # THE POSSIBILITY OF SUCH DAMAGE.
34 #
35 # PyPy changes:
36 # - added __getstate__() methods that raise TypeError on pickling.
37 # - ported to CFFI 1.0
38 # These and subsequent changes are licensed by the PyPy Copyright holders, following
39 # the LICENSE file in the top-level directory
40
41 import threading
42 import functools
43 import collections.abc
44 import weakref
45 import sys
46 import io
47 import __pypy__
48
49 from _lzma_cffi import ffi, lib as m
50
51 SUPPORTED_STREAM_FLAGS_VERSION = 0
52
53 __all__ = ['CHECK_CRC32',
54 'CHECK_CRC64',
55 'CHECK_ID_MAX',
56 'CHECK_NONE',
57 'CHECK_SHA256',
58 'CHECK_UNKNOWN',
59 'FILTER_ARM',
60 'FILTER_ARMTHUMB',
61 'FILTER_DELTA',
62 'FILTER_IA64',
63 'FILTER_LZMA1',
64 'FILTER_LZMA2',
65 'FILTER_POWERPC',
66 'FILTER_SPARC',
67 'FILTER_X86',
68 'FORMAT_ALONE',
69 'FORMAT_AUTO',
70 'FORMAT_RAW',
71 'FORMAT_XZ',
72 'FORMAT_BLOCK',
73 'LZMACompressor',
74 'LZMADecompressor',
75 'LZMAError',
76 'MF_BT2',
77 'MF_BT3',
78 'MF_BT4',
79 'MF_HC3',
80 'MF_HC4',
81 'MODE_FAST',
82 'MODE_NORMAL',
83 'PRESET_DEFAULT',
84 'PRESET_EXTREME',
85 'STREAM_HEADER_SIZE',
86 'decode_block_header_size',
87 'decode_stream_header',
88 'decode_stream_footer',
89 'decode_index',
90 '_decode_filter_properties',
91 '_encode_filter_properties',
92 'is_check_supported']
93
94 _owns = weakref.WeakKeyDictionary()
95
96 def _new_lzma_stream():
97 ret = ffi.new('lzma_stream*')
98 m._pylzma_stream_init(ret)
99 return ffi.gc(ret, m.lzma_end)
100
101 def _release_lzma_stream(st):
102 ffi.gc(st, None)
103 m.lzma_end(st)
104
105 def add_constant(c):
106 globals()[c] = getattr(m, 'LZMA_' + c)
107
108 if sys.version_info >= (2,7):
109 def to_bytes(data):
110 return memoryview(data).tobytes()
111 else:
112 def to_bytes(data):
113 if not isinstance(data, basestring):
114 raise TypeError("lzma: must be str/unicode, got %s" % (type(data),))
115 return bytes(data)
116
117 if sys.version_info >= (3,0):
118 long = int
119
120 for c in ['CHECK_CRC32', 'CHECK_CRC64', 'CHECK_ID_MAX', 'CHECK_NONE', 'CHECK_SHA256', 'FILTER_ARM', 'FILTER_ARMTHUMB', 'FILTER_DELTA', 'FILTER_IA64', 'FILTER_LZMA1', 'FILTER_LZMA2', 'FILTER_POWERPC', 'FILTER_SPARC', 'FILTER_X86', 'MF_BT2', 'MF_BT3', 'MF_BT4', 'MF_HC3', 'MF_HC4', 'MODE_FAST', 'MODE_NORMAL', 'PRESET_DEFAULT', 'PRESET_EXTREME', 'STREAM_HEADER_SIZE']:
121 add_constant(c)
122
123 def _parse_format(format):
124 if isinstance(format, (int, long)):
125 return format
126 else:
127 raise TypeError
128
129 CHECK_UNKNOWN = CHECK_ID_MAX + 1
130 FORMAT_AUTO, FORMAT_XZ, FORMAT_ALONE, FORMAT_RAW, FORMAT_BLOCK = range(5)
131
132 BCJ_FILTERS = (m.LZMA_FILTER_X86,
133 m.LZMA_FILTER_POWERPC,
134 m.LZMA_FILTER_IA64,
135 m.LZMA_FILTER_ARM,
136 m.LZMA_FILTER_ARMTHUMB,
137 m.LZMA_FILTER_SPARC)
138
139 class LZMAError(Exception):
140 """Call to liblzma failed."""
141
142 def is_check_supported(check):
143 """is_check_supported(check_id) -> bool
144
145 Test whether the given integrity check is supported.
146
147 Always returns True for CHECK_NONE and CHECK_CRC32."""
148 return bool(m.lzma_check_is_supported(check))
149
150 def catch_lzma_error(fun, *args, ignore_buf_error=False):
151 try:
152 lzret = fun(*args)
153 except:
154 raise
155 if lzret in (m.LZMA_OK, m.LZMA_GET_CHECK, m.LZMA_NO_CHECK, m.LZMA_STREAM_END):
156 return lzret
157 elif lzret == m.LZMA_DATA_ERROR:
158 raise LZMAError("Corrupt input data")
159 elif lzret == m.LZMA_UNSUPPORTED_CHECK:
160 raise LZMAError("Unsupported integrity check")
161 elif lzret == m.LZMA_FORMAT_ERROR:
162 raise LZMAError("Input format not supported by decoder")
163 elif lzret == m.LZMA_OPTIONS_ERROR:
164 raise LZMAError("Invalid or unsupported options")
165 elif lzret == m.LZMA_BUF_ERROR:
166 if ignore_buf_error:
167 return m.LZMA_OK
168 raise LZMAError("Insufficient buffer space")
169 elif lzret == m.LZMA_PROG_ERROR:
170 raise LZMAError("Internal error")
171 elif lzret == m.LZMA_MEM_ERROR:
172 raise MemoryError
173 else:
174 raise LZMAError("Unrecognised error from liblzma: %d" % lzret)
175
176 def parse_filter_spec_delta(id, dist=1):
177 ret = ffi.new('lzma_options_delta*')
178 ret.type = m.LZMA_DELTA_TYPE_BYTE
179 ret.dist = dist
180 return ret
181
182 def parse_filter_spec_bcj(id, start_offset=0):
183 ret = ffi.new('lzma_options_bcj*')
184 ret.start_offset = start_offset
185 return ret
186
187 def parse_filter_spec_lzma(id, preset=m.LZMA_PRESET_DEFAULT, **kwargs):
188 ret = ffi.new('lzma_options_lzma*')
189 if m.lzma_lzma_preset(ret, preset):
190 raise LZMAError("Invalid compression preset: %s" % preset)
191 for arg, val in kwargs.items():
192 if arg in ('dict_size', 'lc', 'lp', 'pb', 'nice_len', 'depth'):
193 setattr(ret, arg, val)
194 elif arg in ('mf', 'mode'):
195 setattr(ret, arg, int(val))
196 else:
197 raise ValueError("Invalid filter specifier for LZMA filter")
198 return ret
199
200 def parse_filter_spec(spec):
201 if not isinstance(spec, collections.abc.Mapping):
202 raise TypeError("Filter specifier must be a dict or dict-like object")
203 ret = ffi.new('lzma_filter*')
204 try:
205 ret.id = spec['id']
206 except KeyError:
207 raise ValueError("Filter specifier must have an \"id\" entry")
208 if ret.id in (m.LZMA_FILTER_LZMA1, m.LZMA_FILTER_LZMA2):
209 try:
210 options = parse_filter_spec_lzma(**spec)
211 except TypeError:
212 raise ValueError("Invalid filter specifier for LZMA filter")
213 elif ret.id == m.LZMA_FILTER_DELTA:
214 try:
215 options = parse_filter_spec_delta(**spec)
216 except TypeError:
217 raise ValueError("Invalid filter specifier for delta filter")
218 elif ret.id in BCJ_FILTERS:
219 try:
220 options = parse_filter_spec_bcj(**spec)
221 except TypeError:
222 raise ValueError("Invalid filter specifier for BCJ filter")
223 else:
224 raise ValueError("Invalid %d" % (ret.id,))
225
226 ret.options = options
227 _owns[ret] = options
228 return ret
229
230 def _encode_filter_properties(filterspec):
231 """_encode_filter_properties(filter) -> bytes
232
233 Return a bytes object encoding the options (properties) of the filter
234 specified by *filter* (a dict).
235
236 The result does not include the filter ID itself, only the options."""
237 filter = parse_filter_spec(filterspec)
238 size = ffi.new("uint32_t*")
239 catch_lzma_error(m.lzma_properties_size, size, filter)
240 result = ffi.new('uint8_t[]', size[0])
241 catch_lzma_error(m.lzma_properties_encode, filter, result)
242 return ffi.buffer(result)[:]
243
244 def parse_filter_chain_spec(filterspecs):
245 if len(filterspecs) > m.LZMA_FILTERS_MAX:
246 raise ValueError(
247 "Too many filters - liblzma supports a maximum of %s" %
248 m.LZMA_FILTERS_MAX)
249 filters = ffi.new('lzma_filter[]', m.LZMA_FILTERS_MAX+1)
250 _owns[filters] = children = []
251 for i in range(m.LZMA_FILTERS_MAX+1):
252 try:
253 filterspec = filterspecs[i]
254 except KeyError:
255 raise TypeError
256 except IndexError:
257 filters[i].id = m.LZMA_VLI_UNKNOWN
258 else:
259 filter = parse_filter_spec(filterspecs[i])
260 children.append(filter)
261 filters[i].id = filter.id
262 filters[i].options = filter.options
263 return filters
264
265 def build_filter_spec(lzma_filter):
266 spec = {'id': lzma_filter.id}
267 def add_opts(options_type, *opts):
268 options = ffi.cast('%s*' % (options_type,), lzma_filter.options)
269 if options:
270 for v in opts:
271 spec[v] = getattr(options, v)
272 if lzma_filter.id == m.LZMA_FILTER_LZMA1:
273 add_opts('lzma_options_lzma', 'lc', 'lp', 'pb', 'dict_size')
274 elif lzma_filter.id == m.LZMA_FILTER_LZMA2:
275 add_opts('lzma_options_lzma', 'dict_size')
276 elif lzma_filter.id == m.LZMA_FILTER_DELTA:
277 add_opts('lzma_options_delta', 'dist')
278 elif lzma_filter.id in BCJ_FILTERS:
279 add_opts('lzma_options_bcj', 'start_offset')
280 else:
281 raise ValueError("Invalid filter ID: %s" % lzma_filter.id)
282 return spec
283
284 def _decode_filter_properties(filter_id, encoded_props):
285 """_decode_filter_properties(filter_id, encoded_props) -> dict
286
287 Return a dict describing a filter with ID *filter_id*, and options
288 (properties) decoded from the bytes object *encoded_props*."""
289 lzma_filter = ffi.new('lzma_filter*')
290 lzma_filter.id = filter_id
291 catch_lzma_error(m.lzma_properties_decode,
292 lzma_filter, ffi.NULL, encoded_props, len(encoded_props))
293 try:
294 return build_filter_spec(lzma_filter)
295 finally:
296 # TODO do we need this, the only use of m.free?
297 m.free(lzma_filter.options)
298
299 def _decode_stream_header_or_footer(decode_f, in_bytes):
300 footer_o = ffi.new('char[]', to_bytes(in_bytes))
301 stream_flags = ffi.new('lzma_stream_flags*')
302 catch_lzma_error(decode_f, stream_flags, footer_o)
303 return StreamFlags(stream_flags)
304
305 decode_stream_footer = functools.partial(_decode_stream_header_or_footer,
306 m.lzma_stream_footer_decode)
307
308 decode_stream_header = functools.partial(_decode_stream_header_or_footer,
309 m.lzma_stream_header_decode)
310
311 def decode_block_header_size(in_byte):
312 # lzma_block_header_size_decode(b) (((uint32_t)(b) + 1) * 4)
313 return (ord(in_byte) + 1) * 4
314
315 def decode_index(s, stream_padding=0):
316 indexp = ffi.new('lzma_index**')
317 memlimit = ffi.new('uint64_t*')
318 memlimit[0] = m.UINT64_MAX
319 allocator = ffi.NULL
320 in_buf = ffi.new('char[]', to_bytes(s))
321 in_pos = ffi.new('size_t*')
322 in_pos[0] = 0
323 catch_lzma_error(m.lzma_index_buffer_decode, indexp,
324 memlimit, allocator, in_buf, in_pos, len(s))
325 return Index(indexp[0], allocator, stream_padding)
326
327 class Index(object):
328 def __init__(self, i, allocator, stream_padding=0):
329 self.i = i
330 self.allocator = allocator
331 m.lzma_index_stream_padding(i, stream_padding)
332
333 @property
334 def uncompressed_size(self):
335 return m.lzma_index_uncompressed_size(self.i)
336
337 @property
338 def block_count(self):
339 return m.lzma_index_block_count(self.i)
340
341 @property
342 def index_size(self):
343 return m.lzma_index_size(self.i)
344
345 @property
346 def blocks_size(self):
347 return m.lzma_index_total_size(self.i)
348
349 def __iter__(self):
350 return self.iterator()
351
352 def iterator(self, type=m.LZMA_INDEX_ITER_BLOCK):
353 iterator = ffi.new('lzma_index_iter*')
354 m.lzma_index_iter_init(iterator, self.i)
355 while not m.lzma_index_iter_next(iterator, type):
356 yield (IndexStreamData(iterator.stream), IndexBlockData(iterator.block))
357
358 def find(self, offset):
359 iterator = ffi.new('lzma_index_iter*')
360 m.lzma_index_iter_init(iterator, self.i)
361 if m.lzma_index_iter_locate(iterator, offset):
362 # offset too high
363 return None
364 return (IndexStreamData(iterator.stream), IndexBlockData(iterator.block))
365
366 def __del__(self):
367 m.lzma_index_end(self.i, self.allocator)
368
369 def copy(self):
370 new_i = m.lzma_index_dup(self.i, self.allocator)
371 return Index(new_i, self.allocator)
372
373 deepcopy = copy
374
375 def append(self, other_index):
376 # m.lzma_index_cat frees its second parameter so we
377 # must copy it first
378 other_index_i = m.lzma_index_dup(other_index.i, self.allocator)
379 catch_lzma_error(m.lzma_index_cat, self.i,
380 other_index_i, self.allocator)
381
382 class _StructToPy(object):
383 __slots__ = ()
384 def __init__(self, struct_obj):
385 # TODO make PyPy-fast
386 for attr in self.__slots__:
387 setattr(self, attr, getattr(struct_obj, attr))
388 def __repr__(self):
389 descriptions = ('%s=%r' % (attr, getattr(self, attr)) for attr in self.__slots__)
390 return "<%s %s>" % (type(self).__name__, ' '.join(descriptions))
391
392 class IndexStreamData(_StructToPy):
393 __slots__ = ('number', 'block_count', 'compressed_offset', 'uncompressed_offset',
394 'compressed_size', 'uncompressed_size')
395
396 class IndexBlockData(_StructToPy):
397 __slots__ = ('number_in_file', 'compressed_file_offset', 'uncompressed_file_offset',
398 'compressed_stream_offset', 'uncompressed_stream_offset',
399 'uncompressed_size', 'unpadded_size', 'total_size')
400
401 class StreamFlags(object):
402 def __init__(self, i):
403 self.i = i
404
405 version = property(lambda self: self.i.version)
406 check = property(lambda self: self.i.check)
407 backward_size = property(lambda self: self.i.backward_size)
408
409 @property
410 def supported(self):
411 return self.version > SUPPORTED_STREAM_FLAGS_VERSION
412
413 def check_supported(self):
414 if not self.supported:
415 raise LZMAError("Stream is too new for liblzma version")
416
417 def matches(self, other):
418 return m.lzma_stream_flags_compare(self.i, other.i) == m.LZMA_OK
419
420 def copy(self):
421 other_i = ffi.new('lzma_stream_flags*', self.i)
422 return StreamFlags(other_i)
423
424 class Allocator(object):
425 def __init__(self):
426 self.owns = {}
427 self.lzma_allocator = ffi.new('lzma_allocator*')
428 alloc = self.owns['a'] = ffi.callback("void*(void*, size_t, size_t)", self.__alloc)
429 free = self.owns['b'] = ffi.callback("void(void*, void*)", self.__free)
430 self.lzma_allocator.alloc = alloc
431 self.lzma_allocator.free = free
432 self.lzma_allocator.opaque = ffi.NULL
433 def __alloc(self, _opaque, _nmemb, size):
434 new_mem = ffi.new('char[]', size)
435 self.owns[self._addr(new_mem)] = new_mem
436 return new_mem
437 def _addr(self, ptr):
438 return long(ffi.cast('uintptr_t', ptr))
439 def __free(self, _opaque, ptr):
440 if self._addr(ptr) == 0: return
441 del self.owns[self._addr(ptr)]
442
443 class LZMADecompressor(object):
444 """
445 LZMADecompressor(format=FORMAT_AUTO, memlimit=None, filters=None)
446
447 Create a decompressor object for decompressing data incrementally.
448
449 format specifies the container format of the input stream. If this is
450 FORMAT_AUTO (the default), the decompressor will automatically detect
451 whether the input is FORMAT_XZ or FORMAT_ALONE. Streams created with
452 FORMAT_RAW cannot be autodetected.
453
454 memlimit can be specified to limit the amount of memory used by the
455 decompressor. This will cause decompression to fail if the input
456 cannot be decompressed within the given limit.
457
458 filters specifies a custom filter chain. This argument is required for
459 FORMAT_RAW, and not accepted with any other format. When provided,
460 this should be a sequence of dicts, each indicating the ID and options
461 for a single filter.
462
463 For one-shot decompression, use the decompress() function instead.
464 """
465 def __init__(self, format=FORMAT_AUTO, memlimit=None, filters=None,
466 header=None, check=None, unpadded_size=None):
467 decoder_flags = m.LZMA_TELL_ANY_CHECK | m.LZMA_TELL_NO_CHECK
468 if memlimit is not None:
469 if format == FORMAT_RAW:
470 raise ValueError("Cannot specify memory limit with FORMAT_RAW")
471 else:
472 memlimit = m.UINT64_MAX
473
474 if format == FORMAT_RAW and filters is None:
475 raise ValueError("Must specify filters for FORMAT_RAW")
476 elif format != FORMAT_RAW and filters is not None:
477 raise ValueError("Cannot specify filters except with FORMAT_RAW")
478
479 if format == FORMAT_BLOCK and (header is None or unpadded_size is None or check is None):
480 raise ValueError("Must specify header, unpadded_size and check "
481 "with FORMAT_BLOCK")
482 elif format != FORMAT_BLOCK and (header is not None or unpadded_size is not None or check is not None):
483 raise ValueError("Cannot specify header, unpadded_size or check "
484 "except with FORMAT_BLOCK")
485
486 format = _parse_format(format)
487 self.lock = threading.Lock()
488 self.check = CHECK_UNKNOWN
489 self.unused_data = b''
490 self.eof = False
491 self.lzs = _new_lzma_stream()
492 self._bufsiz = max(8192, io.DEFAULT_BUFFER_SIZE)
493 self.needs_input = True
494 self._input_buffer = ffi.NULL
495 self._input_buffer_size = 0
496
497 if format == FORMAT_AUTO:
498 catch_lzma_error(m.lzma_auto_decoder, self.lzs, memlimit, decoder_flags)
499 elif format == FORMAT_XZ:
500 catch_lzma_error(m.lzma_stream_decoder, self.lzs, memlimit, decoder_flags)
501 elif format == FORMAT_ALONE:
502 self.check = CHECK_NONE
503 catch_lzma_error(m.lzma_alone_decoder, self.lzs, memlimit)
504 elif format == FORMAT_RAW:
505 self.check = CHECK_NONE
506 filters = parse_filter_chain_spec(filters)
507 catch_lzma_error(m.lzma_raw_decoder, self.lzs,
508 filters)
509 elif format == FORMAT_BLOCK:
510 self.__block = block = ffi.new('lzma_block*')
511 block.version = 0
512 block.check = check
513 block.header_size = len(header)
514 block.filters = self.__filters = ffi.new('lzma_filter[]', m.LZMA_FILTERS_MAX+1)
515 header_b = ffi.new('char[]', to_bytes(header))
516 catch_lzma_error(m.lzma_block_header_decode, block, self.lzs.allocator, header_b)
517 if unpadded_size is not None:
518 catch_lzma_error(m.lzma_block_compressed_size, block, unpadded_size)
519 self.expected_size = block.compressed_size
520 catch_lzma_error(m.lzma_block_decoder, self.lzs, block)
521 else:
522 raise ValueError("invalid container format: %s" % format)
523
524 def pre_decompress_left_data(self, buf, buf_size):
525 # in this case there is data left that needs to be processed before the first
526 # argument can be processed
527
528 lzs = self.lzs
529
530 addr_input_buffer = int(ffi.cast('uintptr_t', self._input_buffer))
531 addr_next_in = int(ffi.cast('uintptr_t', lzs.next_in))
532 avail_now = (addr_input_buffer + self._input_buffer_size) - \
533 (addr_next_in + lzs.avail_in)
534 avail_total = self._input_buffer_size - lzs.avail_in
535 if avail_total < buf_size:
536 # resize the buffer, it is too small!
537 offset = addr_next_in - addr_input_buffer
538 new_size = self._input_buffer_size + buf_size - avail_now
539 # there is no realloc?
540 tmp = ffi.cast("uint8_t*",m.malloc(new_size))
541 if tmp == ffi.NULL:
542 raise MemoryError
543 ffi.memmove(tmp, lzs.next_in, lzs.avail_in)
544 lzs.next_in = tmp
545 m.free(self._input_buffer)
546 self._input_buffer = tmp
547 self._input_buffer_size = new_size
548 elif avail_now < buf_size:
549 # the buffer is not too small, but we cannot append it!
550 # move all data to the front
551 ffi.memmove(self._input_buffer, lzs.next_in, lzs.avail_in)
552 lzs.next_in = self._input_buffer
553 ffi.memmove(lzs.next_in+lzs.avail_in, buf, buf_size)
554 lzs.avail_in += buf_size
555 return lzs.next_in, lzs.avail_in
556
557 def post_decompress_avail_data(self):
558 lzs = self.lzs
559 # free buffer it is to small
560 if self._input_buffer is not ffi.NULL and \
561 self._input_buffer_size < lzs.avail_in:
562 m.free(self._input_buffer)
563 self._input_buffer = ffi.NONE
564
565 # allocate if necessary
566 if self._input_buffer is ffi.NULL:
567 self._input_buffer = ffi.cast("uint8_t*",m.malloc(lzs.avail_in))
568 if self._input_buffer == ffi.NULL:
569 raise MemoryError
570 self._input_buffer_size = lzs.avail_in
571
572 ffi.memmove(self._input_buffer, lzs.next_in, lzs.avail_in)
573 lzs.next_in = self._input_buffer
574
575 def clear_input_buffer(self):
576 # clean the buffer
577 if self._input_buffer is not ffi.NULL:
578 m.free(self._input_buffer)
579 self._input_buffer = ffi.NULL
580 self._input_buffer_size = 0
581
582 def decompress(self, data, max_length=-1):
583 """
584 decompress(data, max_length=-1) -> bytes
585
586 Provide data to the decompressor object. Returns a chunk of
587 decompressed data if possible, or b"" otherwise.
588
589 Attempting to decompress data after the end of the stream is
590 reached raises an EOFError. Any data found after the end of the
591 stream is ignored, and saved in the unused_data attribute.
592 """
593 if not isinstance(max_length, int):
594 raise TypeError("max_length parameter object cannot be interpreted as an integer")
595 with self.lock:
596 if self.eof:
597 raise EOFError("Already at end of stream")
598 lzs = self.lzs
599 data = to_bytes(data)
600 buf = ffi.new('uint8_t[]', data)
601 buf_size = len(data)
602
603 if lzs.next_in:
604 buf, buf_size = self.pre_decompress_left_data(buf, buf_size)
605 used__input_buffer = True
606 else:
607 lzs.avail_in = buf_size
608 lzs.next_in = ffi.cast("uint8_t*",buf)
609 used__input_buffer = False
610
611 # actual decompression
612 result = self._decompress(buf, buf_size, max_length)
613
614 if self.eof:
615 self.needs_input = False
616 if lzs.avail_in > 0:
617 self.unused_data = ffi.buffer(lzs.next_in, lzs.avail_in)[:]
618 self.clear_input_buffer()
619 elif lzs.avail_in == 0:
620 # completed successfully!
621 lzs.next_in = ffi.NULL
622 if lzs.avail_out == 0:
623 # (avail_in==0 && avail_out==0)
624 # Maybe lzs's internal state still have a few bytes can
625 # be output, try to output them next time.
626 self.needs_input = False
627 assert max_length >= 0 # if < 0, lzs.avail_out always > 0
628 else:
629 # Input buffer exhausted, output buffer has space.
630 self.needs_input = True
631 self.clear_input_buffer()
632 else:
633 self.needs_input = False
634 if not used__input_buffer:
635 self.post_decompress_avail_data()
636
637 return result
638
639 def _decompress(self, buf, buf_len, max_length):
640 lzs = self.lzs
641
642 lzs.next_in = buf
643 lzs.avail_in = buf_len
644
645 bufsiz = self._bufsiz
646 if not (max_length < 0 or max_length > io.DEFAULT_BUFFER_SIZE):
647 bufsiz = max_length
648
649 lzs.next_out = orig_out = m.malloc(bufsiz)
650 if orig_out == ffi.NULL:
651 raise MemoryError
652
653 lzs.avail_out = bufsiz
654
655 data_size = 0
656
657 try:
658 while True:
659 ret = catch_lzma_error(m.lzma_code, lzs, m.LZMA_RUN,
660 ignore_buf_error=(lzs.avail_in == 0 and lzs.avail_out > 0))
661 data_size = int(ffi.cast('uintptr_t', lzs.next_out)) - int(ffi.cast('uintptr_t', orig_out))
662 # data_size is the amount lzma_code has already outputted
663
664 if ret in (m.LZMA_NO_CHECK, m.LZMA_GET_CHECK):
665 self.check = m.lzma_get_check(lzs)
666
667 if ret == m.LZMA_STREAM_END:
668 self.eof = True
669 break
670 elif lzs.avail_out == 0:
671 # Need to check lzs->avail_out before lzs->avail_in.
672 # Maybe lzs's internal state still have a few bytes
673 # can be output, grow the output buffer and continue
674 # if max_lengh < 0.
675 if data_size == max_length:
676 break
677 # ran out of space in the output buffer, let's grow it
678 bufsiz += (bufsiz >> 3) + 6
679 if max_length > 0 and bufsiz > max_length:
680 bufsiz = max_length
681 next_out = m.realloc(orig_out, bufsiz)
682 if next_out == ffi.NULL:
683 # realloc unsuccessful
684 m.free(orig_out)
685 orig_out = ffi.NULL
686 raise MemoryError
687
688 orig_out = next_out
689
690 lzs.next_out = orig_out + data_size
691 lzs.avail_out = bufsiz - data_size
692 elif lzs.avail_in == 0:
693 # it ate everything
694 break
695
696 result = ffi.buffer(orig_out, data_size)[:]
697 finally:
698 m.free(orig_out)
699
700 return result
701
702 def __getstate__(self):
703 raise TypeError("cannot serialize '%s' object" %
704 self.__class__.__name__)
705
706
707 # Issue #2579: Setting up the stream for encoding takes around 17MB of
708 # RAM on my Linux 64 system. So we call add_memory_pressure(17MB) when
709 # we create the stream. In flush(), we actively free the stream even
710 # though we could just leave it to the GC (but 17MB is too much for
711 # doing that sanely); at this point we call add_memory_pressure(-17MB)
712 # to cancel the original increase.
713 COMPRESSION_STREAM_SIZE = 1024*1024*17
714
715
716 class LZMACompressor(object):
717 """
718 LZMACompressor(format=FORMAT_XZ, check=-1, preset=None, filters=None)
719
720 Create a compressor object for compressing data incrementally.
721
722 format specifies the container format to use for the output. This can
723 be FORMAT_XZ (default), FORMAT_ALONE, or FORMAT_RAW.
724
725 check specifies the integrity check to use. For FORMAT_XZ, the default
726 is CHECK_CRC64. FORMAT_ALONE and FORMAT_RAW do not suport integrity
727 checks; for these formats, check must be omitted, or be CHECK_NONE.
728
729 The settings used by the compressor can be specified either as a
730 preset compression level (with the 'preset' argument), or in detail
731 as a custom filter chain (with the 'filters' argument). For FORMAT_XZ
732 and FORMAT_ALONE, the default is to use the PRESET_DEFAULT preset
733 level. For FORMAT_RAW, the caller must always specify a filter chain;
734 the raw compressor does not support preset compression levels.
735
736 preset (if provided) should be an integer in the range 0-9, optionally
737 OR-ed with the constant PRESET_EXTREME.
738
739 filters (if provided) should be a sequence of dicts. Each dict should
740 have an entry for "id" indicating the ID of the filter, plus
741 additional entries for options to the filter.
742
743 For one-shot compression, use the compress() function instead.
744 """
745 def __init__(self, format=FORMAT_XZ, check=-1, preset=None, filters=None):
746 if format != FORMAT_XZ and check not in (-1, m.LZMA_CHECK_NONE):
747 raise ValueError("Integrity checks are only supported by FORMAT_XZ")
748 if preset is not None and filters is not None:
749 raise ValueError("Cannot specify both preset and filter chain")
750 if preset is None:
751 preset = m.LZMA_PRESET_DEFAULT
752 format = _parse_format(format)
753 self.lock = threading.Lock()
754 self.flushed = 0
755 self.lzs = _new_lzma_stream()
756 __pypy__.add_memory_pressure(COMPRESSION_STREAM_SIZE)
757 if format == FORMAT_XZ:
758 if filters is None:
759 if check == -1:
760 check = m.LZMA_CHECK_CRC64
761 catch_lzma_error(m.lzma_easy_encoder, self.lzs,
762 preset, check)
763 else:
764 filters = parse_filter_chain_spec(filters)
765 catch_lzma_error(m.lzma_stream_encoder, self.lzs,
766 filters, check)
767 elif format == FORMAT_ALONE:
768 if filters is None:
769 options = ffi.new('lzma_options_lzma*')
770 if m.lzma_lzma_preset(options, preset):
771 raise LZMAError("Invalid compression preset: %s" % preset)
772 catch_lzma_error(m.lzma_alone_encoder, self.lzs,
773 options)
774 else:
775 raise NotImplementedError
776 elif format == FORMAT_RAW:
777 if filters is None:
778 raise ValueError("Must specify filters for FORMAT_RAW")
779 filters = parse_filter_chain_spec(filters)
780 catch_lzma_error(m.lzma_raw_encoder, self.lzs,
781 filters)
782 else:
783 raise ValueError("invalid container format: %s" % format)
784
785 def compress(self, data):
786 """
787 compress(data) -> bytes
788
789 Provide data to the compressor object. Returns a chunk of
790 compressed data if possible, or b"" otherwise.
791
792 When you have finished providing data to the compressor, call the
793 flush() method to finish the conversion process.
794 """
795 with self.lock:
796 if self.flushed:
797 raise ValueError("Compressor has been flushed")
798 return self._compress(data)
799
800 def _compress(self, data, action=m.LZMA_RUN):
801 # TODO use realloc like in LZMADecompressor
802 BUFSIZ = 8192
803
804 lzs = self.lzs
805
806 lzs.next_in = input_ = ffi.new('uint8_t[]', to_bytes(data))
807 lzs.avail_in = input_len = len(data)
808 outs = [ffi.new('uint8_t[]', BUFSIZ)]
809 lzs.next_out, = outs
810 lzs.avail_out = BUFSIZ
811
812 siz = BUFSIZ
813
814 while True:
815 next_out_pos = int(ffi.cast('intptr_t', lzs.next_out))
816 ret = catch_lzma_error(m.lzma_code, lzs, action,
817 ignore_buf_error=(input_len==0 and lzs.avail_out > 0))
818 data_size = int(ffi.cast('intptr_t', lzs.next_out)) - next_out_pos
819 if (action == m.LZMA_RUN and lzs.avail_in == 0) or \
820 (action == m.LZMA_FINISH and ret == m.LZMA_STREAM_END):
821 break
822 elif lzs.avail_out == 0:
823 # ran out of space in the output buffer
824 #siz = (BUFSIZ << 1) + 6
825 siz = 512
826 outs.append(ffi.new('uint8_t[]', siz))
827 lzs.next_out = outs[-1]
828 lzs.avail_out = siz
829 last_out = outs.pop()
830 last_out_len = siz - lzs.avail_out
831 last_out_piece = ffi.buffer(last_out[0:last_out_len], last_out_len)[:]
832
833 return b''.join(ffi.buffer(nn)[:] for nn in outs) + last_out_piece
834
835 def flush(self):
836 with self.lock:
837 if self.flushed:
838 raise ValueError("Repeated call to flush()")
839 self.flushed = 1
840 result = self._compress(b'', action=m.LZMA_FINISH)
841 __pypy__.add_memory_pressure(-COMPRESSION_STREAM_SIZE)
842 _release_lzma_stream(self.lzs)
843 return result
844
845 def __getstate__(self):
846 raise TypeError("cannot serialize '%s' object" %
847 self.__class__.__name__)
848