|
15 | 15 | //! ```rust |
16 | 16 | //! # use std::panic::{catch_unwind, AssertUnwindSafe}; |
17 | 17 | //! # |
18 | | -//! use numpy::{PyArray1, PyArrayMethods}; |
| 18 | +//! use numpy::{PyArray1, PyArrayMethods, npyffi::flags}; |
19 | 19 | //! use ndarray::Zip; |
20 | 20 | //! use pyo3::{Python, Bound}; |
21 | 21 | //! |
@@ -176,6 +176,7 @@ use crate::convert::NpyIndex; |
176 | 176 | use crate::dtype::Element; |
177 | 177 | use crate::error::{BorrowError, NotContiguousError}; |
178 | 178 | use crate::untyped_array::PyUntypedArrayMethods; |
| 179 | +use crate::npyffi::flags; |
179 | 180 |
|
180 | 181 | use shared::{acquire, acquire_mut, release, release_mut}; |
181 | 182 |
|
@@ -494,6 +495,22 @@ where |
494 | 495 | { |
495 | 496 | unsafe { self.array.get_mut(index) } |
496 | 497 | } |
| 498 | + |
| 499 | + /// Clear the [`WRITEABLE` flag][writeable] from the underlying NumPy array. |
| 500 | + /// |
| 501 | + /// Calling this will prevent any further [PyReadwriteArray]s from being taken out. Python |
| 502 | + /// space can reset this flag, unless the additional flag [`OWNDATA`][owndata] is unset. Such |
| 503 | + /// an array can be created from Rust space by using [PyArray::borrow_from_array_bound]. |
| 504 | + /// |
| 505 | + /// [writeable]: https://numpy.org/doc/stable/reference/c-api/array.html#c.NPY_ARRAY_WRITEABLE |
| 506 | + /// [owndata]: https://numpy.org/doc/stable/reference/c-api/array.html#c.NPY_ARRAY_OWNDATA |
| 507 | + pub fn make_nonwriteable(self) { |
| 508 | + // SAFETY: consuming the only extant mutable reference guarantees we cannot invalidate an |
| 509 | + // existing reference, nor allow the caller to keep hold of one. |
| 510 | + unsafe { |
| 511 | + (*self.as_array_ptr()).flags &= !flags::NPY_ARRAY_WRITEABLE; |
| 512 | + } |
| 513 | + } |
497 | 514 | } |
498 | 515 |
|
499 | 516 | #[cfg(feature = "nalgebra")] |
|
0 commit comments