1"""Fallback pure Python implementation of msgpack"""
2from datetime
import datetime
as _DateTime
9 int_types = (int, long)
25 RecursionError = RuntimeError
40if hasattr(sys,
"pypy_version_info"):
43 from __pypy__
import newlist_hint
49 USING_STRINGBUILDER =
True
70 USING_STRINGBUILDER =
False
71 from io
import BytesIO
as StringIO
73 newlist_hint =
lambda size: []
76from .exceptions
import BufferFull, OutOfData, ExtraData, FormatError, StackError
78from .ext
import ExtType, Timestamp
83EX_READ_ARRAY_HEADER = 2
93DEFAULT_RECURSE_LIMIT = 511
100 return type(obj)
is t
106 raise ValueError(
"cannot unpack from multi-byte object")
110def unpackb(packed, **kwargs):
112 Unpack an object from `packed`.
114 Raises ``ExtraData`` when *packed* contains extra bytes.
115 Raises ``ValueError`` when *packed* is incomplete.
116 Raises ``FormatError`` when *packed* is not valid msgpack.
117 Raises ``StackError`` when *packed* contains too nested.
118 Other exceptions can be raised during unpacking.
120 See :class:`Unpacker` for options.
122 unpacker =
Unpacker(
None, max_buffer_size=
len(packed), **kwargs)
127 raise ValueError(
"Unpack failed: incomplete input")
128 except RecursionError
as e:
140 """Explicit type cast for legacy struct.unpack_from"""
148 0xC4: (1, _NO_FORMAT_USED, TYPE_BIN),
149 0xC5: (2,
">H", TYPE_BIN),
150 0xC6: (4,
">I", TYPE_BIN),
151 0xC7: (2,
"Bb", TYPE_EXT),
152 0xC8: (3,
">Hb", TYPE_EXT),
153 0xC9: (5,
">Ib", TYPE_EXT),
156 0xCC: (1, _NO_FORMAT_USED),
164 0xD4: (1,
"b1s", TYPE_EXT),
165 0xD5: (2,
"b2s", TYPE_EXT),
166 0xD6: (4,
"b4s", TYPE_EXT),
167 0xD7: (8,
"b8s", TYPE_EXT),
168 0xD8: (16,
"b16s", TYPE_EXT),
169 0xD9: (1, _NO_FORMAT_USED, TYPE_RAW),
170 0xDA: (2,
">H", TYPE_RAW),
171 0xDB: (4,
">I", TYPE_RAW),
172 0xDC: (2,
">H", TYPE_ARRAY),
173 0xDD: (4,
">I", TYPE_ARRAY),
174 0xDE: (2,
">H", TYPE_MAP),
175 0xDF: (4,
">I", TYPE_MAP),
180 """Streaming unpacker.
185 File-like object having `.read(n)` method.
186 If specified, unpacker reads serialized data from it and :meth:`feed()` is not usable.
188 :param int read_size:
189 Used as `file_like.read(read_size)`. (default: `min(16*1024, max_buffer_size)`)
191 :param bool use_list:
192 If true, unpack msgpack array to Python list.
193 Otherwise, unpack to Python tuple. (default: True)
196 If true, unpack msgpack raw to Python bytes.
197 Otherwise, unpack to Python str by decoding with UTF-8 encoding (default).
199 :param int timestamp:
200 Control how timestamp type is unpacked:
203 1 - float (Seconds from the EPOCH)
204 2 - int (Nanoseconds from the EPOCH)
205 3 - datetime.datetime (UTC). Python 2 is not supported.
207 :param bool strict_map_key:
208 If true (default), only str or bytes are accepted for map (dict) keys.
210 :param callable object_hook:
211 When specified, it should be callable.
212 Unpacker calls it with a dict argument after unpacking msgpack map.
213 (See also simplejson)
215 :param callable object_pairs_hook:
216 When specified, it should be callable.
217 Unpacker calls it with a list of key-value pairs after unpacking msgpack map.
218 (See also simplejson)
220 :param str unicode_errors:
221 The error handler for decoding unicode. (default: 'strict')
222 This option should be used only when you have msgpack data which
223 contains invalid UTF-8 string.
225 :param int max_buffer_size:
226 Limits size of data waiting unpacked. 0 means 2**32-1.
227 The default value is 100*1024*1024 (100MiB).
228 Raises `BufferFull` exception when it is insufficient.
229 You should set this parameter when unpacking data from untrusted source.
231 :param int max_str_len:
232 Deprecated, use *max_buffer_size* instead.
233 Limits max length of str. (default: max_buffer_size)
235 :param int max_bin_len:
236 Deprecated, use *max_buffer_size* instead.
237 Limits max length of bin. (default: max_buffer_size)
239 :param int max_array_len:
240 Limits max length of array.
241 (default: max_buffer_size)
243 :param int max_map_len:
244 Limits max length of map.
245 (default: max_buffer_size//2)
247 :param int max_ext_len:
248 Deprecated, use *max_buffer_size* instead.
249 Limits max size of ext type. (default: max_buffer_size)
251 Example of streaming deserialize from file-like object::
253 unpacker = Unpacker(file_like)
257 Example of streaming deserialize from socket::
259 unpacker = Unpacker()
261 buf = sock.recv(1024**2)
268 Raises ``ExtraData`` when *packed* contains extra bytes.
269 Raises ``OutOfData`` when *packed* is incomplete.
270 Raises ``FormatError`` when *packed* is not valid msgpack.
271 Raises ``StackError`` when *packed* contains too nested.
272 Other exceptions can be raised during unpacking.
284 object_pairs_hook=None,
287 max_buffer_size=100 * 1024 * 1024,
295 if unicode_errors
is None:
296 unicode_errors =
"strict"
298 if file_like
is None:
302 raise TypeError(
"`file_like.read` must be callable")
320 if not max_buffer_size:
321 max_buffer_size = 2**31 - 1
322 if max_str_len == -1:
323 max_str_len = max_buffer_size
324 if max_bin_len == -1:
325 max_bin_len = max_buffer_size
326 if max_array_len == -1:
327 max_array_len = max_buffer_size
328 if max_map_len == -1:
329 max_map_len = max_buffer_size // 2
330 if max_ext_len == -1:
331 max_ext_len = max_buffer_size
335 raise ValueError(
"read_size must be smaller than max_buffer_size")
341 if not (0 <= timestamp <= 3):
342 raise ValueError(
"timestamp must be 0..3")
355 if list_hook
is not None and not callable(list_hook):
356 raise TypeError(
"`list_hook` is not callable")
357 if object_hook
is not None and not callable(object_hook):
358 raise TypeError(
"`object_hook` is not callable")
359 if object_pairs_hook
is not None and not callable(object_pairs_hook):
360 raise TypeError(
"`object_pairs_hook` is not callable")
361 if object_hook
is not None and object_pairs_hook
is not None:
363 "object_pairs_hook and object_hook are mutually " "exclusive"
365 if not callable(ext_hook):
366 raise TypeError(
"`ext_hook` is not callable")
384 """Gets rid of the used parts of the buffer."""
395 ret = self.
_read(n, raise_outofdata=
False)
399 def _read(self, n, raise_outofdata=True):
401 self.
_reserve(n, raise_outofdata=raise_outofdata)
411 if remain_bytes >= 0:
425 remain_bytes = -remain_bytes
428 while remain_bytes > 0:
429 to_read_bytes = max(self.
_read_size, remain_bytes)
430 read_data = self.
file_like.read(to_read_bytes)
435 remain_bytes -=
len(read_data)
448 if b & 0b10000000 == 0:
450 elif b & 0b11100000 == 0b11100000:
451 obj = -1 - (b ^ 0xFF)
452 elif b & 0b11100000 == 0b10100000:
456 raise ValueError(
"%s exceeds max_str_len(%s)" % (n, self.
_max_str_len))
458 elif b & 0b11110000 == 0b10010000:
465 elif b & 0b11110000 == 0b10000000:
469 raise ValueError(
"%s exceeds max_map_len(%s)" % (n, self.
_max_map_len))
476 elif 0xC4 <= b <= 0xC6:
477 size, fmt, typ = _MSGPACK_HEADERS[b]
485 raise ValueError(
"%s exceeds max_bin_len(%s)" % (n, self.
_max_bin_len))
487 elif 0xC7 <= b <= 0xC9:
488 size, fmt, typ = _MSGPACK_HEADERS[b]
493 raise ValueError(
"%s exceeds max_ext_len(%s)" % (L, self.
_max_ext_len))
495 elif 0xCA <= b <= 0xD3:
496 size, fmt = _MSGPACK_HEADERS[b]
503 elif 0xD4 <= b <= 0xD8:
504 size, fmt, typ = _MSGPACK_HEADERS[b]
507 "%s exceeds max_ext_len(%s)" % (size, self.
_max_ext_len)
512 elif 0xD9 <= b <= 0xDB:
513 size, fmt, typ = _MSGPACK_HEADERS[b]
521 raise ValueError(
"%s exceeds max_str_len(%s)" % (n, self.
_max_str_len))
523 elif 0xDC <= b <= 0xDD:
524 size, fmt, typ = _MSGPACK_HEADERS[b]
532 elif 0xDE <= b <= 0xDF:
533 size, fmt, typ = _MSGPACK_HEADERS[b]
538 raise ValueError(
"%s exceeds max_map_len(%s)" % (n, self.
_max_map_len))
546 if execute == EX_READ_ARRAY_HEADER:
547 if typ != TYPE_ARRAY:
548 raise ValueError(
"Expected array")
550 if execute == EX_READ_MAP_HEADER:
552 raise ValueError(
"Expected map")
555 if typ == TYPE_ARRAY:
556 if execute == EX_SKIP:
561 ret = newlist_hint(n)
567 return ret
if self.
_use_list else tuple(ret)
569 if execute == EX_SKIP:
583 key = self.
_unpack(EX_CONSTRUCT)
586 "%s is not allowed for map key" % str(type(key))
588 if not PY2
and type(key)
is str:
590 ret[key] = self.
_unpack(EX_CONSTRUCT)
594 if execute == EX_SKIP:
617 assert typ == TYPE_IMMEDIATE
625 ret = self.
_unpack(EX_CONSTRUCT)
631 except RecursionError:
642 ret = self.
_unpack(EX_CONSTRUCT)
643 except RecursionError:
649 ret = self.
_unpack(EX_READ_ARRAY_HEADER)
654 ret = self.
_unpack(EX_READ_MAP_HEADER)
669 astream.write(packer.pack(a))
670 astream.write(packer.pack(b))
672 Packer's constructor has some keyword arguments:
674 :param callable default:
675 Convert user type to builtin type that Packer supports.
676 See also simplejson's document.
678 :param bool use_single_float:
679 Use single precision float type for float. (default: False)
681 :param bool autoreset:
682 Reset buffer after each pack and return its content as `bytes`. (default: True).
683 If set this to false, use `bytes()` to get content and `.reset()` to clear buffer.
685 :param bool use_bin_type:
686 Use bin type introduced in msgpack spec 2.0 for bytes.
687 It also enables str8 type for unicode. (default: True)
689 :param bool strict_types:
690 If set to true, types will be checked to be exact. Derived classes
691 from serializable types will not be serialized and will be
692 treated as unsupported type and forwarded to default.
693 Additionally tuples will not be serialized as lists.
694 This is useful when trying to implement accurate serialization
697 :param bool datetime:
698 If set to true, datetime with tzinfo is packed into Timestamp type.
699 Note that the tzinfo is stripped in the timestamp.
700 You can get UTC datetime with `timestamp=3` option of the Unpacker.
701 (Python 2 is not supported).
703 :param str unicode_errors:
704 The error handler for encoding unicode. (default: 'strict')
705 DO NOT USE THIS!! This option is kept for very specific usage.
707 Example of streaming deserialize from file-like object::
709 unpacker = Unpacker(file_like)
713 Example of streaming deserialize from socket::
715 unpacker = Unpacker()
717 buf = sock.recv(1024**2)
724 Raises ``ExtraData`` when *packed* contains extra bytes.
725 Raises ``OutOfData`` when *packed* is incomplete.
726 Raises ``FormatError`` when *packed* is not valid msgpack.
727 Raises ``StackError`` when *packed* contains too nested.
728 Other exceptions can be raised during unpacking.
734 use_single_float=False,
747 raise ValueError(
"datetime is not supported in Python 2")
750 if default
is not None:
751 if not callable(default):
752 raise TypeError(
"default must be callable")
758 nest_limit=DEFAULT_RECURSE_LIMIT,
760 check_type_strict=_check_type_strict,
764 check = check_type_strict
767 list_types = (list, tuple)
770 raise ValueError(
"recursion limit exceeded")
772 return self.
_buffer.write(b
"\xc0")
775 return self.
_buffer.write(b
"\xc3")
776 return self.
_buffer.write(b
"\xc2")
777 if check(obj, int_types):
782 if 0x80 <= obj <= 0xFF:
786 if 0xFF < obj <= 0xFFFF:
788 if -0x8000 <= obj < -0x80:
790 if 0xFFFF < obj <= 0xFFFFFFFF:
792 if -0x80000000 <= obj < -0x8000:
794 if 0xFFFFFFFF < obj <= 0xFFFFFFFFFFFFFFFF:
796 if -0x8000000000000000 <= obj < -0x80000000:
798 if not default_used
and self.
_default is not None:
803 if check(obj, (bytes, bytearray)):
806 raise ValueError(
"%s is too large" % type(obj).__name__)
809 if check(obj, unicode):
813 raise ValueError(
"String is too large")
816 if check(obj, memoryview):
819 raise ValueError(
"Memoryview is too large")
822 if check(obj, float):
826 if check(obj, (ExtType, Timestamp)):
827 if check(obj, Timestamp):
855 if check(obj, list_types):
859 self.
_pack(obj[i], nest_limit - 1)
871 if not default_used
and self.
_default is not None:
876 if self.
_datetime and check(obj, _DateTime):
877 raise ValueError(
"Cannot serialize %r where tzinfo=None" % (obj,))
879 raise TypeError(
"Cannot serialize %r" % (obj,))
919 raise TypeError(
"typecode must have int type.")
920 if not 0 <= typecode <= 127:
921 raise ValueError(
"typecode should be 0-127")
923 raise TypeError(
"data must have bytes type")
926 raise ValueError(
"Too large data")
953 raise ValueError(
"Array is too large")
962 raise ValueError(
"Dict is too large")
967 self.
_pack(k, nest_limit - 1)
968 self.
_pack(v, nest_limit - 1)
977 elif n <= 0xFFFFFFFF:
980 raise ValueError(
"Raw is too large")
989 elif n <= 0xFFFFFFFF:
992 raise ValueError(
"Bin is too large")
995 """Return internal buffer contents as bytes object"""
999 """Reset internal buffer.
1001 This method is useful only when autoreset=False.
1006 """Return view of internal buffer."""
1007 if USING_STRINGBUILDER
or PY2:
_pack(self, obj, nest_limit=DEFAULT_RECURSE_LIMIT, check=isinstance, check_type_strict=_check_type_strict)
_pack_array_header(self, n)
__init__(self, default=None, use_single_float=False, autoreset=True, use_bin_type=True, strict_types=False, datetime=False, unicode_errors=None)
pack_ext_type(self, typecode, data)
_pack_map_header(self, n)
pack_map_pairs(self, pairs)
pack_array_header(self, n)
_pack_map_pairs(self, n, pairs, nest_limit=DEFAULT_RECURSE_LIMIT)
_pack_raw_header(self, n)
_pack_bin_header(self, n)
_unpack(self, execute=EX_CONSTRUCT)
_reserve(self, n, raise_outofdata=True)
__init__(self, file_like=None, read_size=0, use_list=True, raw=False, timestamp=0, strict_map_key=True, object_hook=None, object_pairs_hook=None, list_hook=None, unicode_errors=None, max_buffer_size=100 *1024 *1024, ext_hook=ExtType, max_str_len=-1, max_bin_len=-1, max_array_len=-1, max_map_len=-1, max_ext_len=-1)
_read(self, n, raise_outofdata=True)
_check_type_strict(obj, t, type=type, tuple=tuple)
_get_data_from_buffer(obj)