You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

971 lines
35 KiB

4 years ago
  1. """Fallback pure Python implementation of msgpack"""
  2. import sys
  3. import struct
  4. import warnings
  5. if sys.version_info[0] == 3:
  6. PY3 = True
  7. int_types = int
  8. Unicode = str
  9. xrange = range
  10. def dict_iteritems(d):
  11. return d.items()
  12. else:
  13. PY3 = False
  14. int_types = (int, long)
  15. Unicode = unicode
  16. def dict_iteritems(d):
  17. return d.iteritems()
  18. if hasattr(sys, 'pypy_version_info'):
  19. # cStringIO is slow on PyPy, StringIO is faster. However: PyPy's own
  20. # StringBuilder is fastest.
  21. from __pypy__ import newlist_hint
  22. try:
  23. from __pypy__.builders import BytesBuilder as StringBuilder
  24. except ImportError:
  25. from __pypy__.builders import StringBuilder
  26. USING_STRINGBUILDER = True
  27. class StringIO(object):
  28. def __init__(self, s=b''):
  29. if s:
  30. self.builder = StringBuilder(len(s))
  31. self.builder.append(s)
  32. else:
  33. self.builder = StringBuilder()
  34. def write(self, s):
  35. if isinstance(s, memoryview):
  36. s = s.tobytes()
  37. elif isinstance(s, bytearray):
  38. s = bytes(s)
  39. self.builder.append(s)
  40. def getvalue(self):
  41. return self.builder.build()
  42. else:
  43. USING_STRINGBUILDER = False
  44. from io import BytesIO as StringIO
  45. newlist_hint = lambda size: []
  46. from msgpack.exceptions import (
  47. BufferFull,
  48. OutOfData,
  49. UnpackValueError,
  50. PackValueError,
  51. PackOverflowError,
  52. ExtraData)
  53. from msgpack import ExtType
  54. EX_SKIP = 0
  55. EX_CONSTRUCT = 1
  56. EX_READ_ARRAY_HEADER = 2
  57. EX_READ_MAP_HEADER = 3
  58. TYPE_IMMEDIATE = 0
  59. TYPE_ARRAY = 1
  60. TYPE_MAP = 2
  61. TYPE_RAW = 3
  62. TYPE_BIN = 4
  63. TYPE_EXT = 5
  64. DEFAULT_RECURSE_LIMIT = 511
  65. def _check_type_strict(obj, t, type=type, tuple=tuple):
  66. if type(t) is tuple:
  67. return type(obj) in t
  68. else:
  69. return type(obj) is t
  70. def _get_data_from_buffer(obj):
  71. try:
  72. view = memoryview(obj)
  73. except TypeError:
  74. # try to use legacy buffer protocol if 2.7, otherwise re-raise
  75. if not PY3:
  76. view = memoryview(buffer(obj))
  77. warnings.warn("using old buffer interface to unpack %s; "
  78. "this leads to unpacking errors if slicing is used and "
  79. "will be removed in a future version" % type(obj),
  80. RuntimeWarning)
  81. else:
  82. raise
  83. if view.itemsize != 1:
  84. raise ValueError("cannot unpack from multi-byte object")
  85. return view
  86. def unpack(stream, **kwargs):
  87. warnings.warn(
  88. "Direct calling implementation's unpack() is deprecated, Use msgpack.unpack() or unpackb() instead.",
  89. PendingDeprecationWarning)
  90. data = stream.read()
  91. return unpackb(data, **kwargs)
  92. def unpackb(packed, **kwargs):
  93. """
  94. Unpack an object from `packed`.
  95. Raises `ExtraData` when `packed` contains extra bytes.
  96. See :class:`Unpacker` for options.
  97. """
  98. unpacker = Unpacker(None, **kwargs)
  99. unpacker.feed(packed)
  100. try:
  101. ret = unpacker._unpack()
  102. except OutOfData:
  103. raise UnpackValueError("Data is not enough.")
  104. if unpacker._got_extradata():
  105. raise ExtraData(ret, unpacker._get_extradata())
  106. return ret
  107. class Unpacker(object):
  108. """Streaming unpacker.
  109. arguments:
  110. :param file_like:
  111. File-like object having `.read(n)` method.
  112. If specified, unpacker reads serialized data from it and :meth:`feed()` is not usable.
  113. :param int read_size:
  114. Used as `file_like.read(read_size)`. (default: `min(16*1024, max_buffer_size)`)
  115. :param bool use_list:
  116. If true, unpack msgpack array to Python list.
  117. Otherwise, unpack to Python tuple. (default: True)
  118. :param bool raw:
  119. If true, unpack msgpack raw to Python bytes (default).
  120. Otherwise, unpack to Python str (or unicode on Python 2) by decoding
  121. with UTF-8 encoding (recommended).
  122. Currently, the default is true, but it will be changed to false in
  123. near future. So you must specify it explicitly for keeping backward
  124. compatibility.
  125. *encoding* option which is deprecated overrides this option.
  126. :param callable object_hook:
  127. When specified, it should be callable.
  128. Unpacker calls it with a dict argument after unpacking msgpack map.
  129. (See also simplejson)
  130. :param callable object_pairs_hook:
  131. When specified, it should be callable.
  132. Unpacker calls it with a list of key-value pairs after unpacking msgpack map.
  133. (See also simplejson)
  134. :param str encoding:
  135. Encoding used for decoding msgpack raw.
  136. If it is None (default), msgpack raw is deserialized to Python bytes.
  137. :param str unicode_errors:
  138. (deprecated) Used for decoding msgpack raw with *encoding*.
  139. (default: `'strict'`)
  140. :param int max_buffer_size:
  141. Limits size of data waiting unpacked. 0 means system's INT_MAX (default).
  142. Raises `BufferFull` exception when it is insufficient.
  143. You should set this parameter when unpacking data from untrusted source.
  144. :param int max_str_len:
  145. Limits max length of str. (default: 2**31-1)
  146. :param int max_bin_len:
  147. Limits max length of bin. (default: 2**31-1)
  148. :param int max_array_len:
  149. Limits max length of array. (default: 2**31-1)
  150. :param int max_map_len:
  151. Limits max length of map. (default: 2**31-1)
  152. example of streaming deserialize from file-like object::
  153. unpacker = Unpacker(file_like, raw=False)
  154. for o in unpacker:
  155. process(o)
  156. example of streaming deserialize from socket::
  157. unpacker = Unpacker(raw=False)
  158. while True:
  159. buf = sock.recv(1024**2)
  160. if not buf:
  161. break
  162. unpacker.feed(buf)
  163. for o in unpacker:
  164. process(o)
  165. """
  166. def __init__(self, file_like=None, read_size=0, use_list=True, raw=True,
  167. object_hook=None, object_pairs_hook=None, list_hook=None,
  168. encoding=None, unicode_errors=None, max_buffer_size=0,
  169. ext_hook=ExtType,
  170. max_str_len=2147483647, # 2**32-1
  171. max_bin_len=2147483647,
  172. max_array_len=2147483647,
  173. max_map_len=2147483647,
  174. max_ext_len=2147483647):
  175. if encoding is not None:
  176. warnings.warn(
  177. "encoding is deprecated, Use raw=False instead.",
  178. PendingDeprecationWarning)
  179. if unicode_errors is None:
  180. unicode_errors = 'strict'
  181. if file_like is None:
  182. self._feeding = True
  183. else:
  184. if not callable(file_like.read):
  185. raise TypeError("`file_like.read` must be callable")
  186. self.file_like = file_like
  187. self._feeding = False
  188. #: array of bytes fed.
  189. self._buffer = bytearray()
  190. #: Which position we currently reads
  191. self._buff_i = 0
  192. # When Unpacker is used as an iterable, between the calls to next(),
  193. # the buffer is not "consumed" completely, for efficiency sake.
  194. # Instead, it is done sloppily. To make sure we raise BufferFull at
  195. # the correct moments, we have to keep track of how sloppy we were.
  196. # Furthermore, when the buffer is incomplete (that is: in the case
  197. # we raise an OutOfData) we need to rollback the buffer to the correct
  198. # state, which _buf_checkpoint records.
  199. self._buf_checkpoint = 0
  200. self._max_buffer_size = max_buffer_size or 2**31-1
  201. if read_size > self._max_buffer_size:
  202. raise ValueError("read_size must be smaller than max_buffer_size")
  203. self._read_size = read_size or min(self._max_buffer_size, 16*1024)
  204. self._raw = bool(raw)
  205. self._encoding = encoding
  206. self._unicode_errors = unicode_errors
  207. self._use_list = use_list
  208. self._list_hook = list_hook
  209. self._object_hook = object_hook
  210. self._object_pairs_hook = object_pairs_hook
  211. self._ext_hook = ext_hook
  212. self._max_str_len = max_str_len
  213. self._max_bin_len = max_bin_len
  214. self._max_array_len = max_array_len
  215. self._max_map_len = max_map_len
  216. self._max_ext_len = max_ext_len
  217. self._stream_offset = 0
  218. if list_hook is not None and not callable(list_hook):
  219. raise TypeError('`list_hook` is not callable')
  220. if object_hook is not None and not callable(object_hook):
  221. raise TypeError('`object_hook` is not callable')
  222. if object_pairs_hook is not None and not callable(object_pairs_hook):
  223. raise TypeError('`object_pairs_hook` is not callable')
  224. if object_hook is not None and object_pairs_hook is not None:
  225. raise TypeError("object_pairs_hook and object_hook are mutually "
  226. "exclusive")
  227. if not callable(ext_hook):
  228. raise TypeError("`ext_hook` is not callable")
  229. def feed(self, next_bytes):
  230. assert self._feeding
  231. view = _get_data_from_buffer(next_bytes)
  232. if (len(self._buffer) - self._buff_i + len(view) > self._max_buffer_size):
  233. raise BufferFull
  234. # Strip buffer before checkpoint before reading file.
  235. if self._buf_checkpoint > 0:
  236. del self._buffer[:self._buf_checkpoint]
  237. self._buff_i -= self._buf_checkpoint
  238. self._buf_checkpoint = 0
  239. self._buffer += view
  240. def _consume(self):
  241. """ Gets rid of the used parts of the buffer. """
  242. self._stream_offset += self._buff_i - self._buf_checkpoint
  243. self._buf_checkpoint = self._buff_i
  244. def _got_extradata(self):
  245. return self._buff_i < len(self._buffer)
  246. def _get_extradata(self):
  247. return self._buffer[self._buff_i:]
  248. def read_bytes(self, n):
  249. return self._read(n)
  250. def _read(self, n):
  251. # (int) -> bytearray
  252. self._reserve(n)
  253. i = self._buff_i
  254. self._buff_i = i+n
  255. return self._buffer[i:i+n]
  256. def _reserve(self, n):
  257. remain_bytes = len(self._buffer) - self._buff_i - n
  258. # Fast path: buffer has n bytes already
  259. if remain_bytes >= 0:
  260. return
  261. if self._feeding:
  262. self._buff_i = self._buf_checkpoint
  263. raise OutOfData
  264. # Strip buffer before checkpoint before reading file.
  265. if self._buf_checkpoint > 0:
  266. del self._buffer[:self._buf_checkpoint]
  267. self._buff_i -= self._buf_checkpoint
  268. self._buf_checkpoint = 0
  269. # Read from file
  270. remain_bytes = -remain_bytes
  271. while remain_bytes > 0:
  272. to_read_bytes = max(self._read_size, remain_bytes)
  273. read_data = self.file_like.read(to_read_bytes)
  274. if not read_data:
  275. break
  276. assert isinstance(read_data, bytes)
  277. self._buffer += read_data
  278. remain_bytes -= len(read_data)
  279. if len(self._buffer) < n + self._buff_i:
  280. self._buff_i = 0 # rollback
  281. raise OutOfData
  282. def _read_header(self, execute=EX_CONSTRUCT):
  283. typ = TYPE_IMMEDIATE
  284. n = 0
  285. obj = None
  286. self._reserve(1)
  287. b = self._buffer[self._buff_i]
  288. self._buff_i += 1
  289. if b & 0b10000000 == 0:
  290. obj = b
  291. elif b & 0b11100000 == 0b11100000:
  292. obj = -1 - (b ^ 0xff)
  293. elif b & 0b11100000 == 0b10100000:
  294. n = b & 0b00011111
  295. typ = TYPE_RAW
  296. if n > self._max_str_len:
  297. raise UnpackValueError("%s exceeds max_str_len(%s)", n, self._max_str_len)
  298. obj = self._read(n)
  299. elif b & 0b11110000 == 0b10010000:
  300. n = b & 0b00001111
  301. typ = TYPE_ARRAY
  302. if n > self._max_array_len:
  303. raise UnpackValueError("%s exceeds max_array_len(%s)", n, self._max_array_len)
  304. elif b & 0b11110000 == 0b10000000:
  305. n = b & 0b00001111
  306. typ = TYPE_MAP
  307. if n > self._max_map_len:
  308. raise UnpackValueError("%s exceeds max_map_len(%s)", n, self._max_map_len)
  309. elif b == 0xc0:
  310. obj = None
  311. elif b == 0xc2:
  312. obj = False
  313. elif b == 0xc3:
  314. obj = True
  315. elif b == 0xc4:
  316. typ = TYPE_BIN
  317. self._reserve(1)
  318. n = self._buffer[self._buff_i]
  319. self._buff_i += 1
  320. if n > self._max_bin_len:
  321. raise UnpackValueError("%s exceeds max_bin_len(%s)" % (n, self._max_bin_len))
  322. obj = self._read(n)
  323. elif b == 0xc5:
  324. typ = TYPE_BIN
  325. self._reserve(2)
  326. n = struct.unpack_from(">H", self._buffer, self._buff_i)[0]
  327. self._buff_i += 2
  328. if n > self._max_bin_len:
  329. raise UnpackValueError("%s exceeds max_bin_len(%s)" % (n, self._max_bin_len))
  330. obj = self._read(n)
  331. elif b == 0xc6:
  332. typ = TYPE_BIN
  333. self._reserve(4)
  334. n = struct.unpack_from(">I", self._buffer, self._buff_i)[0]
  335. self._buff_i += 4
  336. if n > self._max_bin_len:
  337. raise UnpackValueError("%s exceeds max_bin_len(%s)" % (n, self._max_bin_len))
  338. obj = self._read(n)
  339. elif b == 0xc7: # ext 8
  340. typ = TYPE_EXT
  341. self._reserve(2)
  342. L, n = struct.unpack_from('Bb', self._buffer, self._buff_i)
  343. self._buff_i += 2
  344. if L > self._max_ext_len:
  345. raise UnpackValueError("%s exceeds max_ext_len(%s)" % (L, self._max_ext_len))
  346. obj = self._read(L)
  347. elif b == 0xc8: # ext 16
  348. typ = TYPE_EXT
  349. self._reserve(3)
  350. L, n = struct.unpack_from('>Hb', self._buffer, self._buff_i)
  351. self._buff_i += 3
  352. if L > self._max_ext_len:
  353. raise UnpackValueError("%s exceeds max_ext_len(%s)" % (L, self._max_ext_len))
  354. obj = self._read(L)
  355. elif b == 0xc9: # ext 32
  356. typ = TYPE_EXT
  357. self._reserve(5)
  358. L, n = struct.unpack_from('>Ib', self._buffer, self._buff_i)
  359. self._buff_i += 5
  360. if L > self._max_ext_len:
  361. raise UnpackValueError("%s exceeds max_ext_len(%s)" % (L, self._max_ext_len))
  362. obj = self._read(L)
  363. elif b == 0xca:
  364. self._reserve(4)
  365. obj = struct.unpack_from(">f", self._buffer, self._buff_i)[0]
  366. self._buff_i += 4
  367. elif b == 0xcb:
  368. self._reserve(8)
  369. obj = struct.unpack_from(">d", self._buffer, self._buff_i)[0]
  370. self._buff_i += 8
  371. elif b == 0xcc:
  372. self._reserve(1)
  373. obj = self._buffer[self._buff_i]
  374. self._buff_i += 1
  375. elif b == 0xcd:
  376. self._reserve(2)
  377. obj = struct.unpack_from(">H", self._buffer, self._buff_i)[0]
  378. self._buff_i += 2
  379. elif b == 0xce:
  380. self._reserve(4)
  381. obj = struct.unpack_from(">I", self._buffer, self._buff_i)[0]
  382. self._buff_i += 4
  383. elif b == 0xcf:
  384. self._reserve(8)
  385. obj = struct.unpack_from(">Q", self._buffer, self._buff_i)[0]
  386. self._buff_i += 8
  387. elif b == 0xd0:
  388. self._reserve(1)
  389. obj = struct.unpack_from("b", self._buffer, self._buff_i)[0]
  390. self._buff_i += 1
  391. elif b == 0xd1:
  392. self._reserve(2)
  393. obj = struct.unpack_from(">h", self._buffer, self._buff_i)[0]
  394. self._buff_i += 2
  395. elif b == 0xd2:
  396. self._reserve(4)
  397. obj = struct.unpack_from(">i", self._buffer, self._buff_i)[0]
  398. self._buff_i += 4
  399. elif b == 0xd3:
  400. self._reserve(8)
  401. obj = struct.unpack_from(">q", self._buffer, self._buff_i)[0]
  402. self._buff_i += 8
  403. elif b == 0xd4: # fixext 1
  404. typ = TYPE_EXT
  405. if self._max_ext_len < 1:
  406. raise UnpackValueError("%s exceeds max_ext_len(%s)" % (1, self._max_ext_len))
  407. self._reserve(2)
  408. n, obj = struct.unpack_from("b1s", self._buffer, self._buff_i)
  409. self._buff_i += 2
  410. elif b == 0xd5: # fixext 2
  411. typ = TYPE_EXT
  412. if self._max_ext_len < 2:
  413. raise UnpackValueError("%s exceeds max_ext_len(%s)" % (2, self._max_ext_len))
  414. self._reserve(3)
  415. n, obj = struct.unpack_from("b2s", self._buffer, self._buff_i)
  416. self._buff_i += 3
  417. elif b == 0xd6: # fixext 4
  418. typ = TYPE_EXT
  419. if self._max_ext_len < 4:
  420. raise UnpackValueError("%s exceeds max_ext_len(%s)" % (4, self._max_ext_len))
  421. self._reserve(5)
  422. n, obj = struct.unpack_from("b4s", self._buffer, self._buff_i)
  423. self._buff_i += 5
  424. elif b == 0xd7: # fixext 8
  425. typ = TYPE_EXT
  426. if self._max_ext_len < 8:
  427. raise UnpackValueError("%s exceeds max_ext_len(%s)" % (8, self._max_ext_len))
  428. self._reserve(9)
  429. n, obj = struct.unpack_from("b8s", self._buffer, self._buff_i)
  430. self._buff_i += 9
  431. elif b == 0xd8: # fixext 16
  432. typ = TYPE_EXT
  433. if self._max_ext_len < 16:
  434. raise UnpackValueError("%s exceeds max_ext_len(%s)" % (16, self._max_ext_len))
  435. self._reserve(17)
  436. n, obj = struct.unpack_from("b16s", self._buffer, self._buff_i)
  437. self._buff_i += 17
  438. elif b == 0xd9:
  439. typ = TYPE_RAW
  440. self._reserve(1)
  441. n = self._buffer[self._buff_i]
  442. self._buff_i += 1
  443. if n > self._max_str_len:
  444. raise UnpackValueError("%s exceeds max_str_len(%s)", n, self._max_str_len)
  445. obj = self._read(n)
  446. elif b == 0xda:
  447. typ = TYPE_RAW
  448. self._reserve(2)
  449. n, = struct.unpack_from(">H", self._buffer, self._buff_i)
  450. self._buff_i += 2
  451. if n > self._max_str_len:
  452. raise UnpackValueError("%s exceeds max_str_len(%s)", n, self._max_str_len)
  453. obj = self._read(n)
  454. elif b == 0xdb:
  455. typ = TYPE_RAW
  456. self._reserve(4)
  457. n, = struct.unpack_from(">I", self._buffer, self._buff_i)
  458. self._buff_i += 4
  459. if n > self._max_str_len:
  460. raise UnpackValueError("%s exceeds max_str_len(%s)", n, self._max_str_len)
  461. obj = self._read(n)
  462. elif b == 0xdc:
  463. typ = TYPE_ARRAY
  464. self._reserve(2)
  465. n, = struct.unpack_from(">H", self._buffer, self._buff_i)
  466. self._buff_i += 2
  467. if n > self._max_array_len:
  468. raise UnpackValueError("%s exceeds max_array_len(%s)", n, self._max_array_len)
  469. elif b == 0xdd:
  470. typ = TYPE_ARRAY
  471. self._reserve(4)
  472. n, = struct.unpack_from(">I", self._buffer, self._buff_i)
  473. self._buff_i += 4
  474. if n > self._max_array_len:
  475. raise UnpackValueError("%s exceeds max_array_len(%s)", n, self._max_array_len)
  476. elif b == 0xde:
  477. self._reserve(2)
  478. n, = struct.unpack_from(">H", self._buffer, self._buff_i)
  479. self._buff_i += 2
  480. if n > self._max_map_len:
  481. raise UnpackValueError("%s exceeds max_map_len(%s)", n, self._max_map_len)
  482. typ = TYPE_MAP
  483. elif b == 0xdf:
  484. self._reserve(4)
  485. n, = struct.unpack_from(">I", self._buffer, self._buff_i)
  486. self._buff_i += 4
  487. if n > self._max_map_len:
  488. raise UnpackValueError("%s exceeds max_map_len(%s)", n, self._max_map_len)
  489. typ = TYPE_MAP
  490. else:
  491. raise UnpackValueError("Unknown header: 0x%x" % b)
  492. return typ, n, obj
  493. def _unpack(self, execute=EX_CONSTRUCT):
  494. typ, n, obj = self._read_header(execute)
  495. if execute == EX_READ_ARRAY_HEADER:
  496. if typ != TYPE_ARRAY:
  497. raise UnpackValueError("Expected array")
  498. return n
  499. if execute == EX_READ_MAP_HEADER:
  500. if typ != TYPE_MAP:
  501. raise UnpackValueError("Expected map")
  502. return n
  503. # TODO should we eliminate the recursion?
  504. if typ == TYPE_ARRAY:
  505. if execute == EX_SKIP:
  506. for i in xrange(n):
  507. # TODO check whether we need to call `list_hook`
  508. self._unpack(EX_SKIP)
  509. return
  510. ret = newlist_hint(n)
  511. for i in xrange(n):
  512. ret.append(self._unpack(EX_CONSTRUCT))
  513. if self._list_hook is not None:
  514. ret = self._list_hook(ret)
  515. # TODO is the interaction between `list_hook` and `use_list` ok?
  516. return ret if self._use_list else tuple(ret)
  517. if typ == TYPE_MAP:
  518. if execute == EX_SKIP:
  519. for i in xrange(n):
  520. # TODO check whether we need to call hooks
  521. self._unpack(EX_SKIP)
  522. self._unpack(EX_SKIP)
  523. return
  524. if self._object_pairs_hook is not None:
  525. ret = self._object_pairs_hook(
  526. (self._unpack(EX_CONSTRUCT),
  527. self._unpack(EX_CONSTRUCT))
  528. for _ in xrange(n))
  529. else:
  530. ret = {}
  531. for _ in xrange(n):
  532. key = self._unpack(EX_CONSTRUCT)
  533. ret[key] = self._unpack(EX_CONSTRUCT)
  534. if self._object_hook is not None:
  535. ret = self._object_hook(ret)
  536. return ret
  537. if execute == EX_SKIP:
  538. return
  539. if typ == TYPE_RAW:
  540. if self._encoding is not None:
  541. obj = obj.decode(self._encoding, self._unicode_errors)
  542. elif self._raw:
  543. obj = bytes(obj)
  544. else:
  545. obj = obj.decode('utf_8')
  546. return obj
  547. if typ == TYPE_EXT:
  548. return self._ext_hook(n, bytes(obj))
  549. if typ == TYPE_BIN:
  550. return bytes(obj)
  551. assert typ == TYPE_IMMEDIATE
  552. return obj
  553. def __iter__(self):
  554. return self
  555. def __next__(self):
  556. try:
  557. ret = self._unpack(EX_CONSTRUCT)
  558. self._consume()
  559. return ret
  560. except OutOfData:
  561. self._consume()
  562. raise StopIteration
  563. next = __next__
  564. def skip(self, write_bytes=None):
  565. self._unpack(EX_SKIP)
  566. if write_bytes is not None:
  567. warnings.warn("`write_bytes` option is deprecated. Use `.tell()` instead.", DeprecationWarning)
  568. write_bytes(self._buffer[self._buf_checkpoint:self._buff_i])
  569. self._consume()
  570. def unpack(self, write_bytes=None):
  571. ret = self._unpack(EX_CONSTRUCT)
  572. if write_bytes is not None:
  573. warnings.warn("`write_bytes` option is deprecated. Use `.tell()` instead.", DeprecationWarning)
  574. write_bytes(self._buffer[self._buf_checkpoint:self._buff_i])
  575. self._consume()
  576. return ret
  577. def read_array_header(self, write_bytes=None):
  578. ret = self._unpack(EX_READ_ARRAY_HEADER)
  579. if write_bytes is not None:
  580. warnings.warn("`write_bytes` option is deprecated. Use `.tell()` instead.", DeprecationWarning)
  581. write_bytes(self._buffer[self._buf_checkpoint:self._buff_i])
  582. self._consume()
  583. return ret
  584. def read_map_header(self, write_bytes=None):
  585. ret = self._unpack(EX_READ_MAP_HEADER)
  586. if write_bytes is not None:
  587. warnings.warn("`write_bytes` option is deprecated. Use `.tell()` instead.", DeprecationWarning)
  588. write_bytes(self._buffer[self._buf_checkpoint:self._buff_i])
  589. self._consume()
  590. return ret
  591. def tell(self):
  592. return self._stream_offset
  593. class Packer(object):
  594. """
  595. MessagePack Packer
  596. usage:
  597. packer = Packer()
  598. astream.write(packer.pack(a))
  599. astream.write(packer.pack(b))
  600. Packer's constructor has some keyword arguments:
  601. :param callable default:
  602. Convert user type to builtin type that Packer supports.
  603. See also simplejson's document.
  604. :param bool use_single_float:
  605. Use single precision float type for float. (default: False)
  606. :param bool autoreset:
  607. Reset buffer after each pack and return its content as `bytes`. (default: True).
  608. If set this to false, use `bytes()` to get content and `.reset()` to clear buffer.
  609. :param bool use_bin_type:
  610. Use bin type introduced in msgpack spec 2.0 for bytes.
  611. It also enables str8 type for unicode.
  612. :param bool strict_types:
  613. If set to true, types will be checked to be exact. Derived classes
  614. from serializeable types will not be serialized and will be
  615. treated as unsupported type and forwarded to default.
  616. Additionally tuples will not be serialized as lists.
  617. This is useful when trying to implement accurate serialization
  618. for python types.
  619. :param str encoding:
  620. (deprecated) Convert unicode to bytes with this encoding. (default: 'utf-8')
  621. :param str unicode_errors:
  622. Error handler for encoding unicode. (default: 'strict')
  623. """
  624. def __init__(self, default=None, encoding=None, unicode_errors=None,
  625. use_single_float=False, autoreset=True, use_bin_type=False,
  626. strict_types=False):
  627. if encoding is None:
  628. encoding = 'utf_8'
  629. else:
  630. warnings.warn(
  631. "encoding is deprecated, Use raw=False instead.",
  632. PendingDeprecationWarning)
  633. if unicode_errors is None:
  634. unicode_errors = 'strict'
  635. self._strict_types = strict_types
  636. self._use_float = use_single_float
  637. self._autoreset = autoreset
  638. self._use_bin_type = use_bin_type
  639. self._encoding = encoding
  640. self._unicode_errors = unicode_errors
  641. self._buffer = StringIO()
  642. if default is not None:
  643. if not callable(default):
  644. raise TypeError("default must be callable")
  645. self._default = default
  646. def _pack(self, obj, nest_limit=DEFAULT_RECURSE_LIMIT,
  647. check=isinstance, check_type_strict=_check_type_strict):
  648. default_used = False
  649. if self._strict_types:
  650. check = check_type_strict
  651. list_types = list
  652. else:
  653. list_types = (list, tuple)
  654. while True:
  655. if nest_limit < 0:
  656. raise PackValueError("recursion limit exceeded")
  657. if obj is None:
  658. return self._buffer.write(b"\xc0")
  659. if check(obj, bool):
  660. if obj:
  661. return self._buffer.write(b"\xc3")
  662. return self._buffer.write(b"\xc2")
  663. if check(obj, int_types):
  664. if 0 <= obj < 0x80:
  665. return self._buffer.write(struct.pack("B", obj))
  666. if -0x20 <= obj < 0:
  667. return self._buffer.write(struct.pack("b", obj))
  668. if 0x80 <= obj <= 0xff:
  669. return self._buffer.write(struct.pack("BB", 0xcc, obj))
  670. if -0x80 <= obj < 0:
  671. return self._buffer.write(struct.pack(">Bb", 0xd0, obj))
  672. if 0xff < obj <= 0xffff:
  673. return self._buffer.write(struct.pack(">BH", 0xcd, obj))
  674. if -0x8000 <= obj < -0x80:
  675. return self._buffer.write(struct.pack(">Bh", 0xd1, obj))
  676. if 0xffff < obj <= 0xffffffff:
  677. return self._buffer.write(struct.pack(">BI", 0xce, obj))
  678. if -0x80000000 <= obj < -0x8000:
  679. return self._buffer.write(struct.pack(">Bi", 0xd2, obj))
  680. if 0xffffffff < obj <= 0xffffffffffffffff:
  681. return self._buffer.write(struct.pack(">BQ", 0xcf, obj))
  682. if -0x8000000000000000 <= obj < -0x80000000:
  683. return self._buffer.write(struct.pack(">Bq", 0xd3, obj))
  684. if not default_used and self._default is not None:
  685. obj = self._default(obj)
  686. default_used = True
  687. continue
  688. raise PackOverflowError("Integer value out of range")
  689. if check(obj, (bytes, bytearray)):
  690. n = len(obj)
  691. if n >= 2**32:
  692. raise PackValueError("%s is too large" % type(obj).__name__)
  693. self._pack_bin_header(n)
  694. return self._buffer.write(obj)
  695. if check(obj, Unicode):
  696. if self._encoding is None:
  697. raise TypeError(
  698. "Can't encode unicode string: "
  699. "no encoding is specified")
  700. obj = obj.encode(self._encoding, self._unicode_errors)
  701. n = len(obj)
  702. if n >= 2**32:
  703. raise PackValueError("String is too large")
  704. self._pack_raw_header(n)
  705. return self._buffer.write(obj)
  706. if check(obj, memoryview):
  707. n = len(obj) * obj.itemsize
  708. if n >= 2**32:
  709. raise PackValueError("Memoryview is too large")
  710. self._pack_bin_header(n)
  711. return self._buffer.write(obj)
  712. if check(obj, float):
  713. if self._use_float:
  714. return self._buffer.write(struct.pack(">Bf", 0xca, obj))
  715. return self._buffer.write(struct.pack(">Bd", 0xcb, obj))
  716. if check(obj, ExtType):
  717. code = obj.code
  718. data = obj.data
  719. assert isinstance(code, int)
  720. assert isinstance(data, bytes)
  721. L = len(data)
  722. if L == 1:
  723. self._buffer.write(b'\xd4')
  724. elif L == 2:
  725. self._buffer.write(b'\xd5')
  726. elif L == 4:
  727. self._buffer.write(b'\xd6')
  728. elif L == 8:
  729. self._buffer.write(b'\xd7')
  730. elif L == 16:
  731. self._buffer.write(b'\xd8')
  732. elif L <= 0xff:
  733. self._buffer.write(struct.pack(">BB", 0xc7, L))
  734. elif L <= 0xffff:
  735. self._buffer.write(struct.pack(">BH", 0xc8, L))
  736. else:
  737. self._buffer.write(struct.pack(">BI", 0xc9, L))
  738. self._buffer.write(struct.pack("b", code))
  739. self._buffer.write(data)
  740. return
  741. if check(obj, list_types):
  742. n = len(obj)
  743. self._pack_array_header(n)
  744. for i in xrange(n):
  745. self._pack(obj[i], nest_limit - 1)
  746. return
  747. if check(obj, dict):
  748. return self._pack_map_pairs(len(obj), dict_iteritems(obj),
  749. nest_limit - 1)
  750. if not default_used and self._default is not None:
  751. obj = self._default(obj)
  752. default_used = 1
  753. continue
  754. raise TypeError("Cannot serialize %r" % (obj, ))
  755. def pack(self, obj):
  756. try:
  757. self._pack(obj)
  758. except:
  759. self._buffer = StringIO() # force reset
  760. raise
  761. ret = self._buffer.getvalue()
  762. if self._autoreset:
  763. self._buffer = StringIO()
  764. elif USING_STRINGBUILDER:
  765. self._buffer = StringIO(ret)
  766. return ret
  767. def pack_map_pairs(self, pairs):
  768. self._pack_map_pairs(len(pairs), pairs)
  769. ret = self._buffer.getvalue()
  770. if self._autoreset:
  771. self._buffer = StringIO()
  772. elif USING_STRINGBUILDER:
  773. self._buffer = StringIO(ret)
  774. return ret
  775. def pack_array_header(self, n):
  776. if n >= 2**32:
  777. raise PackValueError
  778. self._pack_array_header(n)
  779. ret = self._buffer.getvalue()
  780. if self._autoreset:
  781. self._buffer = StringIO()
  782. elif USING_STRINGBUILDER:
  783. self._buffer = StringIO(ret)
  784. return ret
  785. def pack_map_header(self, n):
  786. if n >= 2**32:
  787. raise PackValueError
  788. self._pack_map_header(n)
  789. ret = self._buffer.getvalue()
  790. if self._autoreset:
  791. self._buffer = StringIO()
  792. elif USING_STRINGBUILDER:
  793. self._buffer = StringIO(ret)
  794. return ret
  795. def pack_ext_type(self, typecode, data):
  796. if not isinstance(typecode, int):
  797. raise TypeError("typecode must have int type.")
  798. if not 0 <= typecode <= 127:
  799. raise ValueError("typecode should be 0-127")
  800. if not isinstance(data, bytes):
  801. raise TypeError("data must have bytes type")
  802. L = len(data)
  803. if L > 0xffffffff:
  804. raise PackValueError("Too large data")
  805. if L == 1:
  806. self._buffer.write(b'\xd4')
  807. elif L == 2:
  808. self._buffer.write(b'\xd5')
  809. elif L == 4:
  810. self._buffer.write(b'\xd6')
  811. elif L == 8:
  812. self._buffer.write(b'\xd7')
  813. elif L == 16:
  814. self._buffer.write(b'\xd8')
  815. elif L <= 0xff:
  816. self._buffer.write(b'\xc7' + struct.pack('B', L))
  817. elif L <= 0xffff:
  818. self._buffer.write(b'\xc8' + struct.pack('>H', L))
  819. else:
  820. self._buffer.write(b'\xc9' + struct.pack('>I', L))
  821. self._buffer.write(struct.pack('B', typecode))
  822. self._buffer.write(data)
  823. def _pack_array_header(self, n):
  824. if n <= 0x0f:
  825. return self._buffer.write(struct.pack('B', 0x90 + n))
  826. if n <= 0xffff:
  827. return self._buffer.write(struct.pack(">BH", 0xdc, n))
  828. if n <= 0xffffffff:
  829. return self._buffer.write(struct.pack(">BI", 0xdd, n))
  830. raise PackValueError("Array is too large")
  831. def _pack_map_header(self, n):
  832. if n <= 0x0f:
  833. return self._buffer.write(struct.pack('B', 0x80 + n))
  834. if n <= 0xffff:
  835. return self._buffer.write(struct.pack(">BH", 0xde, n))
  836. if n <= 0xffffffff:
  837. return self._buffer.write(struct.pack(">BI", 0xdf, n))
  838. raise PackValueError("Dict is too large")
  839. def _pack_map_pairs(self, n, pairs, nest_limit=DEFAULT_RECURSE_LIMIT):
  840. self._pack_map_header(n)
  841. for (k, v) in pairs:
  842. self._pack(k, nest_limit - 1)
  843. self._pack(v, nest_limit - 1)
  844. def _pack_raw_header(self, n):
  845. if n <= 0x1f:
  846. self._buffer.write(struct.pack('B', 0xa0 + n))
  847. elif self._use_bin_type and n <= 0xff:
  848. self._buffer.write(struct.pack('>BB', 0xd9, n))
  849. elif n <= 0xffff:
  850. self._buffer.write(struct.pack(">BH", 0xda, n))
  851. elif n <= 0xffffffff:
  852. self._buffer.write(struct.pack(">BI", 0xdb, n))
  853. else:
  854. raise PackValueError('Raw is too large')
  855. def _pack_bin_header(self, n):
  856. if not self._use_bin_type:
  857. return self._pack_raw_header(n)
  858. elif n <= 0xff:
  859. return self._buffer.write(struct.pack('>BB', 0xc4, n))
  860. elif n <= 0xffff:
  861. return self._buffer.write(struct.pack(">BH", 0xc5, n))
  862. elif n <= 0xffffffff:
  863. return self._buffer.write(struct.pack(">BI", 0xc6, n))
  864. else:
  865. raise PackValueError('Bin is too large')
  866. def bytes(self):
  867. return self._buffer.getvalue()
  868. def reset(self):
  869. self._buffer = StringIO()