comparison rust/pyo3-sharedref/tests/test_sharedref.rs @ 52612:a945845137b1

rust-pyo3-sharedref: share/map methods on PyShareable The pattern to borrow (with owner) for the sole purpose of calling `share_immutable`, and then `map()` is pretty common, being exactly what is needed in the constructors of derived Python objects. we therefore introduce new helpers doing exactly that. We keep the intermediate `share()` and `try_share()` that are used in integration tests, but is is possible that consumers of the API never need it. A nice feature of the new `share_map()` helper is that it collapses all the unsafety in constructors of derived object to one call. It makes sense, since the reason for unsafety is the same all along the call stack: the `owner` object, that cannot be guessed from `PyShareable` itself, must be the right one. It is remarkable that it is only at this point that the compiler insists that `T` should be `'static`, which is actually very reasonable, as it encompasses owned data. We could have set it since the beginning, but the added value is low, as PyO3 would not let us use some `PyShareable<&'a T>` as a Python object data field (with `'a` not outliving `'static` of course)
author Georges Racinet <georges.racinet@cloudcrane.io>
date Sun, 15 Dec 2024 15:36:11 +0100
parents 4a73eb3923ac
children ac0cb3c334a1
comparison
equal deleted inserted replaced
52611:4a73eb3923ac 52612:a945845137b1
26 26
27 /// "leak" in the sense of `SharedByPyObject` the `string` data field, 27 /// "leak" in the sense of `SharedByPyObject` the `string` data field,
28 /// taking care of all the boilerplate 28 /// taking care of all the boilerplate
29 fn leak_string(owner: &Bound<'_, Owner>) -> SharedByPyObject<&'static String> { 29 fn leak_string(owner: &Bound<'_, Owner>) -> SharedByPyObject<&'static String> {
30 let cell = &owner.borrow().string; 30 let cell = &owner.borrow().string;
31 let shared_ref = unsafe { cell.borrow_with_owner(owner) }; 31 unsafe { cell.share(owner) }
32 shared_ref.share_immutable()
33 } 32 }
34 33
35 fn try_leak_string( 34 fn try_leak_string(
36 owner: &Bound<'_, Owner>, 35 owner: &Bound<'_, Owner>,
37 ) -> Result<SharedByPyObject<&'static String>, TryShareError> { 36 ) -> Result<SharedByPyObject<&'static String>, TryShareError> {
38 let cell = &owner.borrow().string; 37 let cell = &owner.borrow().string;
39 let shared_ref = unsafe { cell.borrow_with_owner(owner) }; 38 unsafe { cell.try_share(owner) }
40 shared_ref.try_share_immutable()
41 } 39 }
42 40
43 /// Mutate the `string` field of `owner` as would be done from Python code 41 /// Mutate the `string` field of `owner` as would be done from Python code
44 /// 42 ///
45 /// This is to simulate normal mutation of the owner object from 43 /// This is to simulate normal mutation of the owner object from