Skip to content

Commit

Permalink
Merge pull request #20294 from charris/backport-20237
Browse files Browse the repository at this point in the history
BUG: ``VOID_nonzero`` could sometimes mutate alignment flag
  • Loading branch information
charris committed Nov 4, 2021
2 parents 5fe9833 + b186992 commit acbbf1a
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
4 changes: 2 additions & 2 deletions numpy/core/src/multiarray/arraytypes.c.src
Expand Up @@ -2759,10 +2759,10 @@ VOID_nonzero (char *ip, PyArrayObject *ap)
dummy_fields.descr = new;
if ((new->alignment > 1) && !__ALIGNED(ip + offset,
new->alignment)) {
PyArray_CLEARFLAGS(ap, NPY_ARRAY_ALIGNED);
PyArray_CLEARFLAGS(dummy_arr, NPY_ARRAY_ALIGNED);
}
else {
PyArray_ENABLEFLAGS(ap, NPY_ARRAY_ALIGNED);
PyArray_ENABLEFLAGS(dummy_arr, NPY_ARRAY_ALIGNED);
}
if (new->f->nonzero(ip+offset, dummy_arr)) {
nonz = NPY_TRUE;
Expand Down
12 changes: 12 additions & 0 deletions numpy/core/tests/test_numeric.py
Expand Up @@ -1497,6 +1497,18 @@ def __bool__(self):
a = np.array([[False], [TrueThenFalse()]])
assert_raises(RuntimeError, np.nonzero, a)

def test_nonzero_sideffects_structured_void(self):
# Checks that structured void does not mutate alignment flag of
# original array.
arr = np.zeros(5, dtype="i1,i8,i8") # `ones` may short-circuit
assert arr.flags.aligned # structs are considered "aligned"
assert not arr["f2"].flags.aligned
# make sure that nonzero/count_nonzero do not flip the flag:
np.nonzero(arr)
assert arr.flags.aligned
np.count_nonzero(arr)
assert arr.flags.aligned

def test_nonzero_exception_safe(self):
# gh-13930

Expand Down

0 comments on commit acbbf1a

Please sign in to comment.