summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMatti Picus <matti.picus@gmail.com>2021-12-16 08:03:47 -0700
committerGitHub <noreply@github.com>2021-12-16 08:03:47 -0700
commita48a6733055c995ff4605e852fb39e0113c88be9 (patch)
treeaf21742f4d607a49541ca097e809c5c2f4106069
parent70157e48c68b6c69c1ca86f3b8dfd5d53040eb89 (diff)
parent27b5a240b915c11a760378d699eb36c190f4e36e (diff)
downloadnumpy-a48a6733055c995ff4605e852fb39e0113c88be9.tar.gz
Merge pull request #20592 from seberg/no-suboffsets
BUG: Reject buffers with suboffsets
-rw-r--r--numpy/core/src/multiarray/ctors.c10
-rw-r--r--numpy/core/tests/test_multiarray.py20
2 files changed, 30 insertions, 0 deletions
diff --git a/numpy/core/src/multiarray/ctors.c b/numpy/core/src/multiarray/ctors.c
index e22708f39..c17402947 100644
--- a/numpy/core/src/multiarray/ctors.c
+++ b/numpy/core/src/multiarray/ctors.c
@@ -1152,6 +1152,16 @@ _array_from_buffer_3118(PyObject *memoryview)
npy_intp shape[NPY_MAXDIMS], strides[NPY_MAXDIMS];
view = PyMemoryView_GET_BUFFER(memoryview);
+
+ if (view->suboffsets != NULL) {
+ PyErr_SetString(PyExc_BufferError,
+ "NumPy currently does not support importing buffers which "
+ "include suboffsets as they are not compatible with the NumPy"
+ "memory layout without a copy. Consider copying the original "
+ "before trying to convert it to a NumPy array.");
+ return NULL;
+ }
+
nd = view->ndim;
descr = _dtype_from_buffer_3118(memoryview);
diff --git a/numpy/core/tests/test_multiarray.py b/numpy/core/tests/test_multiarray.py
index 9d728afa4..2fd94f245 100644
--- a/numpy/core/tests/test_multiarray.py
+++ b/numpy/core/tests/test_multiarray.py
@@ -7793,6 +7793,26 @@ class TestNewBufferProtocol:
# Fix buffer info again before we delete (or we lose the memory)
_multiarray_tests.corrupt_or_fix_bufferinfo(obj)
+ def test_no_suboffsets(self):
+ try:
+ import _testbuffer
+ except ImportError:
+ raise pytest.skip("_testbuffer is not available")
+
+ for shape in [(2, 3), (2, 3, 4)]:
+ data = list(range(np.prod(shape)))
+ buffer = _testbuffer.ndarray(data, shape, format='i',
+ flags=_testbuffer.ND_PIL)
+ msg = "NumPy currently does not support.*suboffsets"
+ with pytest.raises(BufferError, match=msg):
+ np.asarray(buffer)
+ with pytest.raises(BufferError, match=msg):
+ np.asarray([buffer])
+
+ # Also check (unrelated and more limited but similar) frombuffer:
+ with pytest.raises(BufferError):
+ np.frombuffer(buffer)
+
class TestArrayCreationCopyArgument(object):