| 1 |
from cpython cimport * |
| 2 |
from cpython.bytearray cimport PyByteArray_Check, PyByteArray_CheckExact |
| 3 |
from cpython.datetime cimport ( |
| 4 |
PyDateTime_CheckExact, PyDelta_CheckExact, |
| 5 |
datetime_tzinfo, timedelta_days, timedelta_seconds, timedelta_microseconds, |
| 6 |
) |
| 7 |
|
| 8 |
cdef ExtType |
| 9 |
cdef Timestamp |
| 10 |
|
| 11 |
from .ext import ExtType, Timestamp |
| 12 |
|
| 13 |
|
| 14 |
cdef extern from "Python.h": |
| 15 |
|
| 16 |
int PyMemoryView_Check(object obj) |
| 17 |
|
| 18 |
cdef extern from "pack.h": |
| 19 |
struct msgpack_packer: |
| 20 |
char* buf |
| 21 |
size_t length |
| 22 |
size_t buf_size |
| 23 |
bint use_bin_type |
| 24 |
|
| 25 |
int msgpack_pack_nil(msgpack_packer* pk) except -1 |
| 26 |
int msgpack_pack_true(msgpack_packer* pk) except -1 |
| 27 |
int msgpack_pack_false(msgpack_packer* pk) except -1 |
| 28 |
int msgpack_pack_long_long(msgpack_packer* pk, long long d) except -1 |
| 29 |
int msgpack_pack_unsigned_long_long(msgpack_packer* pk, unsigned long long d) except -1 |
| 30 |
int msgpack_pack_float(msgpack_packer* pk, float d) except -1 |
| 31 |
int msgpack_pack_double(msgpack_packer* pk, double d) except -1 |
| 32 |
int msgpack_pack_array(msgpack_packer* pk, size_t l) except -1 |
| 33 |
int msgpack_pack_map(msgpack_packer* pk, size_t l) except -1 |
| 34 |
int msgpack_pack_raw(msgpack_packer* pk, size_t l) except -1 |
| 35 |
int msgpack_pack_bin(msgpack_packer* pk, size_t l) except -1 |
| 36 |
int msgpack_pack_raw_body(msgpack_packer* pk, char* body, size_t l) except -1 |
| 37 |
int msgpack_pack_ext(msgpack_packer* pk, char typecode, size_t l) except -1 |
| 38 |
int msgpack_pack_timestamp(msgpack_packer* x, long long seconds, unsigned long nanoseconds) except -1 |
| 39 |
|
| 40 |
|
| 41 |
cdef int DEFAULT_RECURSE_LIMIT=1024 |
| 42 |
cdef long long ITEM_LIMIT = (2**32)-1 |
| 43 |
|
| 44 |
|
| 45 |
cdef inline int PyBytesLike_Check(object o): |
| 46 |
return PyBytes_Check(o) or PyByteArray_Check(o) |
| 47 |
|
| 48 |
|
| 49 |
cdef inline int PyBytesLike_CheckExact(object o): |
| 50 |
return PyBytes_CheckExact(o) or PyByteArray_CheckExact(o) |
| 51 |
|
| 52 |
|
| 53 |
cdef class Packer: |
| 54 |
""" |
| 55 |
MessagePack Packer |
| 56 |
|
| 57 |
Usage:: |
| 58 |
|
| 59 |
packer = Packer() |
| 60 |
astream.write(packer.pack(a)) |
| 61 |
astream.write(packer.pack(b)) |
| 62 |
|
| 63 |
Packer's constructor has some keyword arguments: |
| 64 |
|
| 65 |
:param default: |
| 66 |
When specified, it should be callable. |
| 67 |
Convert user type to builtin type that Packer supports. |
| 68 |
See also simplejson's document. |
| 69 |
|
| 70 |
:param bool use_single_float: |
| 71 |
Use single precision float type for float. (default: False) |
| 72 |
|
| 73 |
:param bool autoreset: |
| 74 |
Reset buffer after each pack and return its content as `bytes`. (default: True). |
| 75 |
If set this to false, use `bytes()` to get content and `.reset()` to clear buffer. |
| 76 |
|
| 77 |
:param bool use_bin_type: |
| 78 |
Use bin type introduced in msgpack spec 2.0 for bytes. |
| 79 |
It also enables str8 type for unicode. (default: True) |
| 80 |
|
| 81 |
:param bool strict_types: |
| 82 |
If set to true, types will be checked to be exact. Derived classes |
| 83 |
from serializeable types will not be serialized and will be |
| 84 |
treated as unsupported type and forwarded to default. |
| 85 |
Additionally tuples will not be serialized as lists. |
| 86 |
This is useful when trying to implement accurate serialization |
| 87 |
for python types. |
| 88 |
|
| 89 |
:param bool datetime: |
| 90 |
If set to true, datetime with tzinfo is packed into Timestamp type. |
| 91 |
Note that the tzinfo is stripped in the timestamp. |
| 92 |
You can get UTC datetime with `timestamp=3` option of the Unpacker. |
| 93 |
|
| 94 |
:param str unicode_errors: |
| 95 |
The error handler for encoding unicode. (default: 'strict') |
| 96 |
DO NOT USE THIS!! This option is kept for very specific usage. |
| 97 |
|
| 98 |
:param int buf_size: |
| 99 |
The size of the internal buffer. (default: 256*1024) |
| 100 |
Useful if serialisation size can be correctly estimated, |
| 101 |
avoid unnecessary reallocations. |
| 102 |
""" |
| 103 |
cdef msgpack_packer pk |
| 104 |
cdef object _default |
| 105 |
cdef object _berrors |
| 106 |
cdef const char *unicode_errors |
| 107 |
cdef size_t exports # number of exported buffers |
| 108 |
cdef bint strict_types |
| 109 |
cdef bint use_float |
| 110 |
cdef bint autoreset |
| 111 |
cdef bint datetime |
| 112 |
|
| 113 |
def __cinit__(self, buf_size=256*1024, **_kwargs): |
| 114 |
self.pk.buf = <char*> PyMem_Malloc(buf_size) |
| 115 |
if self.pk.buf == NULL: |
| 116 |
raise MemoryError("Unable to allocate internal buffer.") |
| 117 |
self.pk.buf_size = buf_size |
| 118 |
self.pk.length = 0 |
| 119 |
self.exports = 0 |
| 120 |
|
| 121 |
def __dealloc__(self): |
| 122 |
PyMem_Free(self.pk.buf) |
| 123 |
self.pk.buf = NULL |
| 124 |
assert self.exports == 0 |
| 125 |
|
| 126 |
cdef _check_exports(self): |
| 127 |
if self.exports > 0: |
| 128 |
raise BufferError("Existing exports of data: Packer cannot be changed") |
| 129 |
|
| 130 |
@cython.critical_section |
| 131 |
def __init__(self, *, default=None, |
| 132 |
bint use_single_float=False, bint autoreset=True, bint use_bin_type=True, |
| 133 |
bint strict_types=False, bint datetime=False, unicode_errors=None, |
| 134 |
buf_size=256*1024): |
| 135 |
self.use_float = use_single_float |
| 136 |
self.strict_types = strict_types |
| 137 |
self.autoreset = autoreset |
| 138 |
self.datetime = datetime |
| 139 |
self.pk.use_bin_type = use_bin_type |
| 140 |
if default is not None: |
| 141 |
if not PyCallable_Check(default): |
| 142 |
raise TypeError("default must be a callable.") |
| 143 |
self._default = default |
| 144 |
|
| 145 |
self._berrors = unicode_errors |
| 146 |
if unicode_errors is None: |
| 147 |
self.unicode_errors = NULL |
| 148 |
else: |
| 149 |
self.unicode_errors = self._berrors |
| 150 |
|
| 151 |
# returns -2 when default should(o) be called |
| 152 |
cdef int _pack_inner(self, object o, bint will_default, int nest_limit) except -1: |
| 153 |
cdef long long llval |
| 154 |
cdef unsigned long long ullval |
| 155 |
cdef unsigned long ulval |
| 156 |
cdef const char* rawval |
| 157 |
cdef Py_ssize_t L |
| 158 |
cdef Py_buffer view |
| 159 |
cdef bint strict = self.strict_types |
| 160 |
|
| 161 |
if o is None: |
| 162 |
msgpack_pack_nil(&self.pk) |
| 163 |
elif o is True: |
| 164 |
msgpack_pack_true(&self.pk) |
| 165 |
elif o is False: |
| 166 |
msgpack_pack_false(&self.pk) |
| 167 |
elif PyLong_CheckExact(o) if strict else PyLong_Check(o): |
| 168 |
try: |
| 169 |
if o > 0: |
| 170 |
ullval = o |
| 171 |
msgpack_pack_unsigned_long_long(&self.pk, ullval) |
| 172 |
else: |
| 173 |
llval = o |
| 174 |
msgpack_pack_long_long(&self.pk, llval) |
| 175 |
except OverflowError as oe: |
| 176 |
if will_default: |
| 177 |
return -2 |
| 178 |
else: |
| 179 |
raise OverflowError("Integer value out of range") |
| 180 |
elif PyFloat_CheckExact(o) if strict else PyFloat_Check(o): |
| 181 |
if self.use_float: |
| 182 |
msgpack_pack_float(&self.pk, <float>o) |
| 183 |
else: |
| 184 |
msgpack_pack_double(&self.pk, <double>o) |
| 185 |
elif PyBytesLike_CheckExact(o) if strict else PyBytesLike_Check(o): |
| 186 |
L = Py_SIZE(o) |
| 187 |
if L > ITEM_LIMIT: |
| 188 |
PyErr_Format(ValueError, b"%.200s object is too large", Py_TYPE(o).tp_name) |
| 189 |
rawval = o |
| 190 |
msgpack_pack_bin(&self.pk, L) |
| 191 |
msgpack_pack_raw_body(&self.pk, rawval, L) |
| 192 |
elif PyUnicode_CheckExact(o) if strict else PyUnicode_Check(o): |
| 193 |
if self.unicode_errors == NULL: |
| 194 |
rawval = PyUnicode_AsUTF8AndSize(o, &L) |
| 195 |
if L >ITEM_LIMIT: |
| 196 |
raise ValueError("unicode string is too large") |
| 197 |
else: |
| 198 |
o = PyUnicode_AsEncodedString(o, NULL, self.unicode_errors) |
| 199 |
L = Py_SIZE(o) |
| 200 |
if L > ITEM_LIMIT: |
| 201 |
raise ValueError("unicode string is too large") |
| 202 |
rawval = o |
| 203 |
msgpack_pack_raw(&self.pk, L) |
| 204 |
msgpack_pack_raw_body(&self.pk, rawval, L) |
| 205 |
elif PyDict_CheckExact(o) if strict else PyDict_Check(o): |
| 206 |
L = len(o) |
| 207 |
if L > ITEM_LIMIT: |
| 208 |
raise ValueError("dict is too large") |
| 209 |
msgpack_pack_map(&self.pk, L) |
| 210 |
for k, v in o.items(): |
| 211 |
self._pack(k, nest_limit) |
| 212 |
self._pack(v, nest_limit) |
| 213 |
elif type(o) is ExtType if strict else isinstance(o, ExtType): |
| 214 |
# This should be before Tuple because ExtType is namedtuple. |
| 215 |
rawval = o.data |
| 216 |
L = len(o.data) |
| 217 |
if L > ITEM_LIMIT: |
| 218 |
raise ValueError("EXT data is too large") |
| 219 |
msgpack_pack_ext(&self.pk, <long>o.code, L) |
| 220 |
msgpack_pack_raw_body(&self.pk, rawval, L) |
| 221 |
elif type(o) is Timestamp: |
| 222 |
llval = o.seconds |
| 223 |
ulval = o.nanoseconds |
| 224 |
msgpack_pack_timestamp(&self.pk, llval, ulval) |
| 225 |
elif PyList_CheckExact(o) if strict else (PyTuple_Check(o) or PyList_Check(o)): |
| 226 |
L = Py_SIZE(o) |
| 227 |
if L > ITEM_LIMIT: |
| 228 |
raise ValueError("list is too large") |
| 229 |
msgpack_pack_array(&self.pk, L) |
| 230 |
for v in o: |
| 231 |
self._pack(v, nest_limit) |
| 232 |
elif PyMemoryView_Check(o): |
| 233 |
PyObject_GetBuffer(o, &view, PyBUF_SIMPLE) |
| 234 |
L = view.len |
| 235 |
if L > ITEM_LIMIT: |
| 236 |
PyBuffer_Release(&view); |
| 237 |
raise ValueError("memoryview is too large") |
| 238 |
try: |
| 239 |
msgpack_pack_bin(&self.pk, L) |
| 240 |
msgpack_pack_raw_body(&self.pk, <char*>view.buf, L) |
| 241 |
finally: |
| 242 |
PyBuffer_Release(&view); |
| 243 |
elif self.datetime and PyDateTime_CheckExact(o) and datetime_tzinfo(o) is not None: |
| 244 |
delta = o - epoch |
| 245 |
if not PyDelta_CheckExact(delta): |
| 246 |
raise ValueError("failed to calculate delta") |
| 247 |
llval = timedelta_days(delta) * <long long>(24*60*60) + timedelta_seconds(delta) |
| 248 |
ulval = timedelta_microseconds(delta) * 1000 |
| 249 |
msgpack_pack_timestamp(&self.pk, llval, ulval) |
| 250 |
elif will_default: |
| 251 |
return -2 |
| 252 |
elif self.datetime and PyDateTime_CheckExact(o): |
| 253 |
# this should be later than will_default |
| 254 |
PyErr_Format(ValueError, b"can not serialize '%.200s' object where tzinfo=None", Py_TYPE(o).tp_name) |
| 255 |
else: |
| 256 |
PyErr_Format(TypeError, b"can not serialize '%.200s' object", Py_TYPE(o).tp_name) |
| 257 |
|
| 258 |
cdef int _pack(self, object o, int nest_limit=DEFAULT_RECURSE_LIMIT) except -1: |
| 259 |
cdef int ret |
| 260 |
if nest_limit < 0: |
| 261 |
raise ValueError("recursion limit exceeded.") |
| 262 |
nest_limit -= 1 |
| 263 |
if self._default is not None: |
| 264 |
ret = self._pack_inner(o, 1, nest_limit) |
| 265 |
if ret == -2: |
| 266 |
o = self._default(o) |
| 267 |
else: |
| 268 |
return ret |
| 269 |
return self._pack_inner(o, 0, nest_limit) |
| 270 |
|
| 271 |
@cython.critical_section |
| 272 |
def pack(self, object obj): |
| 273 |
cdef int ret |
| 274 |
self._check_exports() |
| 275 |
try: |
| 276 |
ret = self._pack(obj, DEFAULT_RECURSE_LIMIT) |
| 277 |
except: |
| 278 |
self.pk.length = 0 |
| 279 |
raise |
| 280 |
if ret: # should not happen. |
| 281 |
raise RuntimeError("internal error") |
| 282 |
if self.autoreset: |
| 283 |
buf = PyBytes_FromStringAndSize(self.pk.buf, self.pk.length) |
| 284 |
self.pk.length = 0 |
| 285 |
return buf |
| 286 |
|
| 287 |
@cython.critical_section |
| 288 |
def pack_ext_type(self, typecode, data): |
| 289 |
self._check_exports() |
| 290 |
if len(data) > ITEM_LIMIT: |
| 291 |
raise ValueError("ext data too large") |
| 292 |
msgpack_pack_ext(&self.pk, typecode, len(data)) |
| 293 |
msgpack_pack_raw_body(&self.pk, data, len(data)) |
| 294 |
if self.autoreset: |
| 295 |
buf = PyBytes_FromStringAndSize(self.pk.buf, self.pk.length) |
| 296 |
self.pk.length = 0 |
| 297 |
return buf |
| 298 |
|
| 299 |
@cython.critical_section |
| 300 |
def pack_array_header(self, long long size): |
| 301 |
self._check_exports() |
| 302 |
if size > ITEM_LIMIT: |
| 303 |
raise ValueError("array too large") |
| 304 |
msgpack_pack_array(&self.pk, size) |
| 305 |
if self.autoreset: |
| 306 |
buf = PyBytes_FromStringAndSize(self.pk.buf, self.pk.length) |
| 307 |
self.pk.length = 0 |
| 308 |
return buf |
| 309 |
|
| 310 |
@cython.critical_section |
| 311 |
def pack_map_header(self, long long size): |
| 312 |
self._check_exports() |
| 313 |
if size > ITEM_LIMIT: |
| 314 |
raise ValueError("map too learge") |
| 315 |
msgpack_pack_map(&self.pk, size) |
| 316 |
if self.autoreset: |
| 317 |
buf = PyBytes_FromStringAndSize(self.pk.buf, self.pk.length) |
| 318 |
self.pk.length = 0 |
| 319 |
return buf |
| 320 |
|
| 321 |
@cython.critical_section |
| 322 |
def pack_map_pairs(self, object pairs): |
| 323 |
""" |
| 324 |
Pack *pairs* as msgpack map type. |
| 325 |
|
| 326 |
*pairs* should be a sequence of pairs. |
| 327 |
(`len(pairs)` and `for k, v in pairs:` should be supported.) |
| 328 |
""" |
| 329 |
self._check_exports() |
| 330 |
size = len(pairs) |
| 331 |
if size > ITEM_LIMIT: |
| 332 |
raise ValueError("map too large") |
| 333 |
msgpack_pack_map(&self.pk, size) |
| 334 |
for k, v in pairs: |
| 335 |
self._pack(k) |
| 336 |
self._pack(v) |
| 337 |
if self.autoreset: |
| 338 |
buf = PyBytes_FromStringAndSize(self.pk.buf, self.pk.length) |
| 339 |
self.pk.length = 0 |
| 340 |
return buf |
| 341 |
|
| 342 |
@cython.critical_section |
| 343 |
def reset(self): |
| 344 |
"""Reset internal buffer. |
| 345 |
|
| 346 |
This method is useful only when autoreset=False. |
| 347 |
""" |
| 348 |
self._check_exports() |
| 349 |
self.pk.length = 0 |
| 350 |
|
| 351 |
@cython.critical_section |
| 352 |
def bytes(self): |
| 353 |
"""Return internal buffer contents as bytes object""" |
| 354 |
return PyBytes_FromStringAndSize(self.pk.buf, self.pk.length) |
| 355 |
|
| 356 |
def getbuffer(self): |
| 357 |
"""Return memoryview of internal buffer. |
| 358 |
|
| 359 |
Note: Packer now supports buffer protocol. You can use memoryview(packer). |
| 360 |
""" |
| 361 |
return memoryview(self) |
| 362 |
|
| 363 |
@cython.critical_section |
| 364 |
def __getbuffer__(self, Py_buffer *buffer, int flags): |
| 365 |
PyBuffer_FillInfo(buffer, self, self.pk.buf, self.pk.length, 1, flags) |
| 366 |
self.exports += 1 |
| 367 |
|
| 368 |
@cython.critical_section |
| 369 |
def __releasebuffer__(self, Py_buffer *buffer): |
| 370 |
self.exports -= 1 |