TakeOnce

Struct TakeOnce 

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

A thread-safe container that allows storing a value once and taking it exactly once. This is useful in scenarios where:

  • A value needs to be initialized lazily but only once
  • The initialized value should be consumable (moved out) rather than just accessible. See std::sync::OnceLock for a similar use case where the value can be accessed in place.
  • Multiple threads might attempt to initialize or consume the value, but only one should succeed

§Thread Safety

TakeOnce<T> implements Send and Sync when T: Send, making it safe to share across thread boundaries. All operations are atomic and properly synchronized.

§Memory Management

The stored value is heap-allocated and properly cleaned up when the TakeOnce is dropped.

§Examples

Basic usage:

use take_once::TakeOnce;

let cell = TakeOnce::new();

// Initial store succeeds
assert_eq!(cell.store(42), Ok(()));

// Subsequent stores return the provided value
assert_eq!(cell.store(24), Err(24));

// Take the value
assert_eq!(cell.take(), Some(42));

// Can't take twice
assert_eq!(cell.take(), None);

Concurrent usage:

use std::sync::Arc;
use std::thread;
use take_once::TakeOnce;

let shared = Arc::new(TakeOnce::new());
let threads: Vec<_> = (0..3)
    .map(|i| {
        let shared = shared.clone();
        thread::spawn(move || {
            // Only one thread will successfully store
            shared.store(i)
        })
    })
    .collect();

Implementations§

Source§

impl<T> TakeOnce<T>

Source

pub const fn new() -> TakeOnce<T>

Creates a new empty cell.

Source

pub fn new_with(val: T) -> TakeOnce<T>

Create and store a cell in a single operation

use take_once::TakeOnce;

let initialized = TakeOnce::new_with(true);
assert_eq!(initialized.store(false), Err(false));
assert_eq!(initialized.take(), Some(true));
Source

pub fn store(&self, val: T) -> Result<(), T>

Stores a value into this TakeOnce if it has not been initialized.

If the TakeOnce has already been initialized, the value is returned as Err. Otherwise, the value is stored and Ok is returned.

This method allocates memory on the heap to store the value.

Source

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

Takes the value out of this TakeOnce, if it has been initialized.

If the TakeOnce has not been initialized, or if the value has already been taken, this method returns None.

Source

pub fn is_completed(&self) -> bool

Returns true if the value has been initialized, regardless of whether it has been taken. In other words, this returns true if store has been called at least once.

Trait Implementations§

Source§

impl<T: Debug> Debug for TakeOnce<T>

Source§

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

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

impl<T> Default for TakeOnce<T>

Source§

fn default() -> Self

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

impl<T> Drop for TakeOnce<T>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl<T: Send> Send for TakeOnce<T>

Source§

impl<T: Send> Sync for TakeOnce<T>

Auto Trait Implementations§

§

impl<T> !Freeze for TakeOnce<T>

§

impl<T> RefUnwindSafe for TakeOnce<T>
where T: RefUnwindSafe,

§

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

§

impl<T> UnwindSafe for TakeOnce<T>

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> 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, 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.