10000 Packer accepts bytearray objects · msgpack/msgpack-python@9fbeaf6 · GitHub
[go: up one dir, main page]

Skip to content

Commit 9fbeaf6

Browse files
committed
Packer accepts bytearray objects
1 parent a8d9162 commit 9fbeaf6

File tree

3 files changed

+23
-4
lines changed

3 files changed

+23
-4
lines changed

msgpack/_packer.pyx

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ from msgpack import ExtType
1010
cdef extern from "Python.h":
1111

1212
int PyMemoryView_Check(object obj)
13+
int PyByteArray_Check(object obj)
14+
int PyByteArray_CheckExact(object obj)
1315

1416

1517
cdef extern from "pack.h":
@@ -39,6 +41,14 @@ cdef int DEFAULT_RECURSE_LIMIT=511
3941
cdef size_t ITEM_LIMIT = (2**32)-1
4042

4143

44+
cdef inline int PyBytesLike_Check(object o):
45+
return PyBytes_Check(o) or PyByteArray_Check(o)
46+
47+
48+
cdef inline int PyBytesLike_CheckExact(object o):
49+
return PyBytes_CheckExact(o) or PyByteArray_CheckExact(o)
50+
51+
4252
cdef class Packer(object):
4353
"""
4454
MessagePack Packer
@@ -174,10 +184,11 @@ cdef class Packer(object):
174184
else:
175185
dval = o
176186
ret = msgpack_pack_double(&self.pk, dval)
177-
elif PyBytes_CheckExact(o) if strict_types else PyBytes_Check(o):
187+
elif PyBytesLike_CheckExact(o) if strict_types else PyBytesLike_Check(o):
178188
L = len(o)
179189
if L > ITEM_LIMIT:
180-
raise PackValueError("bytes is too large")
190+
raise PackValueError("%s is too large"
191+
% type(o).__name__.capitalize())
181192
rawval = o
182193
ret = msgpack_pack_bin(&self.pk, L)
183194
if ret == 0:

msgpack/fallback.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -728,10 +728,11 @@ def _pack(self, obj, nest_limit=DEFAULT_RECURSE_LIMIT,
728728
default_used = True
729729
continue
730730
raise PackOverflowError("Integer value out of range")
731-
if check(obj, bytes):
731+
if check(obj, (bytes, bytearray)):
732732
n = len(obj)
733733
if n >= 2**32:
734-
raise PackValueError("Bytes is too large")
734+
raise PackValueError("%s is too large"
735+
% type(obj).__name__.capitalize())
735736
self._pack_bin_header(n)
736737
return self._buffer.write(obj)
737738
if check(obj, Unicode):

test/test_pack.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,13 @@ def testPackBytes():
5858
for td in test_data:
5959
check(td)
6060

61+
def testPackByteArrays():
62+
test_data = [
63+
bytearray(b""), bytearray(b"abcd"), (bytearray(b"defgh"),),
64+
]
65+
for td in test_data:
66+
check(td)
67+
6168
def testIgnoreUnicodeErrors():
6269
re = unpackb(packb(b'abc\xeddef'), encoding='utf-8', unicode_errors='ignore', use_list=1)
6370
assert re == "abcdef"

0 commit comments

Comments
 (0)
0