-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathsnappy.py
More file actions
378 lines (302 loc) · 12.1 KB
/
snappy.py
File metadata and controls
378 lines (302 loc) · 12.1 KB
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
#!/usr/bin/env python
#
# Copyright (c) 2011, Andres Moreira <andres@andresmoreira.com>
# 2011, Felipe Cruz <felipecruz@loogica.net>
# 2012, JT Olds <jt@spacemonkey.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the authors nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL ANDRES MOREIRA BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
"""python-snappy
Python library for the snappy compression library from Google.
Expected usage like:
import snappy
compressed = snappy.compress("some data")
assert "some data" == snappy.uncompress(compressed)
"""
from __future__ import absolute_import, annotations
from typing import (
Optional, Union, IO, BinaryIO, Protocol, Type, Any, overload,
)
import cramjam
_CHUNK_MAX = 65536
_STREAM_TO_STREAM_BLOCK_SIZE = _CHUNK_MAX
_STREAM_IDENTIFIER = b"sNaPpY"
_IDENTIFIER_CHUNK = 0xff
_STREAM_HEADER_BLOCK = b"\xff\x06\x00\x00sNaPpY"
_compress = cramjam.snappy.compress_raw
_uncompress = cramjam.snappy.decompress_raw
class UncompressError(Exception):
pass
def isValidCompressed(data: Union[str, bytes]) -> bool:
if isinstance(data, str):
data = data.encode('utf-8')
ok = True
try:
decompress(data)
except UncompressError as err:
ok = False
return ok
def compress(data: Union[str, bytes], encoding: str = 'utf-8') -> bytes:
if isinstance(data, str):
data = data.encode(encoding)
return bytes(_compress(data))
@overload
def uncompress(data: bytes) -> bytes: ...
@overload
def uncompress(data: bytes, decoding: Optional[str] = None) -> Union[str, bytes]: ...
def uncompress(data, decoding=None):
if isinstance(data, str):
raise UncompressError("It's only possible to uncompress bytes")
try:
out = bytes(_uncompress(data))
except cramjam.DecompressionError as err:
raise UncompressError from err
if decoding:
return out.decode(decoding)
return out
decompress = uncompress
class Compressor(Protocol):
def add_chunk(self, data) -> Any: ...
class Decompressor(Protocol):
def decompress(self, data) -> Any: ...
def flush(self): ...
class StreamCompressor():
"""This class implements the compressor-side of the proposed Snappy framing
format, found at
http://code.google.com/p/snappy/source/browse/trunk/framing_format.txt
?spec=svn68&r=71
This class matches the interface found for the zlib module's compression
objects (see zlib.compressobj), but also provides some additions, such as
the snappy framing format's ability to intersperse uncompressed data.
Keep in mind that this compressor object does no buffering for you to
appropriately size chunks. Every call to StreamCompressor.compress results
in a unique call to the underlying snappy compression method.
"""
def __init__(self):
self.c = cramjam.snappy.Compressor()
def add_chunk(self, data: bytes, compress=None) -> bytes:
"""Add a chunk, returning a string that is framed and compressed.
Outputs a single snappy chunk; if it is the very start of the stream,
will also contain the stream header chunk.
"""
self.c.compress(data)
return self.flush()
compress = add_chunk
def flush(self) -> bytes:
return bytes(self.c.flush())
def copy(self) -> 'StreamCompressor':
"""This method exists for compatibility with the zlib compressobj.
"""
return self
class StreamDecompressor():
"""This class implements the decompressor-side of the proposed Snappy
framing format, found at
http://code.google.com/p/snappy/source/browse/trunk/framing_format.txt
?spec=svn68&r=71
This class matches a subset of the interface found for the zlib module's
decompression objects (see zlib.decompressobj). Specifically, it currently
implements the decompress method without the max_length option, the flush
method without the length option, and the copy method.
"""
def __init__(self):
self.c = cramjam.snappy.Decompressor()
self.remains = None
@staticmethod
def check_format(fin):
"""Does this stream start with a stream header block?
True indicates that the stream can likely be decoded using this class.
"""
try:
return fin.read(len(_STREAM_HEADER_BLOCK)) == _STREAM_HEADER_BLOCK
except:
return False
def decompress(self, data: bytes) -> bytes:
"""Decompress 'data', returning a string containing the uncompressed
data corresponding to at least part of the data in string. This data
should be concatenated to the output produced by any preceding calls to
the decompress() method. Some of the input data may be preserved in
internal buffers for later processing.
"""
if self.remains:
data = self.remains + data
self.remains = None
if not data.startswith(_STREAM_HEADER_BLOCK):
data = _STREAM_HEADER_BLOCK + data
ldata = len(data)
bsize = len(_STREAM_HEADER_BLOCK)
if bsize + 4 > ldata:
# not even enough for one block
self.remains = data
return b""
while True:
this_size = int.from_bytes(data[bsize + 1: bsize + 4], "little") + 4
if bsize == ldata:
# ended on a block boundary
break
if this_size + bsize > ldata:
# last block incomplete
self.remains = data[bsize:]
data = data[:bsize]
break
bsize += this_size
self.c.decompress(data)
return self.flush()
def flush(self) -> bytes:
return bytes(self.c.flush())
def copy(self) -> 'StreamDecompressor':
return self
class HadoopStreamCompressor():
def add_chunk(self, data: bytes, compress=None) -> bytes:
"""Add a chunk, returning a string that is framed and compressed.
Outputs a single snappy chunk; if it is the very start of the stream,
will also contain the stream header chunk.
"""
cdata = _compress(data)
return b"".join((len(data).to_bytes(4, "big"), len(cdata).to_bytes(4, "big"), cdata))
compress = add_chunk
def flush(self) -> bytes:
# never maintains a buffer
return b""
def copy(self) -> 'HadoopStreamCompressor':
"""This method exists for compatibility with the zlib compressobj.
"""
return self
class HadoopStreamDecompressor():
def __init__(self):
self.remains = b""
@staticmethod
def check_format(fin):
"""Does this look like a hadoop snappy stream?
"""
try:
from snappy.snappy_formats import check_unframed_format
size = fin.seek(0, 2)
fin.seek(0)
assert size >= 8
chunk_length = int.from_bytes(fin.read(4), "big")
assert chunk_length < size
fin.read(4)
return check_unframed_format(fin)
except:
return False
def decompress(self, data: bytes) -> bytes:
"""Decompress 'data', returning a string containing the uncompressed
data corresponding to at least part of the data in string. This data
should be concatenated to the output produced by any preceding calls to
the decompress() method. Some of the input data may be preserved in
internal buffers for later processing.
"""
if self.remains:
data = self.remains + data
self.remains = None
if len(data) < 8:
self.remains = data
return b""
out = []
while True:
chunk_length = int.from_bytes(data[4:8], "big")
if len(data) < 8 + chunk_length:
self.remains = data
break
out.append(_uncompress(data[8:8 + chunk_length]))
data = data[8 + chunk_length:]
return b"".join(out)
def flush(self) -> bytes:
return b""
def copy(self) -> 'HadoopStreamDecompressor':
return self
def stream_compress(src: IO,
dst: IO,
blocksize: int = _STREAM_TO_STREAM_BLOCK_SIZE,
compressor_cls: Type[Compressor] = StreamCompressor) -> None:
"""Takes an incoming file-like object and an outgoing file-like object,
reads data from src, compresses it, and writes it to dst. 'src' should
support the read method, and 'dst' should support the write method.
The default blocksize is good for almost every scenario.
"""
compressor = compressor_cls()
while True:
buf = src.read(blocksize)
if not buf: break
buf = compressor.add_chunk(buf)
if buf: dst.write(buf)
def stream_decompress(src: IO,
dst: IO,
blocksize: int = _STREAM_TO_STREAM_BLOCK_SIZE,
decompressor_cls: Type[Decompressor] = StreamDecompressor,
start_chunk=None) -> None:
"""Takes an incoming file-like object and an outgoing file-like object,
reads data from src, decompresses it, and writes it to dst. 'src' should
support the read method, and 'dst' should support the write method.
The default blocksize is good for almost every scenario.
:param decompressor_cls: class that implements `decompress` and
`flush` methods like StreamDecompressor in the module
:param start_chunk: start block of data that have already been read from
the input stream (to detect the format, for example)
"""
decompressor = decompressor_cls()
while True:
if start_chunk:
buf = start_chunk
start_chunk = None
else:
buf = src.read(blocksize)
if not buf: break
buf = decompressor.decompress(buf)
if buf: dst.write(buf)
decompressor.flush() # makes sure the stream ended well
def hadoop_stream_decompress(
src: BinaryIO,
dst: BinaryIO,
blocksize: int = _STREAM_TO_STREAM_BLOCK_SIZE,
) -> None:
c = HadoopStreamDecompressor()
while True:
data = src.read(blocksize)
if not data:
break
buf = c.decompress(data)
if buf:
dst.write(buf)
dst.flush()
def hadoop_stream_compress(
src: BinaryIO,
dst: BinaryIO,
blocksize: int = _STREAM_TO_STREAM_BLOCK_SIZE,
) -> None:
c = HadoopStreamCompressor()
while True:
data = src.read(blocksize)
if not data:
break
buf = c.compress(data)
if buf:
dst.write(buf)
dst.flush()
def raw_stream_decompress(src: BinaryIO, dst: BinaryIO) -> None:
data = src.read()
dst.write(decompress(data))
def raw_stream_compress(src: BinaryIO, dst: BinaryIO) -> None:
data = src.read()
dst.write(compress(data))