|
5 | 5 |
|
6 | 6 |
|
7 | 7 | from .abc import Codec |
8 | | -from .compat import ndarray_copy, ensure_ndarray, 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): |
@@ -50,16 +50,27 @@ def encode(self, buf): |
50 | 50 | def decode(self, buf, out=None): |
51 | 51 |
|
52 | 52 | # normalise inputs |
53 | | - buf = ensure_contiguous_ndarray(buf) |
54 | | - if out is not None: |
55 | | - 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) |
56 | 61 |
|
57 | 62 | # do decompression |
58 | 63 | buf = io.BytesIO(buf) |
59 | 64 | with _gzip.GzipFile(fileobj=buf, mode='rb') as decompressor: |
60 | | - 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()) |
61 | 72 |
|
62 | 73 | # handle destination - Python standard library zlib module does not |
63 | 74 | # support direct decompression into buffer, so we have to copy into |
64 | 75 | # out if given |
65 | | - return ndarray_copy(decompressed, out) |
| 76 | + return out |
0 commit comments