Debian Codegraph @

snappy/snappy.py

raw
1 #!/usr/bin/env python
2 #
3 # Copyright (c) 2011, Andres Moreira <[email protected]>
4 # 2011, Felipe Cruz <[email protected]>
5 # 2012, JT Olds <[email protected]>
6 # All rights reserved.
7 #
8 # Redistribution and use in source and binary forms, with or without
9 # modification, are permitted provided that the following conditions are met:
10 # * Redistributions of source code must retain the above copyright
11 # notice, this list of conditions and the following disclaimer.
12 # * Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in the
14 # documentation and/or other materials provided with the distribution.
15 # * Neither the name of the authors nor the
16 # names of its contributors may be used to endorse or promote products
17 # derived from this software without specific prior written permission.
18 #
19 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 # ARE DISCLAIMED. IN NO EVENT SHALL ANDRES MOREIRA BE LIABLE FOR ANY DIRECT,
23 # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26 # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #
30
31 """python-snappy
32
33 Python library for the snappy compression library from Google.
34 Expected usage like:
35
36 import snappy
37
38 compressed = snappy.compress("some data")
39 assert "some data" == snappy.uncompress(compressed)
40
41 """
42 from __future__ import absolute_import
43
44 import sys
45 import struct
46
47 try:
48 from ._snappy import UncompressError, compress, decompress, \
49 isValidCompressed, uncompress, _crc32c
50 except ImportError:
51 from .snappy_cffi import UncompressError, compress, decompress, \
52 isValidCompressed, uncompress, _crc32c
53
54 _CHUNK_MAX = 65536
55 _STREAM_TO_STREAM_BLOCK_SIZE = _CHUNK_MAX
56 _STREAM_IDENTIFIER = b"sNaPpY"
57 _COMPRESSED_CHUNK = 0x00
58 _UNCOMPRESSED_CHUNK = 0x01
59 _IDENTIFIER_CHUNK = 0xff
60 _RESERVED_UNSKIPPABLE = (0x02, 0x80) # chunk ranges are [inclusive, exclusive)
61 _RESERVED_SKIPPABLE = (0x80, 0xff)
62
63 # the minimum percent of bytes compression must save to be enabled in automatic
64 # mode
65 _COMPRESSION_THRESHOLD = .125
66
67 def _masked_crc32c(data):
68 # see the framing format specification
69 crc = _crc32c(data)
70 return (((crc >> 15) | (crc << 17)) + 0xa282ead8) & 0xffffffff
71
72 _compress = compress
73 _uncompress = uncompress
74
75
76 py3k = False
77 if sys.hexversion > 0x03000000:
78 unicode = str
79 py3k = True
80
81 def compress(data, encoding='utf-8'):
82 if isinstance(data, unicode):
83 data = data.encode(encoding)
84
85 return _compress(data)
86
87 def uncompress(data, decoding=None):
88 if isinstance(data, unicode):
89 raise UncompressError("It's only possible to uncompress bytes")
90 if decoding:
91 return _uncompress(data).decode(decoding)
92 return _uncompress(data)
93
94 decompress = uncompress
95
96
97 class StreamCompressor(object):
98
99 """This class implements the compressor-side of the proposed Snappy framing
100 format, found at
101
102 http://code.google.com/p/snappy/source/browse/trunk/framing_format.txt
103 ?spec=svn68&r=71
104
105 This class matches the interface found for the zlib module's compression
106 objects (see zlib.compressobj), but also provides some additions, such as
107 the snappy framing format's ability to intersperse uncompressed data.
108
109 Keep in mind that this compressor object does no buffering for you to
110 appropriately size chunks. Every call to StreamCompressor.compress results
111 in a unique call to the underlying snappy compression method.
112 """
113
114 __slots__ = ["_header_chunk_written"]
115
116 def __init__(self):
117 self._header_chunk_written = False
118
119 def add_chunk(self, data, compress=None):
120 """Add a chunk containing 'data', returning a string that is framed and
121 (optionally, default) compressed. This data should be concatenated to
122 the tail end of an existing Snappy stream. In the absence of any
123 internal buffering, no data is left in any internal buffers, and so
124 unlike zlib.compress, this method returns everything.
125
126 If compress is None, compression is determined automatically based on
127 snappy's performance. If compress == True, compression always happens,
128 and if compress == False, compression never happens.
129 """
130 if not self._header_chunk_written:
131 self._header_chunk_written = True
132 out = [struct.pack("<L", _IDENTIFIER_CHUNK +
133 (len(_STREAM_IDENTIFIER) << 8)),
134 _STREAM_IDENTIFIER]
135 else:
136 out = []
137 for i in range(0, len(data), _CHUNK_MAX):
138 chunk = data[i:i + _CHUNK_MAX]
139 crc = _masked_crc32c(chunk)
140 if compress is None:
141 compressed_chunk = _compress(chunk)
142 if (len(compressed_chunk) <=
143 (1 - _COMPRESSION_THRESHOLD) * len(chunk)):
144 chunk = compressed_chunk
145 chunk_type = _COMPRESSED_CHUNK
146 else:
147 chunk_type = _UNCOMPRESSED_CHUNK
148 compressed_chunk = None
149 elif compress:
150 chunk = _compress(chunk)
151 chunk_type = _COMPRESSED_CHUNK
152 else:
153 chunk_type = _UNCOMPRESSED_CHUNK
154 out.append(struct.pack("<LL", chunk_type + ((len(chunk) + 4) << 8),
155 crc))
156 out.append(chunk)
157 return b"".join(out)
158
159 def compress(self, data):
160 """This method is simply an alias for compatibility with zlib
161 compressobj's compress method.
162 """
163 return self.add_chunk(data)
164
165 def flush(self, mode=None):
166 """This method does nothing and only exists for compatibility with
167 the zlib compressobj
168 """
169 pass
170
171 def copy(self):
172 """This method exists for compatibility with the zlib compressobj.
173 """
174 copy = StreamCompressor()
175 copy._header_chunk_written = self._header_chunk_written
176 return copy
177
178
179 class StreamDecompressor(object):
180
181 """This class implements the decompressor-side of the proposed Snappy
182 framing format, found at
183
184 http://code.google.com/p/snappy/source/browse/trunk/framing_format.txt
185 ?spec=svn68&r=71
186
187 This class matches a subset of the interface found for the zlib module's
188 decompression objects (see zlib.decompressobj). Specifically, it currently
189 implements the decompress method without the max_length option, the flush
190 method without the length option, and the copy method.
191 """
192
193 __slots__ = ["_buf", "_header_found"]
194
195 def __init__(self):
196 self._buf = b""
197 self._header_found = False
198
199 @staticmethod
200 def check_format(data):
201 """Checks that the given data starts with snappy framing format
202 stream identifier.
203 Raises UncompressError if it doesn't start with the identifier.
204 :return: None
205 """
206 if len(data) < 6:
207 raise UncompressError("Too short data length")
208 chunk_type = struct.unpack("<L", data[:4])[0]
209 size = (chunk_type >> 8)
210 chunk_type &= 0xff
211 if (chunk_type != _IDENTIFIER_CHUNK or
212 size != len(_STREAM_IDENTIFIER)):
213 raise UncompressError("stream missing snappy identifier")
214 chunk = data[4:4 + size]
215 if chunk != _STREAM_IDENTIFIER:
216 raise UncompressError("stream has invalid snappy identifier")
217
218 def decompress(self, data):
219 """Decompress 'data', returning a string containing the uncompressed
220 data corresponding to at least part of the data in string. This data
221 should be concatenated to the output produced by any preceding calls to
222 the decompress() method. Some of the input data may be preserved in
223 internal buffers for later processing.
224 """
225 self._buf += data
226 uncompressed = []
227 while True:
228 if len(self._buf) < 4:
229 return b"".join(uncompressed)
230 chunk_type = struct.unpack("<L", self._buf[:4])[0]
231 size = (chunk_type >> 8)
232 chunk_type &= 0xff
233 if not self._header_found:
234 if (chunk_type != _IDENTIFIER_CHUNK or
235 size != len(_STREAM_IDENTIFIER)):
236 raise UncompressError("stream missing snappy identifier")
237 self._header_found = True
238 if (_RESERVED_UNSKIPPABLE[0] <= chunk_type and
239 chunk_type < _RESERVED_UNSKIPPABLE[1]):
240 raise UncompressError(
241 "stream received unskippable but unknown chunk")
242 if len(self._buf) < 4 + size:
243 return b"".join(uncompressed)
244 chunk, self._buf = self._buf[4:4 + size], self._buf[4 + size:]
245 if chunk_type == _IDENTIFIER_CHUNK:
246 if chunk != _STREAM_IDENTIFIER:
247 raise UncompressError(
248 "stream has invalid snappy identifier")
249 continue
250 if (_RESERVED_SKIPPABLE[0] <= chunk_type and
251 chunk_type < _RESERVED_SKIPPABLE[1]):
252 continue
253 assert chunk_type in (_COMPRESSED_CHUNK, _UNCOMPRESSED_CHUNK)
254 crc, chunk = chunk[:4], chunk[4:]
255 if chunk_type == _COMPRESSED_CHUNK:
256 chunk = _uncompress(chunk)
257 if struct.pack("<L", _masked_crc32c(chunk)) != crc:
258 raise UncompressError("crc mismatch")
259 uncompressed.append(chunk)
260
261 def flush(self):
262 """All pending input is processed, and a string containing the
263 remaining uncompressed output is returned. After calling flush(), the
264 decompress() method cannot be called again; the only realistic action
265 is to delete the object.
266 """
267 if self._buf != b"":
268 raise UncompressError("chunk truncated")
269 return b""
270
271 def copy(self):
272 """Returns a copy of the decompression object. This can be used to save
273 the state of the decompressor midway through the data stream in order
274 to speed up random seeks into the stream at a future point.
275 """
276 copy = StreamDecompressor()
277 copy._buf, copy._header_found = self._buf, self._header_found
278 return copy
279
280
281 def stream_compress(src,
282 dst,
283 blocksize=_STREAM_TO_STREAM_BLOCK_SIZE,
284 compressor_cls=StreamCompressor):
285 """Takes an incoming file-like object and an outgoing file-like object,
286 reads data from src, compresses it, and writes it to dst. 'src' should
287 support the read method, and 'dst' should support the write method.
288
289 The default blocksize is good for almost every scenario.
290 """
291 compressor = compressor_cls()
292 while True:
293 buf = src.read(blocksize)
294 if not buf: break
295 buf = compressor.add_chunk(buf)
296 if buf: dst.write(buf)
297
298
299 def stream_decompress(src,
300 dst,
301 blocksize=_STREAM_TO_STREAM_BLOCK_SIZE,
302 decompressor_cls=StreamDecompressor,
303 start_chunk=None):
304 """Takes an incoming file-like object and an outgoing file-like object,
305 reads data from src, decompresses it, and writes it to dst. 'src' should
306 support the read method, and 'dst' should support the write method.
307
308 The default blocksize is good for almost every scenario.
309 :param decompressor_cls: class that implements `decompress` method like
310 StreamDecompressor in the module
311 :param start_chunk: start block of data that have already been read from
312 the input stream (to detect the format, for example)
313 """
314 decompressor = decompressor_cls()
315 while True:
316 if start_chunk:
317 buf = start_chunk
318 start_chunk = None
319 else:
320 buf = src.read(blocksize)
321 if not buf: break
322 buf = decompressor.decompress(buf)
323 if buf: dst.write(buf)
324 decompressor.flush() # makes sure the stream ended well
325
326
327 def check_format(fin=None, chunk=None,
328 blocksize=_STREAM_TO_STREAM_BLOCK_SIZE,
329 decompressor_cls=StreamDecompressor):
330 ok = True
331 if chunk is None:
332 chunk = fin.read(blocksize)
333 if not chunk:
334 raise UncompressError("Empty input stream")
335 try:
336 decompressor_cls.check_format(chunk)
337 except UncompressError as err:
338 ok = False
339 return ok, chunk