Once

Struct Once 

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

A thread-safe cell which can be written to only once.

This structure provides safe initialization for values that might be accessed concurrently by multiple threads. It ensures that the initialization logic runs only once, even if multiple threads attempt to initialize the value simultaneously.

It uses atomic operations and parking_lot’s futex-based synchronization for efficient blocking when necessary.

Implementations§

Source§

impl<T> Once<T>

Source

pub const fn new() -> Self

Creates a new, uninitialized Once cell.

Source

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

Creates a new Once cell that is already initialized with the given value.

Source

pub fn is_done(&self) -> bool

Checks if the cell has been initialized.

This method never blocks.

Source

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

Returns a reference to the contained value if initialized.

Returns None if the cell is uninitialized or currently being initialized. This method never blocks.

Source

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

Returns a mutable reference to the contained value if initialized.

Returns None if the cell is uninitialized or currently being initialized. This method requires exclusive access (&mut self) and never blocks.

Source

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

Attempts to initialize the cell with value without blocking.

  • If the cell is uninitialized and not locked, initializes it with value and returns Ok(&value).
  • If the cell is already initialized, returns Err(value).
  • If the cell is currently locked by another thread, returns Err(value).
Source

pub fn replace_mut(&mut self, value: T) -> Option<T>

Replaces the cell’s value, returning the old value if initialized.

  • If uninitialized, sets the value to value and returns None.
  • If initialized, replaces the existing value with value and returns the old value.

Requires exclusive access (&mut self), so it never blocks.

Source

pub fn get_mut_or_set(&mut self, value: T) -> &mut T

Gets a mutable reference, initializing with value if needed.

  • If initialized, returns a mutable reference to the existing value.
  • If uninitialized, initializes it with value and returns a mutable reference.

Requires exclusive access (&mut self), so it never blocks.

Source

pub fn get_mut_or_default(&mut self) -> &mut T
where T: Default,

Gets a mutable reference, initializing with Default::default() if needed.

  • If initialized, returns a mutable reference to the existing value.
  • If uninitialized, initializes it with T::default() and returns a mutable reference.

Requires exclusive access (&mut self), so it never blocks.

Source

pub unsafe fn get_unchecked(&self) -> &T

Returns a reference to the value without checking if it’s initialized.

§Safety

Calling this method on an uninitialized Once cell is undefined behavior. The caller must ensure the cell is initialized, e.g., by calling is_done() or get().

Source

pub unsafe fn get_unchecked_mut(&mut self) -> &mut T

Returns a mutable reference to the value without checking if it’s initialized.

§Safety

Calling this method on an uninitialized Once cell is undefined behavior. The caller must ensure the cell is initialized and that they have exclusive access.

Source

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

Takes the value out of the cell, leaving it uninitialized.

Returns Some(value) if the cell was initialized, None otherwise. Requires exclusive access (&mut self), so it never blocks.

Source

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

Initializes the cell with value. Blocks if another thread is initializing.

  • If uninitialized, initializes it with value and returns Ok(()).
  • If already initialized, returns Err(value).

Guarantees the cell is initialized upon return, but not necessarily with value if another thread completed initialization first.

Source

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

Initializes the cell with value if uninitialized, returning a reference. Blocks if needed.

  • If uninitialized, initializes with value and returns Ok(&value).
  • If already initialized, returns Err((&current_value, value)).

Guarantees the cell is initialized upon return.

Source

pub fn get_or_init<F>(&self, f: F) -> &T
where F: FnOnce() -> T,

Gets the value, initializing with f() if needed. Blocks if needed.

  • If initialized, returns a reference to the existing value.
  • If uninitialized, calls f(), stores the result, and returns a reference.

If multiple threads call this concurrently, only one f() execution happens.

Source

pub fn get_mut_or_init<F>(&mut self, f: F) -> &mut T
where F: FnOnce() -> T,

