pub struct AtomicLazy<T, F = fn() -> T> { /* private fields */ }
Expand description

A thread-safe value which is initialized on the first access.

Blocking

Calling AtomicLazy::force() – directly or through Deref – might block and should not be called from an interrupt handler. To use AtomicLazy in an interrupt handler, the following pattern is recommended:

use atomic_once_cell::AtomicLazy;

static LAZY: AtomicLazy<String> = AtomicLazy::new(|| "Hello, World!".to_owned());

fn interrupt_handler() {
    let item = AtomicLazy::get(&LAZY).unwrap_or_else(|| unreachable!());
    assert_eq!(*item, "Hello, World!");
    // [...]
}

fn main() {
    AtomicLazy::init(&LAZY);
    assert_eq!(*LAZY, "Hello, World!");
    // [...] <- Enable interrupt here
    interrupt_handler(); // interrupt handler called
                         // asynchronously at some point
    // [...]
}

Implementations

Creates a new lazy value with the given initializing function.

Examples
use atomic_once_cell::AtomicLazy;

let hello = "Hello, World!".to_string();

let lazy = AtomicLazy::new(|| hello.to_uppercase());

assert_eq!(&*lazy, "HELLO, WORLD!");

Forces the evaluation of this lazy value and returns a reference to the result.

This is equivalent to the Deref impl, but is explicit.

Blocking

This method might block and should not be used from an interrupt handler. Blocking is based on crossbeam::utils::Backoff, and will be reduced to a spin lock in #[no_std] environments.

Examples
use atomic_once_cell::AtomicLazy;

let lazy = AtomicLazy::new(|| 92);

assert_eq!(AtomicLazy::force(&lazy), &92);
assert_eq!(&*lazy, &92);

Like AtomicLazy::force(), but without returing a reference.

Examples
use atomic_once_cell::AtomicLazy;

let lazy = AtomicLazy::new(|| 92);

AtomicLazy::init(&lazy);
assert_eq!(&*lazy, &92);

Gets the reference to the underlying value.

Returns None if the cell is not initialized.

Examples
use atomic_once_cell::AtomicLazy;

let lazy = AtomicLazy::new(|| 92);

assert_eq!(AtomicLazy::get(&lazy), None);
assert_eq!(AtomicLazy::force(&lazy), &92);
assert_eq!(AtomicLazy::get(&lazy), Some(&92));

Trait Implementations

Formats the value using the given formatter. Read more

Creates a new lazy value using Default as the initializing function.

The resulting type after dereferencing.

Dereferences the value.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.