Crate scoped_static

Crate scoped_static 

Source
Expand description

§scoped_static

github crates.io docs.rs test status

Lift references into 'static safely — at runtime.

scoped_static allows temporarily extending a reference’s lifetime to 'static using runtime safety checks. This enables you to safely spawn asynchronous tasks, threads, or other 'static contexts without running into borrow checker limitations — while still avoiding undefined behavior.


§Motivation

Rust’s lifetime system ensures safety at compile time, but sometimes you need to move a non-'static reference into an async task or thread:

#[tokio::main]
async fn main() {
    let concrete_value = Box::new(1.0);
    let ref_value = &concrete_value; // This is does not live long enough (not 'static)
    tokio::spawn(async move {
        let value = **ref_value + 1.0;
        assert_eq!(value, 2.0);
    })
    .await
    .unwrap();
}

This fails because the reference to ref_value isn’t 'static.

scoped_static solves this by allowing you to lift a reference to 'static under the protection of a scope guard that enforces correct drop order at runtime.


§Example

use scoped_static::{ScopeGuard, Scoped};

#[tokio::main]
async fn main() {
    let value = Box::new(1.0);
    let ref_value = &value;
    // `guard` ensures no derived "lifted" values exist when dropped
    let guard = ScopeGuard::new(ref_value);
    // `lifted` holds a `'static` reference to `'ref_value`
    let lifted: Scoped<Box<f64>> = guard.lift();
    tokio::spawn(async move {
        // lifted moved here
        let value = **lifted + 1.0;
        assert_eq!(value, 2.0);
        // lifted dropped
    })
    .await
    .unwrap();
   // guard dropped
}

See ScopeGuard and UncheckedScopeGuard for more info.

Structs§

ScopeGuard
A reference with lifetime 'a that can be lifted to a reference with a 'static lifetime (Scoped). Runtime checks are used to ensure that no derived Scoped exists when this ScopeGuard is dropped.
Scoped
A reference derived from a ScopeGuard. The lifetime of the underlying value has been lifted to 'static. See ScopeGuard for more info.
UncheckedScopeGuard
Works like a ScopeGuard, except more performant in release-like modes, since no checks are used. But at the cost of risking additional UB if not used correctly. See UB notes below. Only consider using over [ScopedGuard] if one is certain this is dropped after all derived scoped values.
UncheckedScoped
A reference derived from a UncheckedScopeGuard. The lifetime of the underlying value has been lifted to 'static. See UncheckedScopeGuard for more info.