Struct cpython::PySharedRefCell
source · pub struct PySharedRefCell<T: ?Sized> { /* private fields */ }
Expand description
A mutable memory location shareable immutably across Python objects.
This is a RefCell that can also be borrowed immutably by another Python object.
The primary use case is to implement a Python iterator over a Rust
iterator. Since a Python object cannot hold a lifetime-bound object,
Iter<'a, T>
cannot be a data field of the Python iterator object.
PySharedRef::leak_immutable() provides a way around this issue.
py_class!(pub class List |py| {
@shared data rust_vec: Vec<i32>;
def __iter__(&self) -> PyResult<ListIterator> {
let leaked = self.rust_vec(py).leak_immutable();
ListIterator::create_instance(
py,
RefCell::new(unsafe { leaked.map(py, |o| o.iter()) }),
)
}
});
py_class!(pub class ListIterator |py| {
data rust_iter: RefCell<UnsafePyLeaked<Iter<'static, i32>>>;
def __next__(&self) -> PyResult<Option<PyInt>> {
let mut leaked = self.rust_iter(py).borrow_mut();
let mut iter = unsafe { leaked.try_borrow_mut(py)? };
Ok(iter.next().map(|v| v.to_py_object(py)))
}
def __iter__(&self) -> PyResult<Self> {
Ok(self.clone_ref(py))
}
});
The borrow rules are enforced dynamically in a similar manner to the Python iterator.
PySharedRefCell
is merely a data struct to be stored in a Python object.
Any further operation will be performed through PySharedRef, which is
a lifetime-bound reference to the PySharedRefCell
.
Implementations§
sourcepub fn new(value: T) -> PySharedRefCell<T>
pub fn new(value: T) -> PySharedRefCell<T>
Creates a new PySharedRefCell
containing value
.
Trait Implementations§
Auto Trait Implementations§
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more