Crate ref_portals

Source
Expand description

Safely use (stack) references outside their original scope.

§Example

use ref_portals::rc::Anchor;
 
let x = "Scoped".to_owned();
let anchor = Anchor::new(&x);
let self_owned: Box<dyn Fn() + 'static> = Box::new({
    let portal = anchor.portal();
    move || println!("{}", *portal)
});
 
self_owned(); // Scoped

Note that dropping anchor before self_owned would still cause a panic here.
You can use weak portals to work around this:

use ref_portals::rc::Anchor;
 
let x = "Scoped".to_owned();
let anchor = Anchor::new(&x);
let eternal: &'static dyn Fn() = Box::leak(Box::new({
    let weak_portal = anchor.weak_portal();
    move || println!(
        "{}",
        *weak_portal.upgrade(), // Panics iff the anchor has been dropped.
    )
}));
 
eternal(); // Scoped

§Notes

Panic assertions in this documentation use assert_panic.

Modules§

rc
Single-threaded anchors and portals.
These don’t implement Send or Sync, but are more efficient for use cases where that’s not needed.
sync
Theadsafe anchors and portals.
These (but not their guards) are various degrees of Send and Sync depending on their type parameter.