Skip to content

Commit

Permalink
Add From<PyReadwriteArray> for PyReadonlyArray
Browse files Browse the repository at this point in the history
The ordering of drops is important for the dynamic checker, so this is a
convenience for conversion.
  • Loading branch information
jakelishman authored and davidhewitt committed Oct 27, 2024
1 parent a4b922f commit 327ab10
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions src/borrow/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,8 @@ use crate::array::{PyArray, PyArrayMethods};
use crate::convert::NpyIndex;
use crate::dtype::Element;
use crate::error::{BorrowError, NotContiguousError};
use crate::untyped_array::PyUntypedArrayMethods;
use crate::npyffi::flags;
use crate::untyped_array::PyUntypedArrayMethods;

use shared::{acquire, acquire_mut, release, release_mut};

Expand Down Expand Up @@ -454,6 +454,18 @@ where
unsafe { &*(self as *const Self as *const Self::Target) }
}
}
impl<'py, T, D> From<PyReadwriteArray<'py, T, D>> for PyReadonlyArray<'py, T, D>
where
T: Element,
D: Dimension,
{
fn from(value: PyReadwriteArray<'py, T, D>) -> Self {
let array = value.array.clone();
::std::mem::drop(value);
Self::try_new(array)
.expect("releasing an exclusive reference should immediately permit a shared reference")
}
}

impl<'py, T: Element, D: Dimension> FromPyObject<'py> for PyReadwriteArray<'py, T, D> {
fn extract_bound(obj: &Bound<'py, PyAny>) -> PyResult<Self> {
Expand Down Expand Up @@ -504,12 +516,13 @@ where
///
/// [writeable]: https://numpy.org/doc/stable/reference/c-api/array.html#c.NPY_ARRAY_WRITEABLE
/// [owndata]: https://numpy.org/doc/stable/reference/c-api/array.html#c.NPY_ARRAY_OWNDATA
pub fn make_nonwriteable(self) {
pub fn make_nonwriteable(self) -> PyReadonlyArray<'py, T, D> {
// SAFETY: consuming the only extant mutable reference guarantees we cannot invalidate an
// existing reference, nor allow the caller to keep hold of one.
unsafe {
(*self.as_array_ptr()).flags &= !flags::NPY_ARRAY_WRITEABLE;
}
self.into()
}
}

Expand Down

0 comments on commit 327ab10

Please sign in to comment.