Skip to content

Commit 22145dd

Browse files
committed
Add dynamic borrow checking for dereferencing NumPy arrays.
1 parent e933e27 commit 22145dd

File tree

10 files changed

+1024
-398
lines changed

10 files changed

+1024
-398
lines changed

benches/borrow.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#![feature(test)]
2+
3+
extern crate test;
4+
use test::{black_box, Bencher};
5+
6+
use numpy::PyArray;
7+
use pyo3::Python;
8+
9+
#[bench]
10+
fn initial_shared_borrow(bencher: &mut Bencher) {
11+
Python::with_gil(|py| {
12+
let array = PyArray::<f64, _>::zeros(py, (1, 2, 3), false);
13+
14+
bencher.iter(|| {
15+
let array = black_box(array);
16+
17+
let _shared = array.readonly();
18+
});
19+
});
20+
}
21+
22+
#[bench]
23+
fn additional_shared_borrow(bencher: &mut Bencher) {
24+
Python::with_gil(|py| {
25+
let array = PyArray::<f64, _>::zeros(py, (1, 2, 3), false);
26+
27+
let _shared = (0..128).map(|_| array.readonly()).collect::<Vec<_>>();
28+
29+
bencher.iter(|| {
30+
let array = black_box(array);
31+
32+
let _shared = array.readonly();
33+
});
34+
});
35+
}
36+
37+
#[bench]
38+
fn exclusive_borrow(bencher: &mut Bencher) {
39+
Python::with_gil(|py| {
40+
let array = PyArray::<f64, _>::zeros(py, (1, 2, 3), false);
41+
42+
bencher.iter(|| {
43+
let array = black_box(array);
44+
45+
let _exclusive = array.readwrite();
46+
});
47+
});
48+
}

