|
| 1 | +use std::cell::UnsafeCell; |
| 2 | +use std::collections::hash_map::{Entry, HashMap}; |
| 3 | +use std::ops::Deref; |
| 4 | + |
| 5 | +use ndarray::{ArrayView, ArrayViewMut, Dimension, Ix1, Ix2, IxDyn}; |
| 6 | +use pyo3::{FromPyObject, PyAny, PyResult}; |
| 7 | + |
| 8 | +use crate::array::PyArray; |
| 9 | +use crate::dtype::Element; |
| 10 | +use crate::error::{BorrowError, NotContiguousError}; |
| 11 | +use crate::npyffi::{self, PyArrayObject, NPY_ARRAY_WRITEABLE}; |
| 12 | + |
| 13 | +struct BorrowFlags(UnsafeCell<Option<HashMap<usize, isize>>>); |
| 14 | + |
| 15 | +unsafe impl Sync for BorrowFlags {} |
| 16 | + |
| 17 | +impl BorrowFlags { |
| 18 | + const fn new() -> Self { |
| 19 | + Self(UnsafeCell::new(None)) |
| 20 | + } |
| 21 | + |
| 22 | + #[allow(clippy::mut_from_ref)] |
| 23 | + unsafe fn get(&self) -> &mut HashMap<usize, isize> { |
| 24 | + (*self.0.get()).get_or_insert_with(HashMap::new) |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +static BORROW_FLAGS: BorrowFlags = BorrowFlags::new(); |
| 29 | + |
| 30 | +pub struct PyReadonlyArray<'py, T, D>(&'py PyArray<T, D>); |
| 31 | + |
| 32 | +pub type PyReadonlyArray1<'py, T> = PyReadonlyArray<'py, T, Ix1>; |
| 33 | + |
| 34 | +pub type PyReadonlyArray2<'py, T> = PyReadonlyArray<'py, T, Ix2>; |
| 35 | + |
| 36 | +pub type PyReadonlyArrayDyn<'py, T> = PyReadonlyArray<'py, T, IxDyn>; |
| 37 | + |
| 38 | +impl<'py, T, D> Deref for PyReadonlyArray<'py, T, D> { |
| 39 | + type Target = PyArray<T, D>; |
| 40 | + |
| 41 | + fn deref(&self) -> &Self::Target { |
| 42 | + self.0 |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +impl<'py, T: Element, D: Dimension> FromPyObject<'py> for PyReadonlyArray<'py, T, D> { |
| 47 | + fn extract(obj: &'py PyAny) -> PyResult<Self> { |
| 48 | + let array: &'py PyArray<T, D> = obj.extract()?; |
| 49 | + Ok(array.readonly()) |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +impl<'py, T, D> PyReadonlyArray<'py, T, D> |
| 54 | +where |
| 55 | + T: Element, |
| 56 | + D: Dimension, |
| 57 | +{ |
| 58 | + pub(crate) fn try_new(array: &'py PyArray<T, D>) -> Result<Self, BorrowError> { |
| 59 | + let address = base_address(array); |
| 60 | + |
| 61 | + // SAFETY: Access to a `&'py PyArray<T, D>` implies holding the GIL |
| 62 | + // and we are not calling into user code which might re-enter this function. |
| 63 | + let borrow_flags = unsafe { BORROW_FLAGS.get() }; |
| 64 | + |
| 65 | + match borrow_flags.entry(address) { |
| 66 | + Entry::Occupied(entry) => { |
| 67 | + let readers = entry.into_mut(); |
| 68 | + |
| 69 | + let new_readers = readers.wrapping_add(1); |
| 70 | + |
| 71 | + if new_readers <= 0 { |
| 72 | + cold(); |
| 73 | + return Err(BorrowError::AlreadyBorrowed); |
| 74 | + } |
| 75 | + |
| 76 | + *readers = new_readers; |
| 77 | + } |
| 78 | + Entry::Vacant(entry) => { |
| 79 | + entry.insert(1); |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + Ok(Self(array)) |
| 84 | + } |
| 85 | + |
| 86 | + pub fn as_array(&self) -> ArrayView<T, D> { |
| 87 | + // SAFETY: Global borrow flags ensure aliasing discipline. |
| 88 | + unsafe { self.0.as_array() } |
| 89 | + } |
| 90 | + |
| 91 | + pub fn as_slice(&self) -> Result<&[T], NotContiguousError> { |
| 92 | + // SAFETY: Global borrow flags ensure aliasing discipline. |
| 93 | + unsafe { self.0.as_slice() } |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +impl<'a, T, D> Drop for PyReadonlyArray<'a, T, D> { |
| 98 | + fn drop(&mut self) { |
| 99 | + let address = base_address(self.0); |
| 100 | + |
| 101 | + // SAFETY: Access to a `&'py PyArray<T, D>` implies holding the GIL |
| 102 | + // and we are not calling into user code which might re-enter this function. |
| 103 | + let borrow_flags = unsafe { BORROW_FLAGS.get() }; |
| 104 | + |
| 105 | + let readers = borrow_flags.get_mut(&address).unwrap(); |
| 106 | + |
| 107 | + *readers -= 1; |
| 108 | + |
| 109 | + if *readers == 0 { |
| 110 | + borrow_flags.remove(&address).unwrap(); |
| 111 | + } |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +pub struct PyReadwriteArray<'py, T, D>(&'py PyArray<T, D>); |
| 116 | + |
| 117 | +pub type PyReadwriteArrayDyn<'py, T> = PyReadwriteArray<'py, T, IxDyn>; |
| 118 | + |
| 119 | +impl<'py, T, D> Deref for PyReadwriteArray<'py, T, D> { |
| 120 | + type Target = PyArray<T, D>; |
| 121 | + |
| 122 | + fn deref(&self) -> &Self::Target { |
| 123 | + self.0 |
| 124 | + } |
| 125 | +} |
| 126 | + |
| 127 | +impl<'py, T: Element, D: Dimension> FromPyObject<'py> for PyReadwriteArray<'py, T, D> { |
| 128 | + fn extract(obj: &'py PyAny) -> PyResult<Self> { |
| 129 | + let array: &'py PyArray<T, D> = obj.extract()?; |
| 130 | + Ok(array.readwrite()) |
| 131 | + } |
| 132 | +} |
| 133 | + |
| 134 | +impl<'py, T, D> PyReadwriteArray<'py, T, D> |
| 135 | +where |
| 136 | + T: Element, |
| 137 | + D: Dimension, |
| 138 | +{ |
| 139 | + pub(crate) fn try_new(array: &'py PyArray<T, D>) -> Result<Self, BorrowError> { |
| 140 | + if !array.check_flags(NPY_ARRAY_WRITEABLE) { |
| 141 | + return Err(BorrowError::NotWriteable); |
| 142 | + } |
| 143 | + |
| 144 | + let address = base_address(array); |
| 145 | + |
| 146 | + // SAFETY: Access to a `&'py PyArray<T, D>` implies holding the GIL |
| 147 | + // and we are not calling into user code which might re-enter this function. |
| 148 | + let borrow_flags = unsafe { BORROW_FLAGS.get() }; |
| 149 | + |
| 150 | + match borrow_flags.entry(address) { |
| 151 | + Entry::Occupied(entry) => { |
| 152 | + let writers = entry.into_mut(); |
| 153 | + |
| 154 | + if *writers != 0 { |
| 155 | + cold(); |
| 156 | + return Err(BorrowError::AlreadyBorrowed); |
| 157 | + } |
| 158 | + |
| 159 | + *writers = -1; |
| 160 | + } |
| 161 | + Entry::Vacant(entry) => { |
| 162 | + entry.insert(-1); |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + Ok(Self(array)) |
| 167 | + } |
| 168 | + |
| 169 | + pub fn as_array(&self) -> ArrayView<T, D> { |
| 170 | + // SAFETY: Global borrow flags ensure aliasing discipline. |
| 171 | + unsafe { self.0.as_array() } |
| 172 | + } |
| 173 | + |
| 174 | + pub fn as_slice(&self) -> Result<&[T], NotContiguousError> { |
| 175 | + // SAFETY: Global borrow flags ensure aliasing discipline. |
| 176 | + unsafe { self.0.as_slice() } |
| 177 | + } |
| 178 | + |
| 179 | + pub fn as_array_mut(&mut self) -> ArrayViewMut<T, D> { |
| 180 | + // SAFETY: Global borrow flags ensure aliasing discipline. |
| 181 | + unsafe { self.0.as_array_mut() } |
| 182 | + } |
| 183 | + |
| 184 | + pub fn as_slice_mut(&self) -> Result<&mut [T], NotContiguousError> { |
| 185 | + // SAFETY: Global borrow flags ensure aliasing discipline. |
| 186 | + unsafe { self.0.as_slice_mut() } |
| 187 | + } |
| 188 | +} |
| 189 | + |
| 190 | +impl<'a, T, D> Drop for PyReadwriteArray<'a, T, D> { |
| 191 | + fn drop(&mut self) { |
| 192 | + let address = base_address(self.0); |
| 193 | + |
| 194 | + // SAFETY: Access to a `&'py PyArray<T, D>` implies holding the GIL |
| 195 | + // and we are not calling into user code which might re-enter this function. |
| 196 | + let borrow_flags = unsafe { BORROW_FLAGS.get() }; |
| 197 | + |
| 198 | + borrow_flags.remove(&address).unwrap(); |
| 199 | + } |
| 200 | +} |
| 201 | + |
| 202 | +// FIXME(adamreichold): This is a coarse approximation and needs to be refined, |
| 203 | +// i.e. borrows of non-overlapping views into the same base should not be considered conflicting. |
| 204 | +fn base_address<T, D>(array: &PyArray<T, D>) -> usize { |
| 205 | + let py = array.py(); |
| 206 | + let mut array = array.as_array_ptr(); |
| 207 | + |
| 208 | + loop { |
| 209 | + let base = unsafe { (*array).base }; |
| 210 | + |
| 211 | + if base.is_null() { |
| 212 | + return unsafe { (*array).data } as usize; |
| 213 | + } else if unsafe { npyffi::PyArray_Check(py, base) } != 0 { |
| 214 | + array = base as *mut PyArrayObject; |
| 215 | + } else { |
| 216 | + return base as usize; |
| 217 | + } |
| 218 | + } |
| 219 | +} |
| 220 | + |
| 221 | +#[cold] |
| 222 | +#[inline(always)] |
| 223 | +fn cold() {} |
0 commit comments