Crate take_once

Crate take_once 

Source
Expand description

A thread-safe container for one-time storage and one-time consumption of a value.

This module provides the TakeOnce type, which enables safe storage and consumption of a value in concurrent contexts. It ensures that:

  • A value can be stored exactly once
  • A stored value can be taken out exactly once
  • All operations are thread-safe

This is similar to std::sync::OnceLock, but with different semantics regarding value consumption. TakeOnce allows the stored value to be taken out (moved) exactly once, whereas OnceLock allows the value to be accessed in place multiple times.

§Example

use take_once::TakeOnce;

let cell = TakeOnce::new();

// Store a value
assert_eq!(cell.store(42), Ok(()));

// Subsequent stores do not consume the value.
assert_eq!(cell.store(24), Err(24));

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

// Value can only be taken once
assert_eq!(cell.take(), None);

§Thread Safety

TakeOnce<T> is both Send and Sync when T: Send, making it suitable for sharing across thread boundaries. All operations are atomic and properly synchronized.

let shared = Arc::new(TakeOnce::new());
let shared2 = shared.clone();

// Store in one thread
thread::spawn(move || {
    shared.store(42).unwrap();
}).join().unwrap();

// Take in another thread
thread::spawn(move || {
    if let Some(value) = shared2.take() {
        println!("Got value: {}", value);
    }
});

Structs§

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