examples/simple/src/lib.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
use numpy::ndarray::{ArrayD, ArrayViewD, ArrayViewMutD};
2-
use numpy::{Complex64, IntoPyArray, PyArray1, PyArrayDyn, PyReadonlyArrayDyn};
2+
use numpy::{
3+
Complex64, IntoPyArray, PyArray1, PyArrayDyn, PyReadonlyArrayDyn, PyReadwriteArrayDyn,
4+
};
35
use pyo3::{
46
pymodule,
57
types::{PyDict, PyModule},
@@ -41,8 +43,8 @@ fn rust_ext(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
4143
// wrapper of `mult`
4244
#[pyfn(m)]
4345
#[pyo3(name = "mult")]
44-
fn mult_py(a: f64, x: &PyArrayDyn<f64>) {
45-
let x = unsafe { x.as_array_mut() };
46+
fn mult_py(a: f64, mut x: PyReadwriteArrayDyn<f64>) {
47+
let x = x.as_array_mut();
4648
mult(a, x);
4749
}
4850

src/array.rs

Lines changed: 67 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,11 @@ use pyo3::{
1919
Python, ToPyObject,
2020
};
2121

22+
use crate::borrow::{PyReadonlyArray, PyReadwriteArray};
2223
use crate::convert::{ArrayExt, IntoPyArray, NpyIndex, ToNpyDims, ToPyArray};
2324
use crate::dtype::{Element, PyArrayDescr};
2425
use crate::error::{DimensionalityError, FromVecError, NotContiguousError, TypeError};
2526
use crate::npyffi::{self, npy_intp, NPY_ORDER, PY_ARRAY_API};
26-
#[allow(deprecated)]
27-
use crate::npyiter::{NpySingleIter, NpySingleIterBuilder, ReadWrite};
28-
use crate::readonly::PyReadonlyArray;
2927
use crate::slice_container::PySliceContainer;
3028

3129
/// A safe, static-typed interface for
@@ -194,18 +192,8 @@ impl<T, D> PyArray<T, D> {
194192
}
195193

196194
#[inline(always)]
197-
fn check_flag(&self, flag: c_int) -> bool {
198-
unsafe { *self.as_array_ptr() }.flags & flag == flag
199-
}
200-
201-
#[inline(always)]
202-
pub(crate) fn get_flag(&self) -> c_int {
203-
unsafe { *self.as_array_ptr() }.flags
204-
}
205-
206-
/// Returns a temporally unwriteable reference of the array.
207-
pub fn readonly(&self) -> PyReadonlyArray<T, D> {
208-
self.into()
195+
pub(crate) fn check_flags(&self, flags: c_int) -> bool {
196+
unsafe { *self.as_array_ptr() }.flags & flags != 0
209197
}
210198

211199
/// Returns `true` if the internal data of the array is C-style contiguous
@@ -227,18 +215,17 @@ impl<T, D> PyArray<T, D> {
227215
/// });
228216
/// ```
229217
pub fn is_contiguous(&self) -> bool {
230-
self.check_flag(npyffi::NPY_ARRAY_C_CONTIGUOUS)
231-
| self.check_flag(npyffi::NPY_ARRAY_F_CONTIGUOUS)
218+
self.check_flags(npyffi::NPY_ARRAY_C_CONTIGUOUS | npyffi::NPY_ARRAY_F_CONTIGUOUS)
232219
}
233220

234221
/// Returns `true` if the internal data of the array is Fortran-style contiguous.
235222
pub fn is_fortran_contiguous(&self) -> bool {
236-
self.check_flag(npyffi::NPY_ARRAY_F_CONTIGUOUS)
223+
self.check_flags(npyffi::NPY_ARRAY_F_CONTIGUOUS)
237224
}
238225

239226
/// Returns `true` if the internal data of the array is C-style contiguous.
240227
pub fn is_c_contiguous(&self) -> bool {
241-
self.check_flag(npyffi::NPY_ARRAY_C_CONTIGUOUS)
228+
self.check_flags(npyffi::NPY_ARRAY_C_CONTIGUOUS)
242229
}
243230

244231
/// Get `Py<PyArray>` from `&PyArray`, which is the owned wrapper of PyObject.
@@ -684,27 +671,61 @@ impl<T: Element, D: Dimension> PyArray<T, D> {
684671

685672
/// Get the immutable reference of the specified element, with checking the passed index is valid.
686673
///
687-
/// Please consider the use of safe alternatives
688-
/// ([`PyReadonlyArray::get`](../struct.PyReadonlyArray.html#method.get)
689-
/// or [`get_owned`](#method.get_owned)) instead of this.
674+
/// Consider using safe alternatives like [`PyReadonlyArray::get`].
675+
///
690676
/// # Example
677+
///
691678
/// ```
692679
/// use numpy::PyArray;
693-
/// pyo3::Python::with_gil(|py| {
680+
/// use pyo3::Python;
681+
///
682+
/// Python::with_gil(|py| {
694683
/// let arr = PyArray::arange(py, 0, 16, 1).reshape([2, 2, 4]).unwrap();
695-
/// assert_eq!(*unsafe { arr.get([1, 0, 3]) }.unwrap(), 11);
684+
/// assert_eq!(unsafe { *arr.get([1, 0, 3]).unwrap() }, 11);
696685
/// });
697686
/// ```
698687
///
699688
/// # Safety
700-
/// If the internal array is not readonly and can be mutated from Python code,
701-
/// holding the slice might cause undefined behavior.
689+
///
690+
/// Calling this method is undefined behaviour if the underlying array
691+
/// is aliased mutably by other instances of `PyArray`
692+
/// or concurrently modified by Python or other native code.
702693
#[inline(always)]
703694
pub unsafe fn get(&self, index: impl NpyIndex<Dim = D>) -> Option<&T> {
704695
let offset = index.get_checked::<T>(self.shape(), self.strides())?;
705696
Some(&*self.data().offset(offset))
706697
}
707698

699+
/// Same as [`get`][Self::get], but returns `Option<&mut T>`.
700+
///
701+
/// Consider using safe alternatives like [`PyReadwriteArray::get_mut`].
702+
///
703+
/// # Example
704+
///
705+
/// ```
706+
/// use numpy::PyArray;
707+
/// use pyo3::Python;
708+
///
709+
/// Python::with_gil(|py| {
710+
/// let arr = PyArray::arange(py, 0, 16, 1).reshape([2, 2, 4]).unwrap();
711+
/// unsafe {
712+
/// *arr.get_mut([1, 0, 3]).unwrap() = 42;
713+
/// }
714+
/// assert_eq!(unsafe { *arr.get([1, 0, 3]).unwrap() }, 42);
715+
/// });
716+
/// ```
717+
///
718+
/// # Safety
719+
///
720+
/// Calling this method is undefined behaviour if the underlying array
721+
/// is aliased immutably by mutably by other instances of `PyArray`
722+
/// or concurrently modified by Python or other native code.
723+
#[inline(always)]
724+
pub unsafe fn get_mut(&self, index: impl NpyIndex<Dim = D>) -> Option<&mut T> {
725+
let offset = index.get_checked::<T>(self.shape(), self.strides())?;
726+
Some(&mut *self.data().offset(offset))
727+
}
728+
708729
/// Get the immutable reference of the specified element, without checking the
709730
/// passed index is valid.
710731
///
@@ -827,28 +848,37 @@ impl<T: Element, D: Dimension> PyArray<T, D> {
827848
ToPyArray::to_pyarray(arr, py)
828849
}
829850

830-
/// Get the immutable view of the internal data of `PyArray`, as
831-
/// [`ndarray::ArrayView`](https://docs.rs/ndarray/latest/ndarray/type.ArrayView.html).
851+
/// Get an immutable borrow of the NumPy array
852+
pub fn readonly(&self) -> PyReadonlyArray<'_, T, D> {
853+
PyReadonlyArray::try_new(self).unwrap()
854+
}
855+
856+
/// Get a mutable borrow of the NumPy array
857+
pub fn readwrite(&self) -> PyReadwriteArray<'_, T, D> {
858+
PyReadwriteArray::try_new(self).unwrap()
859+
}
860+
861+
/// Returns the internal array as [`ArrayView`].
832862
///
833-
/// Please consider the use of safe alternatives
834-
/// ([`PyReadonlyArray::as_array`](../struct.PyReadonlyArray.html#method.as_array)
835-
/// or [`to_array`](#method.to_array)) instead of this.
863+
/// See also [`PyReadonlyArray::as_array`].
836864
///
837865
/// # Safety
838-
/// If the internal array is not readonly and can be mutated from Python code,
839-
/// holding the `ArrayView` might cause undefined behavior.
866+
///
867+
/// The existence of an exclusive reference to the internal data, e.g. `&mut [T]` or `ArrayViewMut`, implies undefined behavior.
840868
pub unsafe fn as_array(&self) -> ArrayView<'_, T, D> {
841869
let (shape, ptr, inverted_axes) = self.ndarray_shape_ptr();
842870
let mut res = ArrayView::from_shape_ptr(shape, ptr);
843871
inverted_axes.invert(&mut res);
844872
res
845873
}
846874

847-
/// Returns the internal array as [`ArrayViewMut`]. See also [`as_array`](#method.as_array).
875+
/// Returns the internal array as [`ArrayViewMut`].
876+
///
877+
/// See also [`PyReadwriteArray::as_array_mut`].
848878
///
849879
/// # Safety
850-
/// If another reference to the internal data exists(e.g., `&[T]` or `ArrayView`),
851-
/// it might cause undefined behavior.
880+
///
881+
/// The existence of another reference to the internal data, e.g. `&[T]` or `ArrayView`, implies undefined behavior.
852882
pub unsafe fn as_array_mut(&self) -> ArrayViewMut<'_, T, D> {
853883
let (shape, ptr, inverted_axes) = self.ndarray_shape_ptr();
854884
let mut res = ArrayViewMut::from_shape_ptr(shape, ptr);
@@ -924,7 +954,7 @@ impl<D: Dimension> PyArray<PyObject, D> {
924954
///
925955
/// let pyarray = PyArray::from_owned_object_array(py, array);
926956
///
927-
/// assert!(pyarray.readonly().get(0).unwrap().as_ref(py).is_instance_of::<CustomElement>().unwrap());
957+
/// assert!(pyarray.readonly().as_array().get(0).unwrap().as_ref(py).is_instance_of::<CustomElement>().unwrap());
928958
/// });
929959
/// ```
930960
pub fn from_owned_object_array<'py, T>(py: Python<'py>, arr: Array<Py<T>, D>) -> &'py Self {
@@ -1073,21 +1103,6 @@ impl<T: Element> PyArray<T, Ix1> {
10731103
self.resize_(self.py(), [new_elems], 1, NPY_ORDER::NPY_ANYORDER)
10741104
}
10751105

1076-
/// Iterates all elements of this array.
1077-
/// See [NpySingleIter](../npyiter/struct.NpySingleIter.html) for more.
1078-
///
1079-
/// # Safety
1080-
///
1081-
/// The iterator will produce mutable references into the array which must not be
1082-
/// aliased by other references for the life time of the iterator.
1083-
#[deprecated(
1084-
note = "The wrappers of the array iterator API are deprecated, please use ndarray's `ArrayBase::iter_mut` instead."
1085-
)]
1086-
#[allow(deprecated)]
1087-
pub unsafe fn iter<'py>(&'py self) -> PyResult<NpySingleIter<'py, T, ReadWrite>> {
1088-
NpySingleIterBuilder::readwrite(self).build()
1089-
}
1090-
10911106
fn resize_<D: IntoDimension>(
10921107
&self,
10931108
py: Python,

0 commit comments

Comments
 (0)