|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +from __future__ import absolute_import, print_function, division |
| 3 | + |
| 4 | + |
| 5 | +import numpy as np |
| 6 | + |
| 7 | + |
| 8 | +from numcodecs.abc import Codec |
| 9 | +from numcodecs.compat import ndarray_from_buffer, buffer_copy |
| 10 | +try: |
| 11 | + import cPickle as pickle |
| 12 | +except ImportError: |
| 13 | + import pickle |
| 14 | + |
| 15 | + |
| 16 | +class Pickle(Codec): |
| 17 | + """Codec to encode data as as pickled bytes. Useful for encoding python |
| 18 | + strings. |
| 19 | +
|
| 20 | + Parameters |
| 21 | + ---------- |
| 22 | + protocol : int, defaults to pickle.HIGHEST_PROTOCOL |
| 23 | + the protocol used to pickle data |
| 24 | +
|
| 25 | + Raises |
| 26 | + ------ |
| 27 | + encoding a non-object dtyped ndarray will raise ValueError |
| 28 | +
|
| 29 | + Examples |
| 30 | + -------- |
| 31 | + >>> import numcodecs as codecs |
| 32 | + >>> import numpy as np |
| 33 | + >>> x = np.array(['foo', 'bar', 'baz'], dtype='object') |
| 34 | + >>> f = codecs.Pickle() |
| 35 | + >>> f.decode(f.encode(x)) |
| 36 | + array(['foo', 'bar', 'baz'], dtype=object) |
| 37 | +
|
| 38 | + """ # flake8: noqa |
| 39 | + |
| 40 | + codec_id = 'pickle' |
| 41 | + |
| 42 | + def __init__(self, protocol=pickle.HIGHEST_PROTOCOL): |
| 43 | + self.protocol = protocol |
| 44 | + |
| 45 | + def encode(self, buf): |
| 46 | + if hasattr(buf, 'dtype') and buf.dtype != 'object': |
| 47 | + raise ValueError("cannot encode non-object ndarrays, %s " |
| 48 | + "dtype was passed" % buf.dtype) |
| 49 | + return pickle.dumps(buf, protocol=self.protocol) |
| 50 | + |
| 51 | + def decode(self, buf, out=None): |
| 52 | + dec = pickle.loads(buf) |
| 53 | + if out is not None: |
| 54 | + np.copyto(out, dec) |
| 55 | + return out |
| 56 | + else: |
| 57 | + return dec |
| 58 | + |
| 59 | + def get_config(self): |
| 60 | + return dict(id=self.codec_id, |
| 61 | + protocol=self.protocol) |
| 62 | + |
| 63 | + def __repr__(self): |
| 64 | + return 'Pickle(protocol=%s)' % self.protocol |
0 commit comments