Struct future_local_storage::FutureOnceCell
source · pub struct FutureOnceCell<T>(/* private fields */);
Expand description
An init-once-per-future cell for thread-local values.
It uses thread local storage to ensure that the each polled future has its own local storage key.
Unlike the std::thread::LocalKey
this cell will not lazily initialize the value on first access.
Instead, the value is first initialized when the future containing the future-local is first polled
by an executor.
After the execution finished the value moves from the future local cell to the future output.
Implementations§
source§impl<T> FutureOnceCell<T>
impl<T> FutureOnceCell<T>
source§impl<T: Send + 'static> FutureOnceCell<T>
impl<T: Send + 'static> FutureOnceCell<T>
sourcepub fn with<F, R>(&'static self, f: F) -> R
pub fn with<F, R>(&'static self, f: F) -> R
Acquires a reference to the value in this future local storage.
Unlike the std::thread::LocalKey::with
this method does not initialize the value
when called.
Panics
-
This method will panic if the future local doesn’t have a value set.
-
If you the returned future inside the a call to
Self::with
on the same cell, then the call topoll
will panic.
sourcepub fn get(&'static self) -> Twhere
T: Copy,
pub fn get(&'static self) -> Twhere
T: Copy,
Returns a copy of the contained value.
Panics
This method will panic if the future local doesn’t have a value set.
sourcepub fn scope<F>(
&'static self,
value: T,
future: F
) -> ScopedFutureWithValue<T, F> ⓘwhere
F: Future,
pub fn scope<F>(
&'static self,
value: T,
future: F
) -> ScopedFutureWithValue<T, F> ⓘwhere
F: Future,
Sets a value T
as the future-local value for the future F
.
On completion of scope
, the future-local value will be returned by the scoped future.
use std::cell::Cell;
use future_local_storage::FutureOnceCell;
static VALUE: FutureOnceCell<Cell<u64>> = FutureOnceCell::new();
#[tokio::main]
async fn main() {
let (output, answer) = VALUE.scope(Cell::from(0), async {
VALUE.with(|x| {
let value = x.get();
x.set(value + 1);
});
42
}).await;
}