Add Unpacker.read_bytes().

It reads from inner buffer without unpacking.

Merge remote-tracking branch 'jnothman/patch-2'

Conflicts:
	msgpack/_msgpack.pyx
This commit is contained in:
INADA Naoki 2012-12-06 22:13:28 +09:00
commit c1d15df87a
2 changed files with 26 additions and 0 deletions

View file

@ -501,6 +501,16 @@ cdef class Unpacker(object):
else: else:
raise ValueError("Unpack failed: error = %d" % (ret,)) 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): def unpack(self, object write_bytes=None):
""" """
unpack one object unpack one object

View file

@ -1,6 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# coding: utf-8 # coding: utf-8
import six
from msgpack import Unpacker, BufferFull from msgpack import Unpacker, BufferFull
import nose import nose
@ -56,5 +57,20 @@ def test_maxbuffersize():
assert ord('b') == next(unpacker) 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__': if __name__ == '__main__':
nose.main() nose.main()