pub struct RefOnce<'a, T: ?Sized> { /* private fields */ }
Implementations§
Source§impl<'a, T> RefOnce<'a, T>
impl<'a, T> RefOnce<'a, T>
Sourcepub fn new(value: T, slot: &'a mut MaybeUninit<T>) -> Self
pub fn new(value: T, slot: &'a mut MaybeUninit<T>) -> Self
Examples found in repository?
5fn main() {
6 let mut a = vec![1, 2, 3];
7 let mut x = 0;
8
9 let mut slots = (MaybeUninit::uninit(), MaybeUninit::uninit());
10
11 scope_lock::lock_scope(|e| {
12 thread::spawn({
13 let f = e.fn_(RefOnce::new(
14 |()| {
15 println!("hello from the first scoped thread");
16 // We can borrow `a` here.
17 dbg!(&a);
18 },
19 &mut slots.0,
20 ));
21 move || f(())
22 });
23 thread::spawn({
24 let mut f = e.fn_mut(RefOnce::new(
25 |()| {
26 println!("hello from the second scoped thread");
27 // We can even mutably borrow `x` here,
28 // because no other threads are using it.
29 x += a[0] + a[2];
30 },
31 &mut slots.1,
32 ));
33 move || f(())
34 });
35 println!("hello from the main thread");
36 });
37
38 // After the scope, we can modify and access our variables again:
39 a.push(4);
40 assert_eq!(x, a.len());
41}
pub fn into_inner(this: Self) -> T
Source§impl<'a, T: ?Sized> RefOnce<'a, T>
impl<'a, T: ?Sized> RefOnce<'a, T>
Sourcepub fn into_raw(this: Self) -> *mut T
pub fn into_raw(this: Self) -> *mut T
Essentially leaks object as a pointer until the original
RefOnce
is restored via Self::from_raw
.
Sourcepub unsafe fn from_raw(ptr: *mut T) -> Self
pub unsafe fn from_raw(ptr: *mut T) -> Self
Convert pointer returned from Self::into_raw
back into
RefOnce
.
§Safety
ptr
must have been returned from Self::into_raw
. New
lifetime argument 'a
of RefOnce
should not outlive old
lifetime not to cause any undefined behaviour.
Trait Implementations§
Source§impl<T: ?Sized> BorrowMut<T> for RefOnce<'_, T>
impl<T: ?Sized> BorrowMut<T> for RefOnce<'_, T>
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> PointerIntoInner for RefOnce<'_, T>
impl<T> PointerIntoInner for RefOnce<'_, T>
fn into_inner(self) -> Self::Pointee
Source§impl<'a, T> PointerLike for RefOnce<'a, T>
impl<'a, T> PointerLike for RefOnce<'a, T>
impl<T> PointerDeref for RefOnce<'_, T>
impl<T> PointerDerefMut for RefOnce<'_, T>
impl<T> PointerPinUnforgotten for RefOnce<'_, T>
Note that RefOnce::into_pin
implementation, mimicking the
Box::into_pin
would be unsound because RefOnce
stores object
within the std::mem::MaybeUninit
slot allocated somewhere
(including on a stack) which would allow us to deallocate pinned
object without first calling drop on it, thus violating the pin’s
drop guarantee. However we can safely assume that this pointer won’t
be forgotten and drop will “eventually” run, so we are safe here.