|
5 | 5 |
|
6 | 6 |
|
7 | 7 | from .abc import Codec |
8 | | -from .compat import ndarray_copy, ensure_contiguous_ndarray, PY2 |
| 8 | +from .compat import ensure_bytes, ensure_ndarray, ensure_contiguous_ndarray, PY2 |
9 | 9 |
|
10 | 10 |
|
11 | 11 | class GZip(Codec): |
@@ -38,24 +38,39 @@ def encode(self, buf): |
38 | 38 | mode='wb', |
39 | 39 | compresslevel=self.level) as compressor: |
40 | 40 | compressor.write(buf) |
41 | | - compressed = compressed.getvalue() |
42 | 41 |
|
43 | | - return compressed |
| 42 | + try: |
| 43 | + compressed = compressed.getbuffer() |
| 44 | + except AttributeError: # pragma: py3 no cover |
| 45 | + compressed = compressed.getvalue() |
| 46 | + |
| 47 | + return ensure_ndarray(compressed) |
44 | 48 |
|
45 | 49 | # noinspection PyMethodMayBeStatic |
46 | 50 | def decode(self, buf, out=None): |
47 | 51 |
|
48 | 52 | # normalise inputs |
49 | | - buf = ensure_contiguous_ndarray(buf) |
50 | | - if out is not None: |
51 | | - out = ensure_contiguous_ndarray(out) |
| 53 | + if PY2: # pragma: py3 no cover |
| 54 | + # On Python 2, BytesIO always copies. |
| 55 | + # Merely ensure the data supports the (new) buffer protocol. |
| 56 | + buf = ensure_contiguous_ndarray(buf) |
| 57 | + else: # pragma: py2 no cover |
| 58 | + # BytesIO only copies if the data is not of `bytes` type. |
| 59 | + # This allows `bytes` objects to pass through without copying. |
| 60 | + buf = ensure_bytes(buf) |
52 | 61 |
|
53 | 62 | # do decompression |
54 | 63 | buf = io.BytesIO(buf) |
55 | 64 | with _gzip.GzipFile(fileobj=buf, mode='rb') as decompressor: |
56 | | - decompressed = decompressor.read() |
| 65 | + if out is not None: |
| 66 | + out_view = ensure_contiguous_ndarray(out) |
| 67 | + decompressor.readinto(out_view) |
| 68 | + if decompressor.read(1) != b'': |
| 69 | + raise ValueError("Unable to fit data into `out`") |
| 70 | + else: |
| 71 | + out = ensure_ndarray(decompressor.read()) |
57 | 72 |
|
58 | 73 | # handle destination - Python standard library zlib module does not |
59 | 74 | # support direct decompression into buffer, so we have to copy into |
60 | 75 | # out if given |
61 | | - return ndarray_copy(decompressed, out) |
| 76 | + return out |
0 commit comments