numpy/borrow/mod.rs
1//! Types to safely create references into NumPy arrays
2//!
3//! It is assumed that unchecked code - which includes unsafe Rust and Python - is validated by its author
4//! which together with the dynamic borrow checking performed by this crate ensures that
5//! safe Rust code cannot cause undefined behaviour by creating references into NumPy arrays.
6//!
7//! With these borrows established, [references to individual elements][PyReadonlyArray::get] or [reference-based views of whole array][PyReadonlyArray::as_array]
8//! can be created safely. These are then the starting point for algorithms iterating over and operating on the elements of the array.
9//!
10//! # Examples
11//!
12//! The first example shows that dynamic borrow checking works to constrain
13//! both what safe Rust code can invoke and how it is invoked.
14//!
15//! ```rust
16//! # use std::panic::{catch_unwind, AssertUnwindSafe};
17//! #
18//! use numpy::{PyArray1, PyArrayMethods, npyffi::flags};
19//! use ndarray::Zip;
20//! use pyo3::{Python, Bound};
21//!
22//! fn add(x: &Bound<'_, PyArray1<f64>>, y: &Bound<'_, PyArray1<f64>>, z: &Bound<'_, PyArray1<f64>>) {
23//! let x1 = x.readonly();
24//! let y1 = y.readonly();
25//! let mut z1 = z.readwrite();
26//!
27//! let x2 = x1.as_array();
28//! let y2 = y1.as_array();
29//! let z2 = z1.as_array_mut();
30//!
31//! Zip::from(x2)
32//! .and(y2)
33//! .and(z2)
34//! .for_each(|x3, y3, z3| *z3 = x3 + y3);
35//!
36//! // Will fail at runtime due to conflict with `x1`.
37//! let res = catch_unwind(AssertUnwindSafe(|| {
38//! let _x4 = x.readwrite();
39//! }));
40//! assert!(res.is_err());
41//! }
42//!
43//! Python::attach(|py| {
44//! let x = PyArray1::<f64>::zeros(py, 42, false);
45//! let y = PyArray1::<f64>::zeros(py, 42, false);
46//! let z = PyArray1::<f64>::zeros(py, 42, false);
47//!
48//! // Will work as the three arrays are distinct.
49//! add(&x, &y, &z);
50//!
51//! // Will work as `x1` and `y1` are compatible borrows.
52//! add(&x, &x, &z);
53//!
54//! // Will fail at runtime due to conflict between `y1` and `z1`.
55//! let res = catch_unwind(AssertUnwindSafe(|| {
56//! add(&x, &y, &y);
57//! }));
58//! assert!(res.is_err());
59//! });
60//! ```
61//!
62//! The second example shows that non-overlapping and interleaved views are also supported.
63//!
64//! ```rust
65//! use numpy::{PyArray1, PyArrayMethods};
66//! use pyo3::{types::{IntoPyDict, PyAnyMethods}, Python};
67//!
68//! # fn main() -> pyo3::PyResult<()> {
69//! Python::attach(|py| {
70//! let array = PyArray1::arange(py, 0.0, 10.0, 1.0);
71//! let locals = [("array", array)].into_py_dict(py)?;
72//!
73//! let view1 = py.eval(c"array[:5]", None, Some(&locals))?.cast_into::<PyArray1<f64>>()?;
74//! let view2 = py.eval(c"array[5:]", None, Some(&locals))?.cast_into::<PyArray1<f64>>()?;
75//! let view3 = py.eval(c"array[::2]", None, Some(&locals))?.cast_into::<PyArray1<f64>>()?;
76//! let view4 = py.eval(c"array[1::2]", None, Some(&locals))?.cast_into::<PyArray1<f64>>()?;
77//!
78//! {
79//! let _view1 = view1.readwrite();
80//! let _view2 = view2.readwrite();
81//! }
82//!
83//! {
84//! let _view3 = view3.readwrite();
85//! let _view4 = view4.readwrite();
86//! }
87//! # Ok(())
88//! })
89//! # }
90//! ```
91//!
92//! The third example shows that some views are incorrectly rejected since the borrows are over-approximated.
93//!
94//! ```rust
95//! # use std::panic::{catch_unwind, AssertUnwindSafe};
96//! #
97//! use numpy::{PyArray2, PyArrayMethods};
98//! use pyo3::{types::{IntoPyDict, PyAnyMethods}, Python};
99//!
100//! # fn main() -> pyo3::PyResult<()> {
101//! Python::attach(|py| {
102//! let array = PyArray2::<f64>::zeros(py, (10, 10), false);
103//! let locals = [("array", array)].into_py_dict(py)?;
104//!
105//! let view1 = py.eval(c"array[:, ::3]", None, Some(&locals))?.cast_into::<PyArray2<f64>>()?;
106//! let view2 = py.eval(c"array[:, 1::3]", None, Some(&locals))?.cast_into::<PyArray2<f64>>()?;
107//!
108//! // A false conflict as the views do not actually share any elements.
109//! let res = catch_unwind(AssertUnwindSafe(|| {
110//! let _view1 = view1.readwrite();
111//! let _view2 = view2.readwrite();
112//! }));
113//! assert!(res.is_err());
114//! # Ok(())
115//! })
116//! # }
117//! ```
118//!
119//! # Rationale
120//!
121//! Rust references require aliasing discipline to be maintained, i.e. there must always
122//! exist only a single mutable (aka exclusive) reference or multiple immutable (aka shared) references
123//! for each object, otherwise the program contains undefined behaviour.
124//!
125//! The aim of this module is to ensure that safe Rust code is unable to violate these requirements on its own.
126//! We cannot prevent unchecked code - this includes unsafe Rust, Python or other native code like C or Fortran -
127//! from violating them. Therefore the responsibility to avoid this lies with the author of that code instead of the compiler.
128//! However, assuming that the unchecked code is correct, we can ensure that safe Rust is unable to introduce mistakes
129//! into an otherwise correct program by dynamically checking which arrays are currently borrowed and in what manner.
130//!
131//! This means that we follow the [base object chain][base] of each array to the original allocation backing it and
132//! track which parts of that allocation are covered by the array and thereby ensure that only a single read-write array
133//! or multiple read-only arrays overlapping with that region are borrowed at any time.
134//!
135//! In contrast to Rust references, the mere existence of Python references or raw pointers is not an issue
136//! because these values are not assumed to follow aliasing discipline by the Rust compiler.
137//!
138//! This cannot prevent unchecked code from concurrently modifying an array via callbacks or using multiple threads,
139//! but that would lead to incorrect results even if the code that is interfered with is implemented in another language
140//! which does not require aliasing discipline.
141//!
142//! Concerning multi-threading in particular: While the GIL needs to be acquired to create borrows, they are not bound to the GIL
143//! and will stay active after the GIL is released, for example by calling [`detach`][pyo3::Python::detach].
144//! Borrows also do not provide synchronization, i.e. multiple threads borrowing the same array will lead to runtime panics,
145//! it will not block those threads until already active borrows are released.
146//!
147//! In summary, this crate takes the position that all unchecked code - unsafe Rust, Python, C, Fortran, etc. - must be checked for correctness by its author.
148//! Safe Rust code can then rely on this correctness, but should not be able to introduce memory safety issues on its own. Additionally, dynamic borrow checking
149//! can catch _some_ mistakes introduced by unchecked code, e.g. Python calling a function with the same array as an input and as an output argument.
150//!
151//! # Limitations
152//!
153//! Note that the current implementation of this is an over-approximation: It will consider borrows
154//! potentially conflicting if the initial arrays have the same object at the end of their [base object chain][base].
155//! Then, multiple conditions which are sufficient but not necessary to show the absence of conflicts are checked.
156//!
157//! While this is sufficient to handle common situations like slicing an array with a non-unit step size which divides
158//! the dimension along that axis, there are also cases which it does not handle. For example, if the step size does
159//! not divide the dimension along the sliced axis. Under such conditions, borrows are rejected even though the arrays
160//! do not actually share any elements.
161//!
162//! This does limit the set of programs that can be written using safe Rust in way similar to rustc itself
163//! which ensures that all accepted programs are memory safe but does not necessarily accept all memory safe programs.
164//! However, the unsafe method [`PyArrayMethods::as_array_mut`] can be used as an escape hatch.
165//! More involved cases like the example from above may be supported in the future.
166//!
167//! [base]: https://numpy.org/doc/stable/reference/c-api/types-and-structures.html#c.NPY_AO.base
168
169mod shared;
170
171use std::any::type_name;
172use std::fmt;
173use std::ops::Deref;
174
175use ndarray::{
176 ArrayView, ArrayViewMut, Dimension, IntoDimension, Ix0, Ix1, Ix2, Ix3, Ix4, Ix5, Ix6, IxDyn,
177};
178use pyo3::{Borrowed, Bound, FromPyObject, PyAny, PyErr, PyResult};
179
180use crate::array::{PyArray, PyArrayMethods};
181use crate::convert::NpyIndex;
182use crate::dtype::Element;
183use crate::error::{AsSliceError, BorrowError};
184use crate::npyffi;
185use crate::npyffi::{_PyArray_GET_ITEM_DATA, flags};
186use crate::untyped_array::PyUntypedArrayMethods;
187
188use shared::{acquire, acquire_mut, release, release_mut};
189
190/// Read-only borrow of an array.
191///
192/// An instance of this type ensures that there are no instances of [`PyReadwriteArray`],
193/// i.e. that only shared references into the interior of the array can be created safely.
194///
195/// See the [module-level documentation](self) for more.
196#[repr(transparent)]
197pub struct PyReadonlyArray<'py, T, D>
198where
199 T: Element,
200 D: Dimension,
201{
202 array: Bound<'py, PyArray<T, D>>,
203}
204
205/// Read-only borrow of a zero-dimensional array.
206pub type PyReadonlyArray0<'py, T> = PyReadonlyArray<'py, T, Ix0>;
207
208/// Read-only borrow of a one-dimensional array.
209pub type PyReadonlyArray1<'py, T> = PyReadonlyArray<'py, T, Ix1>;
210
211/// Read-only borrow of a two-dimensional array.
212pub type PyReadonlyArray2<'py, T> = PyReadonlyArray<'py, T, Ix2>;
213
214/// Read-only borrow of a three-dimensional array.
215pub type PyReadonlyArray3<'py, T> = PyReadonlyArray<'py, T, Ix3>;
216
217/// Read-only borrow of a four-dimensional array.
218pub type PyReadonlyArray4<'py, T> = PyReadonlyArray<'py, T, Ix4>;
219
220/// Read-only borrow of a five-dimensional array.
221pub type PyReadonlyArray5<'py, T> = PyReadonlyArray<'py, T, Ix5>;
222
223/// Read-only borrow of a six-dimensional array.
224pub type PyReadonlyArray6<'py, T> = PyReadonlyArray<'py, T, Ix6>;
225
226/// Read-only borrow of an array whose dimensionality is determined at runtime.
227pub type PyReadonlyArrayDyn<'py, T> = PyReadonlyArray<'py, T, IxDyn>;
228
229impl<'py, T, D> Deref for PyReadonlyArray<'py, T, D>
230where
231 T: Element,
232 D: Dimension,
233{
234 type Target = Bound<'py, PyArray<T, D>>;
235
236 fn deref(&self) -> &Self::Target {
237 &self.array
238 }
239}
240
241impl<'a, 'py, T: Element + 'a, D: Dimension + 'a> FromPyObject<'a, 'py>
242 for PyReadonlyArray<'py, T, D>
243{
244 type Error = PyErr;
245
246 fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
247 let array = PyArray::<T, D>::extract::<PyErr>(obj, npyffi::PyArray_Check)?;
248 Ok(array.try_readonly()?)
249 }
250}
251
252impl<'py, T, D> PyReadonlyArray<'py, T, D>
253where
254 T: Element,
255 D: Dimension,
256{
257 pub(crate) fn try_new(array: Bound<'py, PyArray<T, D>>) -> Result<Self, BorrowError> {
258 acquire(array.py(), array.as_array_ptr())?;
259
260 Ok(Self { array })
261 }
262
263 /// Provides an immutable array view of the interior of the NumPy array.
264 #[inline(always)]
265 #[track_caller]
266 pub fn as_array(&self) -> ArrayView<'_, T, D> {
267 // SAFETY: Global borrow flags ensure aliasing discipline.
268 unsafe { self.array.as_array() }
269 }
270
271 /// Provide an immutable slice view of the interior of the NumPy array if it is contiguous.
272 #[inline(always)]
273 pub fn as_slice(&self) -> Result<&[T], AsSliceError> {
274 // SAFETY: Global borrow flags ensure aliasing discipline.
275 unsafe { self.array.as_slice() }
276 }
277
278 /// Provide an immutable reference to an element of the NumPy array if the index is within bounds.
279 #[inline(always)]
280 pub fn get<I>(&self, index: I) -> Option<&T>
281 where
282 I: NpyIndex<Dim = D>,
283 {
284 unsafe { self.array.get(index) }
285 }
286}
287
288#[cfg(feature = "nalgebra")]
289impl<'py, N, D> PyReadonlyArray<'py, N, D>
290where
291 N: nalgebra::Scalar + Element,
292 D: Dimension,
293{
294 /// Try to convert this array into a [`nalgebra::MatrixView`] using the given shape and strides.
295 ///
296 /// Note that nalgebra's types default to Fortan/column-major standard strides whereas NumPy creates C/row-major strides by default.
297 /// Furthermore, array views created by slicing into existing arrays will often have non-standard strides.
298 ///
299 /// If you do not fully control the memory layout of a given array, e.g. at your API entry points,
300 /// it can be useful to opt into nalgebra's support for [dynamic strides][nalgebra::Dyn], for example
301 ///
302 /// ```rust
303 /// # use pyo3::prelude::*;
304 /// use pyo3::py_run;
305 /// use numpy::{get_array_module, PyReadonlyArray2};
306 /// use nalgebra::{MatrixView, Const, Dyn};
307 ///
308 /// #[pyfunction]
309 /// fn sum_standard_layout<'py>(py: Python<'py>, array: PyReadonlyArray2<'py, f64>) -> Option<f64> {
310 /// let matrix: Option<MatrixView<f64, Const<2>, Const<2>>> = array.try_as_matrix();
311 /// matrix.map(|matrix| matrix.sum())
312 /// }
313 ///
314 /// #[pyfunction]
315 /// fn sum_dynamic_strides<'py>(py: Python<'py>, array: PyReadonlyArray2<'py, f64>) -> Option<f64> {
316 /// let matrix: Option<MatrixView<f64, Const<2>, Const<2>, Dyn, Dyn>> = array.try_as_matrix();
317 /// matrix.map(|matrix| matrix.sum())
318 /// }
319 ///
320 /// # fn main() -> pyo3::PyResult<()> {
321 /// Python::attach(|py| {
322 /// let np = py.eval(c"__import__('numpy')", None, None)?;
323 /// let sum_standard_layout = wrap_pyfunction!(sum_standard_layout)(py)?;
324 /// let sum_dynamic_strides = wrap_pyfunction!(sum_dynamic_strides)(py)?;
325 ///
326 /// py_run!(py, np sum_standard_layout, r"assert sum_standard_layout(np.ones((2, 2), order='F')) == 4.");
327 /// py_run!(py, np sum_standard_layout, r"assert sum_standard_layout(np.ones((2, 2, 2))[:,:,0]) is None");
328 ///
329 /// py_run!(py, np sum_dynamic_strides, r"assert sum_dynamic_strides(np.ones((2, 2), order='F')) == 4.");
330 /// py_run!(py, np sum_dynamic_strides, r"assert sum_dynamic_strides(np.ones((2, 2, 2))[:,:,0]) == 4.");
331 /// # Ok(())
332 /// })
333 /// # }
334 /// ```
335 #[doc(alias = "nalgebra")]
336 pub fn try_as_matrix<R, C, RStride, CStride>(
337 &self,
338 ) -> Option<nalgebra::MatrixView<'_, N, R, C, RStride, CStride>>
339 where
340 R: nalgebra::Dim,
341 C: nalgebra::Dim,
342 RStride: nalgebra::Dim,
343 CStride: nalgebra::Dim,
344 {
345 unsafe { self.array.try_as_matrix() }
346 }
347}
348
349#[cfg(feature = "nalgebra")]
350impl<'py, N> PyReadonlyArray<'py, N, Ix1>
351where
352 N: nalgebra::Scalar + Element,
353{
354 /// Convert this one-dimensional array into a [`nalgebra::DMatrixView`] using dynamic strides.
355 ///
356 /// # Panics
357 ///
358 /// Panics if the array has negative strides.
359 #[doc(alias = "nalgebra")]
360 pub fn as_matrix(&self) -> nalgebra::DMatrixView<'_, N, nalgebra::Dyn, nalgebra::Dyn> {
361 self.try_as_matrix().unwrap()
362 }
363}
364
365#[cfg(feature = "nalgebra")]
366impl<'py, N> PyReadonlyArray<'py, N, Ix2>
367where
368 N: nalgebra::Scalar + Element,
369{
370 /// Convert this two-dimensional array into a [`nalgebra::DMatrixView`] using dynamic strides.
371 ///
372 /// # Panics
373 ///
374 /// Panics if the array has negative strides.
375 #[doc(alias = "nalgebra")]
376 pub fn as_matrix(&self) -> nalgebra::DMatrixView<'_, N, nalgebra::Dyn, nalgebra::Dyn> {
377 self.try_as_matrix().unwrap()
378 }
379}
380
381impl<'py, T, D> Clone for PyReadonlyArray<'py, T, D>
382where
383 T: Element,
384 D: Dimension,
385{
386 fn clone(&self) -> Self {
387 acquire(self.array.py(), self.array.as_array_ptr()).unwrap();
388
389 Self {
390 array: self.array.clone(),
391 }
392 }
393}
394
395impl<'py, T, D> Drop for PyReadonlyArray<'py, T, D>
396where
397 T: Element,
398 D: Dimension,
399{
400 fn drop(&mut self) {
401 release(self.array.py(), self.array.as_array_ptr());
402 }
403}
404
405impl<'py, T, D> fmt::Debug for PyReadonlyArray<'py, T, D>
406where
407 T: Element,
408 D: Dimension,
409{
410 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
411 let name = format!(
412 "PyReadonlyArray<{}, {}>",
413 type_name::<T>(),
414 type_name::<D>()
415 );
416
417 f.debug_struct(&name).finish()
418 }
419}
420
421/// Read-write borrow of an array.
422///
423/// An instance of this type ensures that there are no instances of [`PyReadonlyArray`] and no other instances of [`PyReadwriteArray`],
424/// i.e. that only a single exclusive reference into the interior of the array can be created safely.
425///
426/// See the [module-level documentation](self) for more.
427#[repr(transparent)]
428pub struct PyReadwriteArray<'py, T, D>
429where
430 T: Element,
431 D: Dimension,
432{
433 array: Bound<'py, PyArray<T, D>>,
434}
435
436/// Read-write borrow of a zero-dimensional array.
437pub type PyReadwriteArray0<'py, T> = PyReadwriteArray<'py, T, Ix0>;
438
439/// Read-write borrow of a one-dimensional array.
440pub type PyReadwriteArray1<'py, T> = PyReadwriteArray<'py, T, Ix1>;
441
442/// Read-write borrow of a two-dimensional array.
443pub type PyReadwriteArray2<'py, T> = PyReadwriteArray<'py, T, Ix2>;
444
445/// Read-write borrow of a three-dimensional array.
446pub type PyReadwriteArray3<'py, T> = PyReadwriteArray<'py, T, Ix3>;
447
448/// Read-write borrow of a four-dimensional array.
449pub type PyReadwriteArray4<'py, T> = PyReadwriteArray<'py, T, Ix4>;
450
451/// Read-write borrow of a five-dimensional array.
452pub type PyReadwriteArray5<'py, T> = PyReadwriteArray<'py, T, Ix5>;
453
454/// Read-write borrow of a six-dimensional array.
455pub type PyReadwriteArray6<'py, T> = PyReadwriteArray<'py, T, Ix6>;
456
457/// Read-write borrow of an array whose dimensionality is determined at runtime.
458pub type PyReadwriteArrayDyn<'py, T> = PyReadwriteArray<'py, T, IxDyn>;
459
460impl<'py, T, D> Deref for PyReadwriteArray<'py, T, D>
461where
462 T: Element,
463 D: Dimension,
464{
465 type Target = PyReadonlyArray<'py, T, D>;
466
467 fn deref(&self) -> &Self::Target {
468 // SAFETY: Exclusive references decay implicitly into shared references.
469 unsafe { &*(self as *const Self as *const Self::Target) }
470 }
471}
472impl<'py, T, D> From<PyReadwriteArray<'py, T, D>> for PyReadonlyArray<'py, T, D>
473where
474 T: Element,
475 D: Dimension,
476{
477 fn from(value: PyReadwriteArray<'py, T, D>) -> Self {
478 let array = value.array.clone();
479 ::std::mem::drop(value);
480 Self::try_new(array)
481 .expect("releasing an exclusive reference should immediately permit a shared reference")
482 }
483}
484
485impl<'a, 'py, T: Element + 'a, D: Dimension + 'a> FromPyObject<'a, 'py>
486 for PyReadwriteArray<'py, T, D>
487{
488 type Error = PyErr;
489
490 fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
491 let array = PyArray::<T, D>::extract::<PyErr>(obj, npyffi::PyArray_Check)?;
492 Ok(array.try_readwrite()?)
493 }
494}
495
496impl<'py, T, D> PyReadwriteArray<'py, T, D>
497where
498 T: Element,
499 D: Dimension,
500{
501 pub(crate) fn try_new(array: Bound<'py, PyArray<T, D>>) -> Result<Self, BorrowError> {
502 acquire_mut(array.py(), array.as_array_ptr())?;
503
504 Ok(Self { array })
505 }
506
507 /// Provides a mutable array view of the interior of the NumPy array.
508 #[inline(always)]
509 #[track_caller]
510 pub fn as_array_mut(&mut self) -> ArrayViewMut<'_, T, D> {
511 // SAFETY: Global borrow flags ensure aliasing discipline.
512 unsafe { self.array.as_array_mut() }
513 }
514
515 /// Provide a mutable slice view of the interior of the NumPy array if it is contiguous.
516 #[inline(always)]
517 pub fn as_slice_mut(&mut self) -> Result<&mut [T], AsSliceError> {
518 // SAFETY: Global borrow flags ensure aliasing discipline.
519 unsafe { self.array.as_slice_mut() }
520 }
521
522 /// Provide a mutable reference to an element of the NumPy array if the index is within bounds.
523 #[inline(always)]
524 pub fn get_mut<I>(&mut self, index: I) -> Option<&mut T>
525 where
526 I: NpyIndex<Dim = D>,
527 {
528 unsafe { self.array.get_mut(index) }
529 }
530
531 /// Clear the [`WRITEABLE` flag][writeable] from the underlying NumPy array.
532 ///
533 /// Calling this will prevent any further [PyReadwriteArray]s from being taken out. Python
534 /// space can reset this flag, unless the additional flag [`OWNDATA`][owndata] is unset. Such
535 /// an array can be created from Rust space by using [PyArray::borrow_from_array].
536 ///
537 /// [writeable]: https://numpy.org/doc/stable/reference/c-api/array.html#c.NPY_ARRAY_WRITEABLE
538 /// [owndata]: https://numpy.org/doc/stable/reference/c-api/array.html#c.NPY_ARRAY_OWNDATA
539 pub fn make_nonwriteable(self) -> PyReadonlyArray<'py, T, D> {
540 // SAFETY: consuming the only extant mutable reference guarantees we cannot invalidate an
541 // existing reference, nor allow the caller to keep hold of one.
542 unsafe {
543 (*_PyArray_GET_ITEM_DATA(self.as_array_ptr())).flags &= !flags::NPY_ARRAY_WRITEABLE;
544 }
545 self.into()
546 }
547}
548
549#[cfg(feature = "nalgebra")]
550impl<'py, N, D> PyReadwriteArray<'py, N, D>
551where
552 N: nalgebra::Scalar + Element,
553 D: Dimension,
554{
555 /// Try to convert this array into a [`nalgebra::MatrixViewMut`] using the given shape and strides.
556 ///
557 /// See [`PyReadonlyArray::try_as_matrix`] for a discussion of the memory layout requirements.
558 #[doc(alias = "nalgebra")]
559 pub fn try_as_matrix_mut<R, C, RStride, CStride>(
560 &self,
561 ) -> Option<nalgebra::MatrixViewMut<'_, N, R, C, RStride, CStride>>
562 where
563 R: nalgebra::Dim,
564 C: nalgebra::Dim,
565 RStride: nalgebra::Dim,
566 CStride: nalgebra::Dim,
567 {
568 unsafe { self.array.try_as_matrix_mut() }
569 }
570}
571
572#[cfg(feature = "nalgebra")]
573impl<'py, N> PyReadwriteArray<'py, N, Ix1>
574where
575 N: nalgebra::Scalar + Element,
576{
577 /// Convert this one-dimensional array into a [`nalgebra::DMatrixViewMut`] using dynamic strides.
578 ///
579 /// # Panics
580 ///
581 /// Panics if the array has negative strides.
582 #[doc(alias = "nalgebra")]
583 pub fn as_matrix_mut(&self) -> nalgebra::DMatrixViewMut<'_, N, nalgebra::Dyn, nalgebra::Dyn> {
584 self.try_as_matrix_mut().unwrap()
585 }
586}
587
588#[cfg(feature = "nalgebra")]
589impl<'py, N> PyReadwriteArray<'py, N, Ix2>
590where
591 N: nalgebra::Scalar + Element,
592{
593 /// Convert this two-dimensional array into a [`nalgebra::DMatrixViewMut`] using dynamic strides.
594 ///
595 /// # Panics
596 ///
597 /// Panics if the array has negative strides.
598 #[doc(alias = "nalgebra")]
599 pub fn as_matrix_mut(&self) -> nalgebra::DMatrixViewMut<'_, N, nalgebra::Dyn, nalgebra::Dyn> {
600 self.try_as_matrix_mut().unwrap()
601 }
602}
603
604impl<'py, T> PyReadwriteArray<'py, T, Ix1>
605where
606 T: Element,
607{
608 /// Extends or truncates the dimensions of an array.
609 ///
610 /// Safe wrapper for [`PyArrayMethods::resize`].
611 ///
612 /// Note that as this mutates a pointed-to object, the [`PyReadwriteArray`] must be the only
613 /// Python reference to the object. There cannot be `PyArray` pointers or even `Bound<PyAny>`
614 /// pointing to the same object; this means for example that an object received from a PyO3
615 /// `pyfunction` cannot call this method, since the PyO3 wrapper maintains a reference itself.
616 /// Attempting to call this method when there are other Python references is still safe; NumPy
617 /// will raise a Python-space exception.
618 ///
619 /// # Example
620 ///
621 /// ```
622 /// use numpy::{PyArray, PyArrayMethods, PyUntypedArrayMethods};
623 /// use pyo3::Python;
624 ///
625 /// Python::attach(|py| {
626 /// let pyarray = PyArray::arange(py, 0, 10, 1);
627 /// assert_eq!(pyarray.len(), 10);
628 ///
629 /// let pyarray = pyarray.into_readwrite();
630 /// let pyarray = pyarray.resize(100).unwrap();
631 /// assert_eq!(pyarray.len(), 100);
632 /// });
633 /// ```
634 pub fn resize<ID: IntoDimension>(self, dims: ID) -> PyResult<Self> {
635 // SAFETY: Ownership of `self` proves exclusive access to the interior of the array.
636 unsafe {
637 self.array.resize(dims)?;
638 }
639
640 let py = self.array.py();
641 let ptr = self.array.as_array_ptr();
642
643 // Update the borrow metadata to match the shape change.
644 release_mut(py, ptr);
645 acquire_mut(py, ptr).unwrap();
646
647 Ok(self)
648 }
649}
650
651impl<'py, T, D> Drop for PyReadwriteArray<'py, T, D>
652where
653 T: Element,
654 D: Dimension,
655{
656 fn drop(&mut self) {
657 release_mut(self.array.py(), self.array.as_array_ptr());
658 }
659}
660
661impl<'py, T, D> fmt::Debug for PyReadwriteArray<'py, T, D>
662where
663 T: Element,
664 D: Dimension,
665{
666 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
667 let name = format!(
668 "PyReadwriteArray<{}, {}>",
669 type_name::<T>(),
670 type_name::<D>()
671 );
672
673 f.debug_struct(&name).finish()
674 }
675}
676
677#[cfg(test)]
678mod tests {
679 use super::*;
680
681 use pyo3::{
682 Python,
683 types::{IntoPyDict, PyAnyMethods},
684 };
685
686 use crate::array::PyArray1;
687
688 #[test]
689 fn test_debug_formatting() {
690 Python::attach(|py| {
691 let array = PyArray::<f64, _>::zeros(py, (1, 2, 3), false);
692
693 {
694 let shared = array.readonly();
695
696 assert_eq!(
697 format!("{shared:?}"),
698 "PyReadonlyArray<f64, ndarray::dimension::dim::Dim<[usize; 3]>>"
699 );
700 }
701
702 {
703 let exclusive = array.readwrite();
704
705 assert_eq!(
706 format!("{exclusive:?}"),
707 "PyReadwriteArray<f64, ndarray::dimension::dim::Dim<[usize; 3]>>"
708 );
709 }
710 });
711 }
712
713 #[test]
714 #[should_panic(expected = "AlreadyBorrowed")]
715 fn cannot_clone_exclusive_borrow_via_deref() {
716 Python::attach(|py| {
717 let array = PyArray::<f64, _>::zeros(py, (3, 2, 1), false);
718
719 let exclusive = array.readwrite();
720 let _shared = exclusive.clone();
721 });
722 }
723
724 #[test]
725 fn failed_resize_does_not_double_release() {
726 Python::attach(|py| {
727 let array = PyArray::<f64, _>::zeros(py, 10, false);
728
729 // The view will make the internal reference check of `PyArray_Resize` fail.
730 let locals = [("array", &array)].into_py_dict(py).unwrap();
731 let _view = py
732 .eval(c"array[:]", None, Some(&locals))
733 .unwrap()
734 .cast_into::<PyArray1<f64>>()
735 .unwrap();
736
737 let exclusive = array.into_readwrite();
738 assert!(exclusive.resize(100).is_err());
739 });
740 }
741
742 #[test]
743 fn ineffective_resize_does_not_conflict() {
744 Python::attach(|py| {
745 let array = PyArray::<f64, _>::zeros(py, 10, false);
746
747 let exclusive = array.into_readwrite();
748 assert!(exclusive.resize(10).is_ok());
749 });
750 }
751
752 #[test]
753 fn extraction_reports_dtype_mismatch() {
754 Python::attach(|py| {
755 let array = PyArray::<f64, _>::zeros(py, (2, 2), false);
756 let any = array.as_any();
757
758 let err = any.extract::<PyReadonlyArray2<'_, f32>>().unwrap_err();
759 let msg = err.to_string();
760 assert_eq!(msg, "TypeError: type mismatch:\n from=float64, to=float32");
761
762 let err = any.extract::<PyReadwriteArray2<'_, f32>>().unwrap_err();
763 let msg = err.to_string();
764 assert_eq!(msg, "TypeError: type mismatch:\n from=float64, to=float32");
765 });
766 }
767
768 #[test]
769 fn extraction_reports_dimensionality_mismatch() {
770 Python::attach(|py| {
771 let array = PyArray::<f64, _>::zeros(py, (2, 2), false);
772 let any = array.as_any();
773
774 let err = any.extract::<PyReadonlyArray3<'_, f64>>().unwrap_err();
775 let msg = err.to_string();
776 assert_eq!(msg, "TypeError: dimensionality mismatch:\n from=2, to=3");
777
778 let err = any.extract::<PyReadwriteArray3<'_, f64>>().unwrap_err();
779 let msg = err.to_string();
780 assert_eq!(msg, "TypeError: dimensionality mismatch:\n from=2, to=3");
781 });
782 }
783}