summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAntonio Cuni <anto.cuni@gmail.com>2013-10-19 01:49:03 +0200
committerAntonio Cuni <anto.cuni@gmail.com>2013-10-19 01:49:03 +0200
commitff858387d37d37ec4472f6b6ac7010d8f2b0744f (patch)
tree575f528e68130b8bcaac184a6d5cb2af278e2386
parenta7485eccb2e5fcebbd76612a658f2e18bdebe745 (diff)
downloadmsgpack-python-ff858387d37d37ec4472f6b6ac7010d8f2b0744f.tar.gz
implement unpack_one also for the cython version, and add a test for it
-rw-r--r--msgpack/_unpacker.pyx18
-rw-r--r--test/test_sequnpack.py15
2 files changed, 32 insertions, 1 deletions
diff --git a/msgpack/_unpacker.pyx b/msgpack/_unpacker.pyx
index 1f4dd85..e05b9ed 100644
--- a/msgpack/_unpacker.pyx
+++ b/msgpack/_unpacker.pyx
@@ -359,6 +359,24 @@ cdef class Unpacker(object):
"""
return self._unpack(unpack_construct, write_bytes)
+ def unpack_one(self, object write_bytes=None):
+ """
+ unpack one object
+
+ If write_bytes is not None, it will be called with parts of the raw
+ message as it is unpacked.
+
+ Raises `UnpackValueError` if there are no more bytes to unpack.
+ Raises ``ExtraData`` if there are still bytes left after the unpacking.
+ """
+ try:
+ result = self.unpack()
+ except OutOfData:
+ raise UnpackValueError("Data is not enough")
+ if self.buf_head < self.buf_tail:
+ raise ExtraData(result, self.buf[self.buf_head:])
+ return result
+
def skip(self, object write_bytes=None):
"""
read and ignore one object, returning None
diff --git a/test/test_sequnpack.py b/test/test_sequnpack.py
index 9db14ca..abc447a 100644
--- a/test/test_sequnpack.py
+++ b/test/test_sequnpack.py
@@ -1,9 +1,10 @@
#!/usr/bin/env python
# coding: utf-8
+import py
import six
from msgpack import Unpacker, BufferFull
-from msgpack.exceptions import OutOfData
+from msgpack.exceptions import OutOfData, ExtraData, UnpackValueError
from pytest import raises
@@ -85,3 +86,15 @@ def test_readbytes():
assert unpacker.unpack() == ord(b'a')
assert unpacker.unpack() == ord(b'r')
+def test_unpack_one():
+ unpacker = Unpacker()
+ unpacker.feed('\xda\x00\x03abc')
+ assert unpacker.unpack_one() == 'abc'
+ #
+ unpacker = Unpacker()
+ unpacker.feed('\xda\x00\x03abcd')
+ py.test.raises(ExtraData, "unpacker.unpack_one()")
+ #
+ unpacker = Unpacker()
+ unpacker.feed('\xda\x00\x03ab')
+ py.test.raises(UnpackValueError, "unpacker.unpack_one()")