Skip to content

Commit 34394f0

Browse files
committed
Expose fallible variants of the array borrowing methods.
1 parent 7a5e011 commit 34394f0

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

src/array.rs

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ use crate::borrow::{PyReadonlyArray, PyReadwriteArray};
2323
use crate::cold;
2424
use crate::convert::{ArrayExt, IntoPyArray, NpyIndex, ToNpyDims, ToPyArray};
2525
use crate::dtype::{Element, PyArrayDescr};
26-
use crate::error::{DimensionalityError, FromVecError, NotContiguousError, TypeError};
26+
use crate::error::{BorrowError, DimensionalityError, FromVecError, NotContiguousError, TypeError};
2727
use crate::npyffi::{self, npy_intp, NPY_ORDER, PY_ARRAY_API};
2828
use crate::slice_container::PySliceContainer;
2929

@@ -846,13 +846,33 @@ impl<T: Element, D: Dimension> PyArray<T, D> {
846846
}
847847

848848
/// Get an immutable borrow of the NumPy array
849+
pub fn try_readonly(&self) -> Result<PyReadonlyArray<'_, T, D>, BorrowError> {
850+
PyReadonlyArray::try_new(self)
851+
}
852+
853+
/// Get an immutable borrow of the NumPy array
854+
///
855+
/// # Panics
856+
///
857+
/// Panics if the allocation backing the array is currently mutably borrowed.
858+
/// For a non-panicking variant, use [`try_readonly`][Self::try_readonly].
849859
pub fn readonly(&self) -> PyReadonlyArray<'_, T, D> {
850-
PyReadonlyArray::try_new(self).unwrap()
860+
self.try_readonly().unwrap()
851861
}
852862

853863
/// Get a mutable borrow of the NumPy array
864+
pub fn try_readwrite(&self) -> Result<PyReadwriteArray<'_, T, D>, BorrowError> {
865+
PyReadwriteArray::try_new(self)
866+
}
867+
868+
/// Get a mutable borrow of the NumPy array
869+
///
870+
/// # Panics
871+
///
872+
/// Panics if the allocation backing the array is currently borrowed.
873+
/// For a non-panicking variant, use [`try_readwrite`][Self::try_readwrite].
854874
pub fn readwrite(&self) -> PyReadwriteArray<'_, T, D> {
855-
PyReadwriteArray::try_new(self).unwrap()
875+
self.try_readwrite().unwrap()
856876
}
857877

858878
/// Returns the internal array as [`ArrayView`].

0 commit comments

Comments
 (0)