Skip to content

Commit 9d9c3ee

Browse files
committed
Packer.pack_array/map_header to correspond to read functions
1 parent 0431a76 commit 9d9c3ee

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

msgpack/_msgpack.pyx

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,17 @@ cdef class Packer(object):
178178
self.pk.length = 0
179179
return buf
180180

181+
cpdef pack_array_header(self, size_t size):
182+
msgpack_pack_array(&self.pk, size)
183+
buf = PyBytes_FromStringAndSize(self.pk.buf, self.pk.length)
184+
self.pk.length = 0
185+
return buf
186+
187+
cpdef pack_map_header(self, size_t size):
188+
msgpack_pack_map(&self.pk, size)
189+
buf = PyBytes_FromStringAndSize(self.pk.buf, self.pk.length)
190+
self.pk.length = 0
191+
return buf
181192

182193
def pack(object o, object stream, default=None, encoding='utf-8', unicode_errors='strict'):
183194
"""

test/test_pack.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,35 @@ def testPackFloat():
9191
assert_equal(packb(1.0, use_single_float=True), b'\xca' + struct.pack('>f', 1.0))
9292
assert_equal(packb(1.0, use_single_float=False), b'\xcb' + struct.pack('>d', 1.0))
9393

94+
def testArraySize(sizes=[0, 5, 50, 1000]):
95+
bio = six.BytesIO()
96+
packer = Packer()
97+
for size in sizes:
98+
bio.write(packer.pack_array_header(size))
99+
for i in range(size):
100+
bio.write(packer.pack(i))
101+
102+
bio.seek(0)
103+
unpacker = Unpacker(bio)
104+
for size in sizes:
105+
assert unpacker.unpack() == tuple(range(size))
106+
107+
def testMapSize(sizes=[0, 5, 50, 1000]):
108+
bio = six.BytesIO()
109+
packer = Packer()
110+
for size in sizes:
111+
bio.write(packer.pack_map_header(size))
112+
for i in range(size):
113+
bio.write(packer.pack(i)) # key
114+
bio.write(packer.pack(i * 2)) # value
115+
116+
bio.seek(0)
117+
unpacker = Unpacker(bio)
118+
for size in sizes:
119+
assert unpacker.unpack() == {i: i * 2 for i in range(size)}
120+
121+
122+
94123

95124
class odict(dict):
96125
'''Reimplement OrderedDict to run test on Python 2.6'''

0 commit comments

Comments
 (0)