Expose packed stream with Unpacker.read_bytes()

At present, Unpacker buffers reading from the stream, meaning the stream can no longer be read directly. Unpacker.read_bytes(n) provides access to the underlying data, allowing content of known size to be read without unpacking.
This commit is contained in:
jnothman 2012-09-21 16:03:41 +10:00
parent 5b66edaa15
commit ffec10dff3

View file

@ -455,6 +455,18 @@ 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
ret = ''
while len(ret) < nbytes and self.file_like is not None:
if self.buf_head == self.buf_tail:
self.fill_buffer()
nread = min(self.buf_tail - self.buf_head, nbytes - len(ret))
ret += PyBytes_FromStringAndSize(self.buf + self.buf_head, nread)
self.buf_head += nread
return ret
def __iter__(self):
return self