Skip to content

Commit c20024f

Browse files
committed
Keep Unpacker.tell() at the start of an incomplete object
When the buffer ends inside an object, the C extension decodes the part it has and keeps it for the next feed. tell() then included those bytes, so it pointed into the middle of the next object instead of at its start. Code that saves tell() to resume a stream later restarted mid-object and decoded garbage. The pure Python implementation already returns the start.
1 parent 8a88e3d commit c20024f

2 files changed

Lines changed: 26 additions & 0 deletions

File tree

‎msgpack/_unpacker.pyx‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,8 @@ cdef class Unpacker:
325325
cdef object unicode_errors
326326
cdef Py_ssize_t max_buffer_size
327327
cdef uint64_t stream_offset
328+
# stream_offset at the start of an incomplete object
329+
cdef uint64_t object_offset
328330
cdef bint _unpacking
329331

330332
def __dealloc__(self):
@@ -486,6 +488,8 @@ cdef class Unpacker:
486488
raise RuntimeError("Unpacker cannot be called recursively while unpacking is in progress")
487489
if self.ctx.execute != NULL and self.ctx.execute != execute:
488490
raise ValueError("Cannot switch unpacking methods while an object is incomplete")
491+
if self.ctx.execute == NULL:
492+
self.object_offset = self.stream_offset
489493

490494
self._unpacking = True
491495
try:
@@ -585,6 +589,9 @@ cdef class Unpacker:
585589
number of bytes that were read from the input, also the starting
586590
position of the next object.
587591
"""
592+
if self.ctx.execute != NULL:
593+
# Part of the next object has been decoded, but it still starts here.
594+
return self.object_offset
588595
return self.stream_offset
589596

590597
def __iter__(self):

‎test/test_sequnpack.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,3 +169,22 @@ def test_unpack_tell():
169169
m2 = next(unpacker)
170170
assert m == m2
171171
assert o == unpacker.tell()
172+
173+
174+
def test_unpack_tell_incomplete_object():
175+
# tell() is where the next object starts, even when only part of it has arrived.
176+
first = packb([1, 2, 3])
177+
second = packb(["x" * 40, "y" * 40])
178+
packed = first + second
179+
for cut in (len(first) + 1, len(first) + 3, len(first) + 45):
180+
unpacker = Unpacker()
181+
unpacker.feed(packed[:cut])
182+
assert list(unpacker) == [[1, 2, 3]]
183+
assert unpacker.tell() == len(first)
184+
unpacker.feed(packed[cut:])
185+
assert list(unpacker) == [["x" * 40, "y" * 40]]
186+
assert unpacker.tell() == len(packed)
187+
188+
unpacker = Unpacker(io.BytesIO(packed[:cut]), read_size=16)
189+
assert list(unpacker) == [[1, 2, 3]]
190+
assert unpacker.tell() == len(first)

0 commit comments

Comments
 (0)