From 327ab1006207b0d0563b18ea419976b61f6f1803 Mon Sep 17 00:00:00 2001 From: Jake Lishman Date: Fri, 11 Oct 2024 18:55:05 +0100 Subject: [PATCH] Add `From` for `PyReadonlyArray` The ordering of drops is important for the dynamic checker, so this is a convenience for conversion. --- src/borrow/mod.rs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/borrow/mod.rs b/src/borrow/mod.rs index 8dd28b294..bcfb4028c 100644 --- a/src/borrow/mod.rs +++ b/src/borrow/mod.rs @@ -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}; @@ -454,6 +454,18 @@ where unsafe { &*(self as *const Self as *const Self::Target) } } } +impl<'py, T, D> From> 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 { @@ -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() } }