Skip to main content

OnceCell

Struct OnceCell 

Source
pub struct OnceCell<T> { /* private fields */ }
Expand description

A cell that is written at most once.

  • set publishes a value with one compare-and-swap and never waits. It fails with SetError::InitializingError while an asynchronous initializer holds the turn.
  • get_or_init_racy lets every caller that finds the cell empty build a value; one compare-and-swap publishes one of them and the others are dropped.
  • get_or_init and get_or_try_init run one initializer at a time; the others wait for it as futures. An initializer that fails or is dropped passes the turn to the next waiter.
use nuclei::sync::{OnceCell, SetError};

static NAME: OnceCell<String> = OnceCell::const_new();
assert!(NAME.set("first".to_owned()).is_ok());
assert_eq!(
    NAME.set("second".to_owned()),
    Err(SetError::AlreadyInitializedError("second".to_owned()))
);
assert_eq!(NAME.get_or_init_racy(|| "unused".to_owned()), "first");

Implementations§

Source§

impl<T> OnceCell<T>

Source

pub const fn new() -> Self

An empty cell.

Source

pub const fn const_new() -> Self

An empty cell, usable in a static.

Source

pub fn new_with(value: Option<T>) -> Self

A cell that holds value if there is one, and is empty otherwise.

Source

pub const fn const_new_with(value: T) -> Self

A cell that already holds value, usable in a static.

Source

pub fn initialized(&self) -> bool

Whether the cell holds a value.

Source

pub fn get(&self) -> Option<&T>

The value, once published.

Source

pub fn get_mut(&mut self) -> Option<&mut T>

The value, borrowed mutably.

Source

pub fn into_inner(self) -> Option<T>

Consumes the cell and returns its value, if it has one.

Source

pub fn take(&mut self) -> Option<T>

Takes the value out of the cell, leaving it empty and ready to be set again. None if the cell is empty.

Source

pub fn set(&self, value: T) -> Result<(), SetError<T>>

Publishes value unless the cell already holds one or a task is initializing it, in which case value comes back in the error. One compare-and-swap publishes; never waits. A successful publish also releases any task waiting in get_or_init.

§Errors

SetError::AlreadyInitializedError when the cell holds a value, SetError::InitializingError when an initializer holds the turn.

Source

pub fn get_or_init_racy(&self, init: impl FnOnce() -> T) -> &T

The value, building one with init if the cell is empty. Callers that race all build; one value is published and the rest are dropped. Never waits. A racing builder does not take the turn, so it also wins over an initializer that is running: that one’s value is dropped when it finishes.

Source

pub async fn get_or_init<F, Fut>(&self, f: F) -> &T
where F: FnOnce() -> Fut, Fut: Future<Output = T>,

The value, running f to build it if the cell is empty. One initializer runs at a time; the rest wait. f is called only by the task that holds the turn, and not at all if the cell is full by then.

If the future f returns is dropped or panics, the attempt is cancelled and the next waiter makes its own.

This waits for ever if f tries to initialize the cell recursively.

Source

pub async fn get_or_try_init<E, F, Fut>(&self, f: F) -> Result<&T, E>
where F: FnOnce() -> Fut, Fut: Future<Output = Result<T, E>>,

The value, running f to build it if the cell is empty. One initializer runs at a time; when it fails, its error is returned and the next waiter tries its own.

If the future f returns is dropped or panics, the attempt is cancelled and the next waiter makes its own.

This waits for ever if f tries to initialize the cell recursively.

Trait Implementations§

Source§

impl<T: Clone> Clone for OnceCell<T>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug> Debug for OnceCell<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T> Default for OnceCell<T>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<T> Drop for OnceCell<T>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl<T: Eq> Eq for OnceCell<T>

Source§

impl<T> From<T> for OnceCell<T>

Source§

fn from(value: T) -> Self

Converts to this type from the input type.
Source§

impl<T: PartialEq> PartialEq for OnceCell<T>

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl<T: Send + Sync> Sync for OnceCell<T>

Auto Trait Implementations§

§

impl<T> !Freeze for OnceCell<T>

§

impl<T> !RefUnwindSafe for OnceCell<T>

§

impl<T> !UnwindSafe for OnceCell<T>

§

impl<T> Send for OnceCell<T>
where T: Send,

§

impl<T> Unpin for OnceCell<T>
where T: Unpin,

§

impl<T> UnsafeUnpin for OnceCell<T>
where T: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<!> for T

Source§

fn from(t: !) -> T

Converts to this type from the input type.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

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

§

impl<T> MaybeSend for T
where T: Send + ?Sized,

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.