8000 implement unpack_one also for the cython version, and add a test for it · zhurs/msgpack-python@ff85838 · GitHub
[go: up one dir, main page]

Skip to content

Commit ff85838

Browse files
committed
implement unpack_one also for the cython version, and add a test for it
1 parent a7485ec commit ff85838

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

msgpack/_unpacker.pyx

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,24 @@ cdef class Unpacker(object):
359359
"""
360360
return self._unpack(unpack_construct, write_bytes)
361361

362+
def unpack_one(self, object write_bytes=None):
363+
"""
364+
unpack one object
365+
366+
If write_bytes is not None, it will be called with parts of the raw
367+
message as it is unpacked.
368+
369+
Raises `UnpackValueError` if there are no more bytes to unpack.
370+
Raises ``ExtraData`` if there are still bytes left after the unpacking.
371+
"""
372+
try:
373+
result = self.unpack()
374+
except OutOfData:
375+
raise UnpackValueError("Data is not enough")
376+
if self.buf_head < self.buf_tail:
377+
raise ExtraData(result, self.buf[self.buf_head:])
378+
return result
379+
362380
def skip(self, object write_bytes=None):
363381
"""
364382
read and ignore one object, returning None

test/test_sequnpack.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
#!/usr/bin/env python
22
# coding: utf-8
33

4+
import py
45
import six
56
from msgpack import Unpacker, BufferFull
6-
from msgpack.exceptions import OutOfData
7+
from msgpack.exceptions import OutOfData, ExtraData, UnpackValueError
78
from pytest import raises
89

910

@@ -85,3 +86,15 @@ def test_readbytes():
8586
assert unpacker.unpack() == ord(b'a')
8687
assert unpacker.unpack() == ord(b'r')
8788

89+
def test_unpack_one():
90+
unpacker = Unpacker()
91+
unpacker.feed('\xda\x00\x03abc')
92+
assert unpacker.unpack_one() == 'abc'
93+
#
94+
unpacker = Unpacker()
95+
unpacker.feed('\xda\x00\x03abcd')
96+
py.test.raises(ExtraData, "unpacker.unpack_one()")
97+
#
98+
unpacker = Unpacker()
99+
unpacker.feed('\xda\x00\x03ab')
100+
py.test.raises(UnpackValueError, "unpacker.unpack_one()")

0 commit comments

Comments
 (0)
0