Skip to content

Commit d104105

Browse files
committed
use legacy buffer protocol if necessary
- try new protocol first - fall back to old protocol if not PY3 and warn about future changes - raise otherwise
1 parent a77dd09 commit d104105

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

msgpack/_unpacker.pyx

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ from cpython.buffer cimport (
1515
)
1616
from cpython.mem cimport PyMem_Malloc, PyMem_Free
1717
from cpython.object cimport PyCallable_Check
18+
from cpython.exc cimport PyErr_WarnEx
1819

1920
cdef extern from "Python.h":
2021
ctypedef struct PyObject
@@ -142,8 +143,14 @@ def unpackb(object packed, object object_hook=None, object list_hook=None,
142143
if PyObject_GetBuffer(packed, &view, PyBUF_SIMPLE) == 0:
143144
buf = <char*> view.buf
144145
buf_len = view.len
146+
else:
147+
raise
145148
else:
146149
PyObject_AsReadBuffer(packed, <const void**>&buf, &buf_len)
150+
PyErr_WarnEx(DeprecationWarning,
151+
"unpacking %s requires old buffer protocol,"
152+
"which will be removed in msgpack 1.0" % type(packed),
153+
1)
147154

148155
if encoding is not None:
149156
if isinstance(encoding, unicode):

msgpack/fallback.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import sys
44
import array
55
import struct
6+
import warnings
67

78
if sys.version_info[0] == 3:
89
PY3 = True
@@ -247,9 +248,17 @@ def __init__(self, file_like=None, read_size=0, use_list=True,
247248

248249
def feed(self, next_bytes):
249250
assert self._fb_feeding
250-
if isinstance(next_bytes, array.array):
251-
next_bytes = next_bytes.tostring()
252-
view = memoryview(next_bytes)
251+
try:
252+
view = memoryview(next_bytes)
253+
except TypeError:
254+
# try to use legacy buffer protocol if 2.7, otherwise re-raise
255+
if not PY3:
256+
view = memoryview(buffer(next_bytes))
257+
warnings.warn("unpacking %s requires old buffer protocol,"
258+
"which will be removed in msgpack 1.0" % type(next_bytes),
259+
DeprecationWarning)
260+
else:
261+
raise
253262
assert view.itemsize == 1
254263
L = len(view)
255264
if self._fb_buf_n + L - self._fb_sloppiness > self._max_buffer_size:

0 commit comments

Comments
 (0)