summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorINADA Naoki <inada-n@klab.com>2012-12-06 22:13:28 +0900
committerINADA Naoki <inada-n@klab.com>2012-12-06 22:13:28 +0900
commitc1d15df87ac47e04864cf69faaef0ea412d85788 (patch)
tree084d97dc29f4d2c91364f167344461ef953b86da
parent53b67f14496d71b3aa896d3311367401dc3c00a3 (diff)
parentdf4f23779d14f2b41e9a5ecca0a06e21385cc603 (diff)
downloadmsgpack-python-c1d15df87ac47e04864cf69faaef0ea412d85788.tar.gz
Add Unpacker.read_bytes().
It reads from inner buffer without unpacking. Merge remote-tracking branch 'jnothman/patch-2' Conflicts: msgpack/_msgpack.pyx
-rw-r--r--msgpack/_msgpack.pyx10
-rw-r--r--test/test_sequnpack.py16
2 files changed, 26 insertions, 0 deletions
diff --git a/msgpack/_msgpack.pyx b/msgpack/_msgpack.pyx
index a599846..38940f0 100644
--- a/msgpack/_msgpack.pyx
+++ b/msgpack/_msgpack.pyx
@@ -501,6 +501,16 @@ cdef class Unpacker(object):
else:
raise ValueError("Unpack failed: error = %d" % (ret,))
+ def read_bytes(self, Py_ssize_t nbytes):
+ """read a specified number of raw bytes from the stream"""
+ cdef size_t nread
+ nread = min(self.buf_tail - self.buf_head, nbytes)
+ ret = PyBytes_FromStringAndSize(self.buf + self.buf_head, nread)
+ self.buf_head += nread
+ if len(ret) < nbytes and self.file_like is not None:
+ ret += self.file_like.read(nbytes - len(ret))
+ return ret
+
def unpack(self, object write_bytes=None):
"""
unpack one object
diff --git a/test/test_sequnpack.py b/test/test_sequnpack.py
index dac36a8..769f3ff 100644
--- a/test/test_sequnpack.py
+++ b/test/test_sequnpack.py
@@ -1,6 +1,7 @@
#!/usr/bin/env python
# coding: utf-8
+import six
from msgpack import Unpacker, BufferFull
import nose
@@ -56,5 +57,20 @@ def test_maxbuffersize():
assert ord('b') == next(unpacker)
+def test_readbytes():
+ unpacker = Unpacker(read_size=3)
+ unpacker.feed(b'foobar')
+ assert unpacker.unpack() == ord(b'f')
+ assert unpacker.read_bytes(3) == b'oob'
+ assert unpacker.unpack() == ord(b'a')
+ assert unpacker.unpack() == ord(b'r')
+
+ # Test buffer refill
+ unpacker = Unpacker(six.BytesIO(b'foobar'), read_size=3)
+ assert unpacker.unpack() == ord(b'f')
+ assert unpacker.read_bytes(3) == b'oob'
+ assert unpacker.unpack() == ord(b'a')
+ assert unpacker.unpack() == ord(b'r')
+
if __name__ == '__main__':
nose.main()