Gets a mutable reference, initializing with f() if needed.

  • If initialized, returns a mutable reference to the existing value.
  • If uninitialized, calls f(), stores the result, and returns a mutable reference.

Requires exclusive access (&mut self), so it never blocks.

Source

pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
where F: FnOnce() -> Result<T, E>,

Gets the value, initializing with fallible f() if needed. Blocks if needed.

  • If initialized, returns Ok(&value).
  • If uninitialized, calls f():
    • On Ok(value), initializes the cell and returns Ok(&value).
    • On Err(e), returns Err(e) and leaves the cell uninitialized.

If multiple threads call this concurrently, only one f() execution happens.

Source

pub fn get_mut_or_try_init<F, E>(&mut self, f: F) -> Result<&mut T, E>
where F: FnOnce() -> Result<T, E>,

Gets a mutable reference, initializing with fallible f() if needed.

  • If initialized, returns Ok(&mut value).
  • If uninitialized, calls f():
    • On Ok(value), initializes the cell and returns Ok(&mut value).
    • On Err(e), returns Err(e) and leaves the cell uninitialized.

Requires exclusive access (&mut self), so it never blocks (initialization happens inline).

Source

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

Gets the value, initializing asynchronously with f() if needed. Blocks if needed.

  • If initialized, returns a reference to the existing value.
  • If uninitialized, awaits f(), stores the result, and returns a reference.

If multiple tasks call this concurrently, only one f() execution happens.

Source

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

Gets a mutable reference, initializing asynchronously with f() if needed.

  • If initialized, returns a mutable reference to the existing value.
  • If uninitialized, awaits f(), stores the result, and returns a mutable reference.

Requires exclusive access (&mut self), so it never blocks (initialization happens inline).

Source

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

Gets the value, initializing asynchronously with fallible f() if needed. Blocks if needed.

  • If initialized, returns Ok(&value).
  • If uninitialized, awaits f():
    • On Ok(value), initializes the cell and returns Ok(&value).
    • On Err(e), returns Err(e) and leaves the cell uninitialized.

If multiple tasks call this concurrently, only one f() execution happens.

Source

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

Gets a mutable reference, initializing asynchronously with fallible f() if needed.

  • If initialized, returns Ok(&mut value).
  • If uninitialized, awaits f():
    • On Ok(value), initializes the cell and returns Ok(&mut value).
    • On Err(e), returns Err(e) and leaves the cell uninitialized.

Requires exclusive access (&mut self), so it never blocks (initialization happens inline).

Trait Implementations§

Source§

impl<T: Clone> Clone for Once<T>

Source§

fn clone(&self) -> Self

Clones the Once cell.

If the original cell is initialized, the clone will be initialized with a cloned value. If the original is uninitialized, the clone will also be uninitialized.

1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<T: Debug> Debug for Once<T>

Source§

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

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

impl<T> Default for Once<T>

Source§

fn default() -> Self

Creates a new, uninitialized Once cell.

Source§

impl<T: Display> Display for Once<T>

Source§

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

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

impl<T> Drop for Once<T>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl<T> From<Option<T>> for Once<T>

Source§

fn from(value: Option<T>) -> Self

Creates an initialized Once from Some(value) or an uninitialized one from None.

Source§

impl<T> From<T> for Once<T>

Source§

fn from(value: T) -> Self

Creates a new, initialized Once cell from the given value.

Source§

impl<T: PartialEq> PartialEq for Once<T>

Source§

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

Checks if two Once cells are equal.

They are equal if both are uninitialized, or if both are initialized and their contained values are equal according to PartialEq.

1.0.0 · Source§

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T: Eq> Eq for Once<T>

Source§

impl<T: Send> Send for Once<T>

Source§

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

Auto Trait Implementations§

§

impl<T> !Freeze for Once<T>

§

impl<T> !RefUnwindSafe for Once<T>

§

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

§

impl<T> UnwindSafe for Once<T>
where T: UnwindSafe,

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.

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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. 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.