| 1 |
// Copyright (c) 2019 Raphaël Gomès <[email protected]>, |
| 2 |
// Yuya Nishihara <[email protected]> |
| 3 |
// 2024 Georges Racinet <[email protected]> |
| 4 |
// |
| 5 |
// Permission is hereby granted, free of charge, to any person obtaining a copy |
| 6 |
// of this software and associated documentation files (the "Software"), to |
| 7 |
// deal in the Software without restriction, including without limitation the |
| 8 |
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or |
| 9 |
// sell copies of the Software, and to permit persons to whom the Software is |
| 10 |
// furnished to do so, subject to the following conditions: |
| 11 |
// |
| 12 |
// The above copyright notice and this permission notice shall be included in |
| 13 |
// all copies or substantial portions of the Software. |
| 14 |
// |
| 15 |
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 16 |
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 17 |
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 18 |
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 19 |
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
| 20 |
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS |
| 21 |
// IN THE SOFTWARE. |
| 22 |
|
| 23 |
//! Utility to share Rust reference across Python objects. |
| 24 |
|
| 25 |
use std::ops::Deref; |
| 26 |
use std::ops::DerefMut; |
| 27 |
use std::sync::atomic::AtomicUsize; |
| 28 |
use std::sync::atomic::Ordering; |
| 29 |
use std::sync::RwLock; |
| 30 |
use std::sync::RwLockReadGuard; |
| 31 |
use std::sync::RwLockWriteGuard; |
| 32 |
use std::sync::TryLockError; |
| 33 |
use std::sync::TryLockResult; |
| 34 |
|
| 35 |
use pyo3::exceptions::PyRuntimeError; |
| 36 |
use pyo3::prelude::*; |
| 37 |
|
| 38 |
/// A mutable memory location shareable immutably across Python objects. |
| 39 |
/// |
| 40 |
/// This data structure is meant to be used as a field in a Python class |
| 41 |
/// definition. |
| 42 |
/// It provides interior mutability in a way that allows it to be immutably |
| 43 |
/// referenced by other Python objects defined in Rust than its owner, in |
| 44 |
/// a more general form than references to the whole data. |
| 45 |
/// These immutable references are stored in the referencing Python objects as |
| 46 |
/// [`SharedByPyObject`] fields. |
| 47 |
/// |
| 48 |
/// The primary use case is to implement a Python iterator over a Rust |
| 49 |
/// iterator: since a Python object cannot hold a lifetime-bound object, |
| 50 |
/// `Iter<'a, T>` cannot be a data field of the Python iterator object. |
| 51 |
/// While `&'a T` can be replaced with [`std::sync::Arc`], this is typically |
| 52 |
/// not suited for more complex objects that are created from such references |
| 53 |
/// and re-expose the lifetime on their types, such as iterators. |
| 54 |
/// The [`PyShareableRef::share_immutable()`] and |
| 55 |
/// [`SharedByPyObject::map()`] methods provide a way around this issue. |
| 56 |
/// |
| 57 |
/// [`PyShareable`] is [`Sync`]. It works internally with locks and |
| 58 |
/// a "generation" counter that keeps track of mutations. |
| 59 |
/// |
| 60 |
/// [`PyShareable`] is merely a data struct to be stored in its |
| 61 |
/// owner Python object. |
| 62 |
/// Any further operation will be performed through [`PyShareableRef`], which |
| 63 |
/// is a lifetime-bound reference to the [`PyShareable`]. |
| 64 |
/// |
| 65 |
/// # Example |
| 66 |
/// |
| 67 |
/// ``` |
| 68 |
/// use pyo3::prelude::*; |
| 69 |
/// use pyo3_sharedref::*; |
| 70 |
/// |
| 71 |
/// use pyo3::ffi::c_str; |
| 72 |
/// use pyo3::types::PyDictMethods; |
| 73 |
/// use pyo3::types::{PyDict, PyTuple}; |
| 74 |
/// use std::collections::{hash_set::Iter as IterHashSet, HashSet}; |
| 75 |
/// use pyo3::exceptions::PyRuntimeError; |
| 76 |
/// use std::ffi::CStr; |
| 77 |
/// use std::vec::Vec; |
| 78 |
/// |
| 79 |
/// #[pyclass(sequence)] |
| 80 |
/// struct Set { |
| 81 |
/// rust_set: PyShareable<HashSet<i32>>, |
| 82 |
/// } |
| 83 |
/// |
| 84 |
/// #[pymethods] |
| 85 |
/// impl Set { |
| 86 |
/// #[new] |
| 87 |
/// fn new(values: &Bound<'_, PyTuple>) -> PyResult<Self> { |
| 88 |
/// let as_vec = values.extract::<Vec<i32>>()?; |
| 89 |
/// let s: HashSet<_> = as_vec.iter().copied().collect(); |
| 90 |
/// Ok(Self { rust_set: s.into() }) |
| 91 |
/// } |
| 92 |
/// |
| 93 |
/// fn __iter__(slf: &Bound<'_, Self>) -> SetIterator { |
| 94 |
/// SetIterator::new(slf) |
| 95 |
/// } |
| 96 |
/// |
| 97 |
/// fn add(slf: &Bound<'_, Self>, i: i32) -> PyResult<()> { |
| 98 |
/// let rust_set = &slf.borrow().rust_set; |
| 99 |
/// let shared_ref = unsafe { rust_set.borrow_with_owner(slf) }; |
| 100 |
/// let mut set_ref = shared_ref.write(); |
| 101 |
/// set_ref.insert(i); |
| 102 |
/// Ok(()) |
| 103 |
/// } |
| 104 |
/// } |
| 105 |
/// |
| 106 |
/// #[pyclass] |
| 107 |
/// struct SetIterator { |
| 108 |
/// rust_iter: SharedByPyObject<IterHashSet<'static, i32>>, |
| 109 |
/// } |
| 110 |
/// |
| 111 |
/// #[pymethods] |
| 112 |
/// impl SetIterator { |
| 113 |
/// #[new] |
| 114 |
/// fn new(s: &Bound<'_, Set>) -> Self { |
| 115 |
/// let py = s.py(); |
| 116 |
/// let rust_set = &s.borrow().rust_set; |
| 117 |
/// let iter = unsafe { rust_set.share_map(s, |o| o.iter()) }; |
| 118 |
/// Self { |
| 119 |
/// rust_iter: iter.into(), |
| 120 |
/// } |
| 121 |
/// } |
| 122 |
/// |
| 123 |
/// fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> { |
| 124 |
/// slf |
| 125 |
/// } |
| 126 |
/// |
| 127 |
/// fn __next__(mut slf: PyRefMut<'_, Self>) -> PyResult<Option<i32>> { |
| 128 |
/// let py = slf.py(); |
| 129 |
/// let shared = &mut slf.rust_iter; |
| 130 |
/// let mut inner = unsafe { shared.try_borrow_mut(py) }?; |
| 131 |
/// Ok(inner.next().copied()) |
| 132 |
/// } |
| 133 |
/// } |
| 134 |
/// |
| 135 |
/// /// a shortcut similar to `[pyo3::py_run!]`, allowing inspection of PyErr |
| 136 |
/// fn py_run(statement: &CStr, locals: &Bound<'_, PyDict>) -> PyResult<()> { |
| 137 |
/// locals.py().run(statement, None, Some(locals)) |
| 138 |
/// } |
| 139 |
/// |
| 140 |
/// # pyo3::prepare_freethreaded_python(); |
| 141 |
/// Python::with_gil(|py| { |
| 142 |
/// let tuple = PyTuple::new(py, vec![2, 1, 2])?; |
| 143 |
/// let set = Bound::new(py, Set::new(&tuple)?)?; |
| 144 |
/// let iter = Bound::new(py, Set::__iter__(&set))?; |
| 145 |
/// let locals = PyDict::new(py); |
| 146 |
/// locals.set_item("rust_set", set).unwrap(); |
| 147 |
/// locals.set_item("rust_iter", iter).unwrap(); |
| 148 |
/// |
| 149 |
/// /// iterating on our Rust set just works |
| 150 |
/// py_run( |
| 151 |
/// c_str!("assert sorted(i for i in rust_iter) == [1, 2]"), |
| 152 |
/// &locals, |
| 153 |
/// )?; |
| 154 |
/// |
| 155 |
/// /// however, if any mutation occurs on the Rust set, the iterator |
| 156 |
/// /// becomes invalid. Attempts to use it raise `RuntimeError`. |
| 157 |
/// py_run(c_str!("rust_set.add(3)"), &locals)?; |
| 158 |
/// let err = py_run(c_str!("next(rust_iter)"), &locals).unwrap_err(); |
| 159 |
/// |
| 160 |
/// let exc_repr = format!("{:?}", err.value(py)); |
| 161 |
/// assert_eq!( |
| 162 |
/// exc_repr, |
| 163 |
/// "RuntimeError('Cannot access to shared reference after mutation')" |
| 164 |
/// ); |
| 165 |
/// # Ok::<(), PyErr>(()) |
| 166 |
/// }) |
| 167 |
/// # .expect("This example should not return an error"); |
| 168 |
/// ``` |
| 169 |
/// |
| 170 |
/// The borrow rules are enforced dynamically in a similar manner to the |
| 171 |
/// Python iterator. |
| 172 |
/// |
| 173 |
/// [`PyShareable`] is merely a data struct to be stored in a Python object. |
| 174 |
/// Any further operation will be performed through [PyShareableRef], which is |
| 175 |
/// a lifetime-bound reference to the [`PyShareable`]. |
| 176 |
#[derive(Debug)] |
| 177 |
pub struct PyShareable<T: ?Sized> { |
| 178 |
state: PySharedState, |
| 179 |
data: RwLock<T>, |
| 180 |
} |
| 181 |
|
| 182 |
impl<T: 'static> PyShareable<T> { |
| 183 |
/// Borrows the shared data and its state, keeping a reference |
| 184 |
/// on the owner Python object. |
| 185 |
/// |
| 186 |
/// # Safety |
| 187 |
/// |
| 188 |
/// The `data` must be owned by the `owner`. Otherwise, calling |
| 189 |
/// `share_immutable()` on the shared ref would create an invalid |
| 190 |
/// reference. |
| 191 |
pub unsafe fn borrow_with_owner<'py>( |
| 192 |
&'py self, |
| 193 |
owner: &'py Bound<'py, PyAny>, |
| 194 |
) -> PyShareableRef<'py, T> { |
| 195 |
PyShareableRef { owner, state: &self.state, data: &self.data } |
| 196 |
} |
| 197 |
|
| 198 |
/// Share for other Python objects |
| 199 |
/// |
| 200 |
/// # Safety |
| 201 |
/// |
| 202 |
/// The `data` must be owned by the `owner`. Otherwise, the resulting |
| 203 |
/// [`SharedByPyObject`] would contain an invalid reference. |
| 204 |
pub unsafe fn share<'py>( |
| 205 |
&'py self, |
| 206 |
owner: &'py Bound<'py, PyAny>, |
| 207 |
) -> SharedByPyObject<&'static T> { |
| 208 |
unsafe { self.borrow_with_owner(owner).share_immutable() } |
| 209 |
} |
| 210 |
|
| 211 |
/// Share for other Python objects, transforming the inner data |
| 212 |
/// with a closure |
| 213 |
/// |
| 214 |
/// # Safety |
| 215 |
/// |
| 216 |
/// The `data` must be owned by the `owner`. Otherwise, the resulting |
| 217 |
/// [`SharedByPyObject`] would contain an invalid reference. |
| 218 |
pub unsafe fn share_map<'py, U>( |
| 219 |
&'py self, |
| 220 |
owner: &'py Bound<'py, PyAny>, |
| 221 |
f: impl FnOnce(&'static T) -> U, |
| 222 |
) -> SharedByPyObject<U> { |
| 223 |
unsafe { self.share(owner).map(owner.py(), f) } |
| 224 |
} |
| 225 |
|
| 226 |
/// # Safety |
| 227 |
/// |
| 228 |
/// The `data` must be owned by the `owner`. Otherwise, the resulting |
| 229 |
/// [`SharedByPyObject`] would contain an invalid reference. |
| 230 |
pub unsafe fn try_share<'py>( |
| 231 |
&'py self, |
| 232 |
owner: &'py Bound<'py, PyAny>, |
| 233 |
) -> Result<SharedByPyObject<&'static T>, TryShareError> { |
| 234 |
unsafe { self.borrow_with_owner(owner).try_share_immutable() } |
| 235 |
} |
| 236 |
|
| 237 |
/// # Safety |
| 238 |
/// |
| 239 |
/// The `data` must be owned by the `owner`. Otherwise, the resulting |
| 240 |
/// [`SharedByPyObject`] would contain an invalid reference. |
| 241 |
pub unsafe fn try_share_map<'py, U>( |
| 242 |
&'py self, |
| 243 |
owner: &'py Bound<'py, PyAny>, |
| 244 |
f: impl FnOnce(&'static T) -> U, |
| 245 |
) -> Result<SharedByPyObject<U>, TryShareError> { |
| 246 |
unsafe { Ok(self.try_share(owner)?.map(owner.py(), f)) } |
| 247 |
} |
| 248 |
} |
| 249 |
|
| 250 |
impl<T> From<T> for PyShareable<T> { |
| 251 |
fn from(value: T) -> Self { |
| 252 |
Self { state: PySharedState::new(), data: value.into() } |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
/// Errors that can happen in `share_immutable()` |
| 257 |
#[derive(Debug, PartialEq, Eq)] |
| 258 |
pub enum TryShareError { |
| 259 |
/// The inner lock is poisoned and we do not want to implement recovery |
| 260 |
InnerLockPoisoned, |
| 261 |
/// The inner lock would block and we are expecting to take it immediately |
| 262 |
InnerLockWouldBlock, |
| 263 |
} |
| 264 |
|
| 265 |
impl<T> From<TryLockError<T>> for TryShareError { |
| 266 |
fn from(e: TryLockError<T>) -> Self { |
| 267 |
match e { |
| 268 |
TryLockError::Poisoned(_) => Self::InnerLockPoisoned, |
| 269 |
TryLockError::WouldBlock => Self::InnerLockWouldBlock, |
| 270 |
} |
| 271 |
} |
| 272 |
} |
| 273 |
|
| 274 |
/// A reference to [`PyShareable`] and its legit owner Python object. |
| 275 |
/// |
| 276 |
/// This is a lifetime-bound reference to the [PyShareable] data field, |
| 277 |
/// and could be created by an automatically generated accessor when |
| 278 |
/// we make one. |
| 279 |
pub struct PyShareableRef<'py, T: 'py + ?Sized> { |
| 280 |
owner: &'py Bound<'py, PyAny>, |
| 281 |
state: &'py PySharedState, |
| 282 |
data: &'py RwLock<T>, // TODO perhaps this needs Pin |
| 283 |
} |
| 284 |
|
| 285 |
impl<'py, T: ?Sized> PyShareableRef<'py, T> { |
| 286 |
/// Take the lock on the wrapped value for read-only operations. |
| 287 |
/// |
| 288 |
/// # Panics |
| 289 |
/// |
| 290 |
/// Panics if the lock is currently held for write operations. |
| 291 |
pub fn read(&self) -> RwLockReadGuard<'py, T> { |
| 292 |
self.try_read().expect("already mutably borrowed") |
| 293 |
} |
| 294 |
|
| 295 |
/// Immutably borrows the wrapped value, returning an error if the value |
| 296 |
/// is currently mutably borrowed. |
| 297 |
pub fn try_read(&self) -> TryLockResult<RwLockReadGuard<'py, T>> { |
| 298 |
// state isn't involved since |
| 299 |
// - data.try_read() would fail if self is mutably borrowed, |
| 300 |
// - and data.try_write() would fail while self is borrowed. |
| 301 |
self.data.try_read() |
| 302 |
} |
| 303 |
|
| 304 |
/// Take the lock on the wrapped value for write operations. |
| 305 |
/// |
| 306 |
/// Any existing shared references will be invalidated. |
| 307 |
/// |
| 308 |
/// # Panics |
| 309 |
/// |
| 310 |
/// Panics if the lock is currently held. |
| 311 |
pub fn write(&self) -> RwLockWriteGuard<'py, T> { |
| 312 |
self.try_write().expect("already borrowed") |
| 313 |
} |
| 314 |
|
| 315 |
/// Mutably borrows the wrapped value, returning an error if the value |
| 316 |
/// is currently borrowed. |
| 317 |
pub fn try_write(&self) -> TryLockResult<RwLockWriteGuard<'py, T>> { |
| 318 |
// the value may be immutably borrowed through SharedByPyObject |
| 319 |
if self.state.current_borrow_count(self.py()) > 0 { |
| 320 |
// propagate borrow-by-shared state to data to get BorrowMutError |
| 321 |
let _dummy = self.data.read(); |
| 322 |
let _unused = self.data.try_write()?; |
| 323 |
unreachable!("BorrowMutError should have been returned"); |
| 324 |
} |
| 325 |
|
| 326 |
let data_ref = self.data.try_write()?; |
| 327 |
self.state.increment_generation(self.py()); |
| 328 |
Ok(data_ref) |
| 329 |
} |
| 330 |
|
| 331 |
/// Creates an immutable reference which is not bound to lifetime. |
| 332 |
/// |
| 333 |
/// # Panics |
| 334 |
/// |
| 335 |
/// Panics if the value is currently mutably borrowed. |
| 336 |
pub fn share_immutable(&self) -> SharedByPyObject<&'static T> { |
| 337 |
self.try_share_immutable().expect("already mutably borrowed") |
| 338 |
} |
| 339 |
|
| 340 |
/// Creates an immutable reference which is not bound to lifetime, |
| 341 |
/// returning an error if the value is currently mutably borrowed. |
| 342 |
pub fn try_share_immutable( |
| 343 |
&self, |
| 344 |
) -> Result<SharedByPyObject<&'static T>, TryShareError> { |
| 345 |
// make sure self.data isn't mutably borrowed; otherwise the |
| 346 |
// generation number wouldn't be trusted. |
| 347 |
let data_ref = self.try_read()?; |
| 348 |
|
| 349 |
// keep reference to the owner so the data and state are alive, |
| 350 |
// but the data pointer can be invalidated by write(). |
| 351 |
// the state wouldn't since it is immutable. |
| 352 |
let state_ptr: *const PySharedState = self.state; |
| 353 |
let data_ptr: *const T = &*data_ref; |
| 354 |
Ok(SharedByPyObject::<&'static T> { |
| 355 |
owner: self.owner.clone().unbind(), |
| 356 |
state: unsafe { &*state_ptr }, |
| 357 |
generation: self.state.current_generation(self.py()), |
| 358 |
data: unsafe { &*data_ptr }, |
| 359 |
}) |
| 360 |
} |
| 361 |
|
| 362 |
/// Retrieve the GIL handle |
| 363 |
fn py(&self) -> Python<'py> { |
| 364 |
// Since this is a smart pointer implying the GIL lifetime, |
| 365 |
// we might as well use `assume_gil_acquired`, but the method |
| 366 |
// of `Bound` does it for us. |
| 367 |
self.owner.py() |
| 368 |
} |
| 369 |
} |
| 370 |
|
| 371 |
/// The shared state between Python and Rust |
| 372 |
/// |
| 373 |
/// `PySharedState` is owned by `PyShareable`, and is shared across its |
| 374 |
/// derived references. The consistency of these references are guaranteed |
| 375 |
/// as follows: |
| 376 |
/// |
| 377 |
/// - The immutability of `PycCass` object fields. Any mutation of |
| 378 |
/// [`PyShareable`] is allowed only through its `write()`. |
| 379 |
/// - The `py: Python<'_>` token, which makes sure that any data access is |
| 380 |
/// synchronized by the GIL. |
| 381 |
/// - The underlying `RefCell`, which prevents `PyShareable` value from being |
| 382 |
/// directly borrowed or shared while it is mutably borrowed. |
| 383 |
/// - The `borrow_count`, which is the number of references borrowed from |
| 384 |
/// `SharedByPyObject`. Just like `RefCell`, mutation is prohibited while |
| 385 |
/// `SharedByPyObject` is borrowed. |
| 386 |
/// - The `generation` counter, which increments on `write()`. |
| 387 |
/// `SharedByPyObject` |
| 388 |
#[derive(Debug)] |
| 389 |
struct PySharedState { |
| 390 |
// The counter variable could be Cell<usize> since any operation on |
| 391 |
// PySharedState is synchronized by the GIL, but being "atomic" makes |
| 392 |
// PySharedState inherently Sync. The ordering requirement doesn't |
| 393 |
// matter thanks to the GIL. That's why Ordering::Relaxed is used |
| 394 |
// everywhere. |
| 395 |
/// The number of immutable references borrowed through shared reference. |
| 396 |
borrow_count: AtomicUsize, |
| 397 |
/// The mutation counter of the underlying value. |
| 398 |
generation: AtomicUsize, |
| 399 |
} |
| 400 |
|
| 401 |
impl PySharedState { |
| 402 |
const fn new() -> PySharedState { |
| 403 |
PySharedState { |
| 404 |
borrow_count: AtomicUsize::new(0), |
| 405 |
generation: AtomicUsize::new(0), |
| 406 |
} |
| 407 |
} |
| 408 |
|
| 409 |
fn current_borrow_count(&self, _py: Python) -> usize { |
| 410 |
self.borrow_count.load(Ordering::Relaxed) |
| 411 |
} |
| 412 |
|
| 413 |
fn increase_borrow_count(&self, _py: Python) { |
| 414 |
// this wraps around if there are more than usize::MAX borrowed |
| 415 |
// references, which shouldn't happen due to memory limit. |
| 416 |
self.borrow_count.fetch_add(1, Ordering::Relaxed); |
| 417 |
} |
| 418 |
|
| 419 |
fn decrease_borrow_count(&self, _py: Python) { |
| 420 |
let prev_count = self.borrow_count.fetch_sub(1, Ordering::Relaxed); |
| 421 |
assert!(prev_count > 0); |
| 422 |
} |
| 423 |
|
| 424 |
fn current_generation(&self, _py: Python) -> usize { |
| 425 |
self.generation.load(Ordering::Relaxed) |
| 426 |
} |
| 427 |
|
| 428 |
fn increment_generation(&self, py: Python) { |
| 429 |
assert_eq!(self.current_borrow_count(py), 0); |
| 430 |
// this wraps around to the same value if mutably borrowed |
| 431 |
// usize::MAX times, which wouldn't happen in practice. |
| 432 |
self.generation.fetch_add(1, Ordering::Relaxed); |
| 433 |
} |
| 434 |
} |
| 435 |
|
| 436 |
/// Helper to keep the borrow count updated while the shared object is |
| 437 |
/// immutably borrowed without using the `RwLock` interface. |
| 438 |
struct BorrowPyShared<'a> { |
| 439 |
py: Python<'a>, |
| 440 |
state: &'a PySharedState, |
| 441 |
} |
| 442 |
|
| 443 |
impl<'a> BorrowPyShared<'a> { |
| 444 |
fn new(py: Python<'a>, state: &'a PySharedState) -> BorrowPyShared<'a> { |
| 445 |
state.increase_borrow_count(py); |
| 446 |
BorrowPyShared { py, state } |
| 447 |
} |
| 448 |
} |
| 449 |
|
| 450 |
impl Drop for BorrowPyShared<'_> { |
| 451 |
fn drop(&mut self) { |
| 452 |
self.state.decrease_borrow_count(self.py); |
| 453 |
} |
| 454 |
} |
| 455 |
|
| 456 |
/// An immutable reference to [`PyShareable`] value, not bound to lifetime. |
| 457 |
/// |
| 458 |
/// The reference will be invalidated once the original value is mutably |
| 459 |
/// borrowed. |
| 460 |
/// |
| 461 |
/// # Safety |
| 462 |
/// |
| 463 |
/// Even though [`SharedByPyObject`] tries to enforce the real lifetime of the |
| 464 |
/// underlying object, the object having the artificial `'static` lifetime |
| 465 |
/// may be exposed to your Rust code. You must be careful to not make a bare |
| 466 |
/// reference outlive the actual object lifetime. |
| 467 |
/// |
| 468 |
/// See [`Self::try_borrow_mut()`] for an example of the kind of trouble that |
| 469 |
/// can arise. |
| 470 |
pub struct SharedByPyObject<T: ?Sized> { |
| 471 |
owner: Py<PyAny>, |
| 472 |
state: &'static PySharedState, |
| 473 |
/// Generation counter of data `T` captured when SharedByPyObject is |
| 474 |
/// created. |
| 475 |
generation: usize, |
| 476 |
/// Underlying data of artificial lifetime, which is valid only when |
| 477 |
/// state.generation == self.generation. |
| 478 |
data: T, |
| 479 |
} |
| 480 |
|
| 481 |
// DO NOT implement Deref or DerefMut for SharedByPyObject<T>! Dereferencing |
| 482 |
// SharedByPyObject without taking Python GIL wouldn't be safe. Also, the |
| 483 |
// underling reference is invalid if generation != state.generation. |
| 484 |
static_assertions_next::assert_impl!( |
| 485 |
for(T) SharedByPyObject<T>: !Deref |
| 486 |
); |
| 487 |
|
| 488 |
static_assertions_next::assert_impl!( |
| 489 |
for(T) SharedByPyObject<T>: !DerefMut |
| 490 |
); |
| 491 |
|
| 492 |
impl<T: ?Sized> SharedByPyObject<T> { |
| 493 |
// No panicking version of borrow() and borrow_mut() are implemented |
| 494 |
// because the underlying value is supposed to be mutated in Python |
| 495 |
// world, and the Rust library designer can't prevent it. |
| 496 |
|
| 497 |
/// Immutably borrows the wrapped value. |
| 498 |
/// |
| 499 |
/// Borrowing fails if the underlying reference has been invalidated. |
| 500 |
/// |
| 501 |
/// # Safety |
| 502 |
/// |
| 503 |
/// The lifetime of the innermost object is artificial. Do not obtain and |
| 504 |
/// copy it out of the borrow scope. |
| 505 |
/// |
| 506 |
/// The lifetime of the innermost object is artificial. Do not obtain and |
| 507 |
/// copy it out of the borrow scope. More generally, the returned `&T` |
| 508 |
/// may have a method returning an inner reference, which would typically |
| 509 |
/// be `'static` and not safe without the `owner` Python object, so the |
| 510 |
/// problem might be less obvious than in the example below. |
| 511 |
/// |
| 512 |
/// The following example does compile and illustrates the problem. |
| 513 |
/// In this case, the data is a `Vec<String>` and the leaked reference |
| 514 |
/// `&'static str`, which points to some element of the vector. This |
| 515 |
/// illustrates that the leaks are not necessarily to the whole of the |
| 516 |
/// shared data. |
| 517 |
/// |
| 518 |
/// ```no_run |
| 519 |
/// # use pyo3::prelude::*; |
| 520 |
/// # use pyo3_sharedref::PyShareable; |
| 521 |
/// #[pyclass] |
| 522 |
/// struct Owner { |
| 523 |
/// value: PyShareable<Vec<String>> |
| 524 |
/// } |
| 525 |
/// |
| 526 |
/// #[pymethods] |
| 527 |
/// impl Owner { |
| 528 |
/// #[new] |
| 529 |
/// fn new(s: &str) -> Self { |
| 530 |
/// let split: Vec<_> = s.split(' ').map(String::from).collect(); |
| 531 |
/// Self { value: split.into() } |
| 532 |
/// } |
| 533 |
/// } |
| 534 |
/// |
| 535 |
/// const EMPTY: &'static str = ""; |
| 536 |
/// |
| 537 |
/// let mut outer = EMPTY; |
| 538 |
/// Python::with_gil(|py| { |
| 539 |
/// let owner = Bound::new(py, Owner::new("hello")).unwrap(); |
| 540 |
/// let shareable = &owner.borrow().value; |
| 541 |
/// let shared = unsafe { shareable.share(&owner) }; |
| 542 |
/// { |
| 543 |
/// let inner = unsafe { shared.try_borrow(py) }.unwrap(); |
| 544 |
/// outer = &inner[0]; // Bad, &'static str does outlive the scope |
| 545 |
/// } |
| 546 |
/// }); |
| 547 |
/// ``` |
| 548 |
pub unsafe fn try_borrow<'a>( |
| 549 |
&'a self, |
| 550 |
py: Python<'a>, |
| 551 |
) -> PyResult<SharedByPyObjectRef<'a, T>> { |
| 552 |
self.validate_generation(py)?; |
| 553 |
Ok(SharedByPyObjectRef { |
| 554 |
_borrow: BorrowPyShared::new(py, self.state), |
| 555 |
data: &self.data, |
| 556 |
}) |
| 557 |
} |
| 558 |
|
| 559 |
/// Mutably borrows the wrapped value. |
| 560 |
/// |
| 561 |
/// Borrowing fails if the underlying reference has been invalidated. |
| 562 |
/// |
| 563 |
/// Typically `T` would be an iterator obtained by the [`Self::map`] |
| 564 |
/// method. |
| 565 |
/// |
| 566 |
/// # Safety |
| 567 |
/// |
| 568 |
/// The lifetime of the innermost object is artificial. Do not obtain and |
| 569 |
/// copy it out of the borrow scope. More generally, the returned `&T` |
| 570 |
/// may have a method returning an inner reference, which would typically |
| 571 |
/// be `'static` and not safe without the `owner` Python object, so the |
| 572 |
/// problem might be less obvious than in the example below. |
| 573 |
/// |
| 574 |
/// The following example does compile and illustrates the problem. |
| 575 |
/// It is very close to the example given in [`Self::try_borrow`] because |
| 576 |
/// the problem does not arise from the mutability of the reference |
| 577 |
/// returned by this function. |
| 578 |
/// |
| 579 |
/// In this case, the data is a `Vec<String>` and the leaked reference |
| 580 |
/// `&'static str`, which points to some element of the vector. This |
| 581 |
/// illustrates that the leaks are not necessarily to the whole of the |
| 582 |
/// shared data. |
| 583 |
/// |
| 584 |
/// ```no_run |
| 585 |
/// # use pyo3::prelude::*; |
| 586 |
/// # use pyo3_sharedref::PyShareable; |
| 587 |
/// #[pyclass] |
| 588 |
/// struct Owner { |
| 589 |
/// value: PyShareable<Vec<String>> |
| 590 |
/// } |
| 591 |
/// |
| 592 |
/// #[pymethods] |
| 593 |
/// impl Owner { |
| 594 |
/// #[new] |
| 595 |
/// fn new(s: &str) -> Self { |
| 596 |
/// let split: Vec<_> = s.split(' ').map(String::from).collect(); |
| 597 |
/// Self { value: split.into() } |
| 598 |
/// } |
| 599 |
/// } |
| 600 |
/// |
| 601 |
/// const EMPTY: &'static str = ""; |
| 602 |
/// |
| 603 |
/// let mut outer = EMPTY; |
| 604 |
/// Python::with_gil(|py| { |
| 605 |
/// let owner = Bound::new(py, Owner::new("hello")).unwrap(); |
| 606 |
/// let shareable = &owner.borrow().value; |
| 607 |
/// let shared = unsafe { shareable.share(&owner) }; |
| 608 |
/// let mut shared_iter = unsafe { shared.map(py, |o| o.iter()) }; |
| 609 |
/// { |
| 610 |
/// let mut iter = unsafe { |
| 611 |
/// shared_iter.try_borrow_mut(py) |
| 612 |
/// }.unwrap(); |
| 613 |
/// let inner = iter.next().unwrap(); // Good, in borrow scope |
| 614 |
/// outer = inner; // Bad, &'static str does outlive the scope |
| 615 |
/// } |
| 616 |
/// }); |
| 617 |
/// ``` |
| 618 |
pub unsafe fn try_borrow_mut<'a>( |
| 619 |
&'a mut self, |
| 620 |
py: Python<'a>, |
| 621 |
) -> PyResult<SharedByPyObjectRefMut<'a, T>> { |
| 622 |
self.validate_generation(py)?; |
| 623 |
Ok(SharedByPyObjectRefMut { |
| 624 |
_borrow: BorrowPyShared::new(py, self.state), |
| 625 |
data: &mut self.data, |
| 626 |
}) |
| 627 |
} |
| 628 |
|
| 629 |
fn validate_generation(&self, py: Python) -> PyResult<()> { |
| 630 |
if self.state.current_generation(py) == self.generation { |
| 631 |
Ok(()) |
| 632 |
} else { |
| 633 |
Err(PyRuntimeError::new_err( |
| 634 |
"Cannot access to shared reference after mutation", |
| 635 |
)) |
| 636 |
} |
| 637 |
} |
| 638 |
} |
| 639 |
|
| 640 |
impl<T> SharedByPyObject<T> { |
| 641 |
/// Converts the inner value by the given function. |
| 642 |
/// |
| 643 |
/// Typically `T` is a static reference to a collection, and `U` is an |
| 644 |
/// iterator of that collection. |
| 645 |
/// |
| 646 |
/// # Panics |
| 647 |
/// |
| 648 |
/// Panics if the underlying reference has been invalidated. |
| 649 |
/// |
| 650 |
/// This is typically called immediately after the `SharedByPyObject` is |
| 651 |
/// obtained. At this time, the reference must be valid and no panic |
| 652 |
/// would occur. |
| 653 |
/// |
| 654 |
/// # Safety |
| 655 |
/// |
| 656 |
/// The lifetime of the object passed in to the function `f` is artificial. |
| 657 |
/// It's typically a static reference, but is valid only while the |
| 658 |
/// corresponding `SharedByPyObject` is alive. Do not copy it out of the |
| 659 |
/// function call. For example, the following does compile: |
| 660 |
/// |
| 661 |
/// ```no_run |
| 662 |
/// # use pyo3::prelude::*; |
| 663 |
/// # use pyo3_sharedref::PyShareable; |
| 664 |
/// #[pyclass] |
| 665 |
/// struct Owner { |
| 666 |
/// value: PyShareable<String> |
| 667 |
/// } |
| 668 |
/// |
| 669 |
/// #[pymethods] |
| 670 |
/// impl Owner { |
| 671 |
/// #[new] |
| 672 |
/// fn new(s: &str) -> Self { |
| 673 |
/// Self { value: s.to_owned().into() } |
| 674 |
/// } |
| 675 |
/// } |
| 676 |
/// |
| 677 |
/// const EMPTY: &'static str = ""; |
| 678 |
/// |
| 679 |
/// let mut outer = EMPTY; |
| 680 |
/// Python::with_gil(|py| { |
| 681 |
/// let owner = Bound::new(py, Owner::new("hello")).unwrap(); |
| 682 |
/// let shareable = &owner.borrow().value; |
| 683 |
/// let shared = unsafe { shareable.share(&owner) }; |
| 684 |
/// |
| 685 |
/// unsafe { shared.map(py, |o| { outer = o }) }; // Bad |
| 686 |
/// }); |
| 687 |
/// ``` |
| 688 |
pub unsafe fn map<U>( |
| 689 |
self, |
| 690 |
py: Python, |
| 691 |
f: impl FnOnce(T) -> U, |
| 692 |
) -> SharedByPyObject<U> { |
| 693 |
// Needs to test the generation value to make sure self.data reference |
| 694 |
// is still intact. |
| 695 |
self.validate_generation(py) |
| 696 |
.expect("map() over invalidated shared reference"); |
| 697 |
|
| 698 |
// f() could make the self.data outlive. That's why map() is unsafe. |
| 699 |
// In order to make this function safe, maybe we'll need a way to |
| 700 |
// temporarily restrict the lifetime of self.data and translate the |
| 701 |
// returned object back to Something<'static>. |
| 702 |
let new_data = f(self.data); |
| 703 |
SharedByPyObject { |
| 704 |
owner: self.owner, |
| 705 |
state: self.state, |
| 706 |
generation: self.generation, |
| 707 |
data: new_data, |
| 708 |
} |
| 709 |
} |
| 710 |
} |
| 711 |
|
| 712 |
/// An immutably borrowed reference to a shared value. |
| 713 |
pub struct SharedByPyObjectRef<'a, T: 'a + ?Sized> { |
| 714 |
_borrow: BorrowPyShared<'a>, |
| 715 |
data: &'a T, |
| 716 |
} |
| 717 |
|
| 718 |
impl<T: ?Sized> Deref for SharedByPyObjectRef<'_, T> { |
| 719 |
type Target = T; |
| 720 |
|
| 721 |
fn deref(&self) -> &T { |
| 722 |
self.data |
| 723 |
} |
| 724 |
} |
| 725 |
|
| 726 |
/// A mutably borrowed reference to a shared value. |
| 727 |
pub struct SharedByPyObjectRefMut<'a, T: 'a + ?Sized> { |
| 728 |
_borrow: BorrowPyShared<'a>, |
| 729 |
data: &'a mut T, |
| 730 |
} |
| 731 |
|
| 732 |
impl<T: ?Sized> Deref for SharedByPyObjectRefMut<'_, T> { |
| 733 |
type Target = T; |
| 734 |
|
| 735 |
fn deref(&self) -> &T { |
| 736 |
self.data |
| 737 |
} |
| 738 |
} |
| 739 |
|
| 740 |
impl<T: ?Sized> DerefMut for SharedByPyObjectRefMut<'_, T> { |
| 741 |
fn deref_mut(&mut self) -> &mut T { |
| 742 |
self.data |
| 743 |
} |
| 744 |
} |
| 745 |
|
| 746 |
/// Defines a Python iterator over a Rust iterator. |
| 747 |
/// |
| 748 |
/// TODO: this is a bit awkward to use, and a better (more complicated) |
| 749 |
/// procedural macro would simplify the interface a lot. |
| 750 |
/// |
| 751 |
/// # Parameters |
| 752 |
/// |
| 753 |
/// * `$name` is the identifier to give to the resulting Rust struct. |
| 754 |
/// * `$success_type` is the resulting Python object. It can be a bultin type, |
| 755 |
/// (e.g., `PyBytes`), or any `PyClass`. |
| 756 |
/// * `$owner_type` is the type owning the data |
| 757 |
/// * `$owner_attr` is the name of the shareable attribute in `$owner_type` |
| 758 |
/// * `$shared_type` is the type wrapped in `SharedByPyObject`, typically |
| 759 |
/// `SomeIter<'static>` |
| 760 |
/// * `$iter_func` is a function to obtain the Rust iterator from the content of |
| 761 |
/// the shareable attribute. It can be a closure. |
| 762 |
/// * `$result_func` is a function for converting items returned by the Rust |
| 763 |
/// iterator into `PyResult<Option<Py<$success_type>`. |
| 764 |
/// |
| 765 |
/// # Safety |
| 766 |
/// |
| 767 |
/// `$success_func` may take a reference, whose lifetime may be articial. |
| 768 |
/// Do not copy it out of the function call (this would be possible only |
| 769 |
/// with inner mutability). |
| 770 |
/// |
| 771 |
/// # Example |
| 772 |
/// |
| 773 |
/// The iterator example in [`PyShareable`] can be rewritten as |
| 774 |
/// |
| 775 |
/// ``` |
| 776 |
/// use pyo3::prelude::*; |
| 777 |
/// use pyo3_sharedref::*; |
| 778 |
/// |
| 779 |
/// use pyo3::types::{PyTuple, PyInt}; |
| 780 |
/// use std::collections::{hash_set::Iter as IterHashSet, HashSet}; |
| 781 |
/// use std::vec::Vec; |
| 782 |
/// |
| 783 |
/// #[pyclass(sequence)] |
| 784 |
/// struct Set { |
| 785 |
/// rust_set: PyShareable<HashSet<i32>>, |
| 786 |
/// } |
| 787 |
/// |
| 788 |
/// #[pymethods] |
| 789 |
/// impl Set { |
| 790 |
/// #[new] |
| 791 |
/// fn new(values: &Bound<'_, PyTuple>) -> PyResult<Self> { |
| 792 |
/// let as_vec = values.extract::<Vec<i32>>()?; |
| 793 |
/// let s: HashSet<_> = as_vec.iter().copied().collect(); |
| 794 |
/// Ok(Self { rust_set: s.into() }) |
| 795 |
/// } |
| 796 |
/// |
| 797 |
/// fn __iter__(slf: &Bound<'_, Self>) -> PyResult<SetIterator> { |
| 798 |
/// SetIterator::new(slf) |
| 799 |
/// } |
| 800 |
/// } |
| 801 |
/// |
| 802 |
/// py_shared_iterator!( |
| 803 |
/// SetIterator, |
| 804 |
/// PyInt, |
| 805 |
/// Set, |
| 806 |
/// rust_set, |
| 807 |
/// IterHashSet<'static, i32>, |
| 808 |
/// |hash_set| hash_set.iter(), |
| 809 |
/// it_next_result |
| 810 |
/// ); |
| 811 |
/// |
| 812 |
/// fn it_next_result(py: Python, res: &i32) -> PyResult<Option<Py<PyInt>>> { |
| 813 |
/// Ok(Some((*res).into_pyobject(py)?.unbind())) |
| 814 |
/// } |
| 815 |
/// ``` |
| 816 |
/// |
| 817 |
/// In the example above, `$result_func` is fairly trivial, and can be replaced |
| 818 |
/// by a closure, but things can get more complicated if the Rust |
| 819 |
/// iterator itself returns `Result<T, E>` with `T` not implementing |
| 820 |
/// `IntoPyObject` and `E` needing to be converted. |
| 821 |
/// Also the closure variant is fairly obscure: |
| 822 |
/// |
| 823 |
/// ```ignore |
| 824 |
/// py_shared_iterator!( |
| 825 |
/// SetIterator, |
| 826 |
/// PyInt, |
| 827 |
/// Set, |
| 828 |
/// rust_set, |
| 829 |
/// IterHashSet<'static, i32>, |
| 830 |
/// |hash_set| hash_set.iter(), |
| 831 |
/// (|py, i: &i32| Ok(Some((*i).into_pyobject(py)?.unbind()))) |
| 832 |
/// ) |
| 833 |
/// ``` |
| 834 |
#[macro_export] |
| 835 |
macro_rules! py_shared_iterator { |
| 836 |
( |
| 837 |
$name: ident, |
| 838 |
$success_type: ty, |
| 839 |
$owner_type: ident, |
| 840 |
$owner_attr: ident, |
| 841 |
$shared_type: ty, |
| 842 |
$iter_func: expr, |
| 843 |
$result_func: expr |
| 844 |
) => { |
| 845 |
#[pyclass] |
| 846 |
pub struct $name { |
| 847 |
inner: pyo3_sharedref::SharedByPyObject<$shared_type>, |
| 848 |
} |
| 849 |
|
| 850 |
#[pymethods] |
| 851 |
impl $name { |
| 852 |
#[new] |
| 853 |
fn new(owner: &Bound<'_, $owner_type>) -> PyResult<Self> { |
| 854 |
let inner = &owner.borrow().$owner_attr; |
| 855 |
// Safety: the data is indeed owned by `owner` |
| 856 |
let shared_iter = unsafe { inner.share_map(owner, $iter_func) }; |
| 857 |
Ok(Self { inner: shared_iter }) |
| 858 |
} |
| 859 |
|
| 860 |
fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> { |
| 861 |
slf |
| 862 |
} |
| 863 |
|
| 864 |
fn __next__( |
| 865 |
mut slf: PyRefMut<'_, Self>, |
| 866 |
) -> PyResult<Option<Py<$success_type>>> { |
| 867 |
let py = slf.py(); |
| 868 |
let shared = &mut slf.inner; |
| 869 |
// Safety: we do not leak references derived from the internal |
| 870 |
// 'static reference. |
| 871 |
let mut inner = unsafe { shared.try_borrow_mut(py) }?; |
| 872 |
match inner.next() { |
| 873 |
None => Ok(None), |
| 874 |
Some(res) => $result_func(py, res), |
| 875 |
} |
| 876 |
} |
| 877 |
} |
| 878 |
}; |
| 879 |
} |