Skip to content

Commit

Permalink
BUG: VOID_nonzero could sometimes mutate alignment flag
Browse files Browse the repository at this point in the history
This fixes that invocations of `VOID_nonzero` could flip the
alignment flag on the original array even though the original
array is not modified.
  • Loading branch information
seberg authored and charris committed Nov 3, 2021
1 parent 2b1485e commit b186992
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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 b186992

Please sign in to comment.