Struct TwiceCell

Source
pub struct TwiceCell<A, B> { /* private fields */ }
Expand description

A cell which can nominally be modified only once.

The main difference between this struct and a OnceCell is that rather than operating on an Option, this type operates on an Either – meaning methods such as TwiceCell::get_or_init take a parameter that can be used to compute the B value of a TwiceCell based on its A value.

For a thread-safe version of this struct, see TwiceLock.

§Examples

use twice_cell::TwiceCell;

let cell = TwiceCell::new("an initial `A` value for the cell");
assert!(cell.get().is_none());

let value = cell.get_or_init(|s| s.len()); // <- set a `B` value based on the inital `A` value!
assert_eq!(*value, 33);
assert!(cell.get().is_some());

Implementations§

Source§

impl<A, B> TwiceCell<A, B>

Source

pub const fn new(value: A) -> TwiceCell<A, B>

Creates a new cell with the given value.

Source

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

Gets the reference to the underlying value.

Returns None if the cell hasn’t been set.

Source

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

Gets the mutable reference to the underlying value.

Returns None if the cell hasn’t been set.

Source

pub fn get_either_mut(&mut self) -> Either<&mut A, &mut B>

Gets the mutable reference to either underlying value.

Source

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

Sets the contents of the cell to value.

§Errors

This method returns Ok(()) if the cell was empty and Err(value) if it was full.

§Examples
use twice_cell::TwiceCell;

let cell = TwiceCell::new(0);
assert!(cell.get().is_none());

assert_eq!(cell.set(92), Ok(()));
assert_eq!(cell.set(62), Err(62));

assert!(cell.get().is_some());
Source

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

Sets the contents of the cell to value if the cell was empty, then returns a reference to it.

§Errors

This method returns Ok(&value) if the cell was empty and Err(&current_value, value) if it was full.

§Examples
use twice_cell::TwiceCell;

let cell = TwiceCell::new(0);
assert!(cell.get().is_none());

assert_eq!(cell.try_insert(92), Ok(&92));
assert_eq!(cell.try_insert(62), Err((&92, 62)));

assert!(cell.get().is_some());
Source

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

Gets the contents of the cell, initializing it with f if the cell was unset.

§Panics

If f panics, the panic is propagated to the caller, and the cell remains uninitialized.

It is an error to reentrantly initialize the cell from f. Doing so results in a panic.

§Examples
use twice_cell::TwiceCell;

let cell = TwiceCell::new("hello");
let value = cell.get_or_init(|s| s.len());
assert_eq!(value, &5);
let value = cell.get_or_init(|_| unreachable!());
assert_eq!(value, &5);
Source

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

Gets the mutable reference of the contents of the cell, initializing it with f if the cell was unset.

§Panics

If f panics, the panic is propagated to the caller, and the cell remains uninitialized.

§Examples
use twice_cell::TwiceCell;

let mut cell = TwiceCell::new("twice_cell");
let value = cell.get_mut_or_init(|s| s.len());
assert_eq!(*value, 10);

*value += 2;
assert_eq!(*value, 12);

let value = cell.get_mut_or_init(|_| unreachable!());
assert_eq!(*value, 12);
Source

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

Gets the contents of the cell, initializing it with f if the cell was unset.

§Panics

If f panics, the panic is propagated to the caller, and the cell remains uninitialized.

It is an error to reentrantly initialize the cell from f. Doing so results in a panic.

§Errors

If the cell was unset and f failed, an error is returned.

§Examples
use twice_cell::TwiceCell;

let cell = TwiceCell::new(16);
assert_eq!(cell.get_or_try_init(|_| Err(())), Err(()));
assert!(cell.get().is_none());
let value = cell.get_or_try_init(|n| -> Result<i32, ()> {
    Ok(n * 4)
});
assert_eq!(value, Ok(&64));
assert_eq!(cell.get(), Some(&64))
Source

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

Gets the mutable reference of the contents of the cell, initializing it with f if the cell was unset.

§Panics

If f panics, the panic is propagated to the caller, and the cell remains uninitialized.

§Errors

If the cell was unset and f failed, an error is returned.

§Examples
use twice_cell::TwiceCell;

let mut cell = TwiceCell::new("not a number!");

// Failed initializers do not change the value
assert!(cell.get_mut_or_try_init(|s| s.parse::<i32>()).is_err());
assert!(cell.get().is_none());

let value = cell.get_mut_or_try_init(|_| "1234".parse());
assert_eq!(value, Ok(&mut 1234));
*value.unwrap() += 2;
assert_eq!(cell.get(), Some(&1236))
Source

pub fn into_inner(self) -> Either<A, B>

Consumes the cell, returning the wrapped value.

Returns Either::Left(A) if the cell was unset.

§Examples
use twice_cell::TwiceCell;
use either::Either;

let cell: TwiceCell<u8, &'static str> = TwiceCell::new(123);
assert_eq!(cell.into_inner(), Either::Left(123));

let cell: TwiceCell<u8, &'static str> = TwiceCell::new(123);
cell.set("hello").unwrap();
assert_eq!(cell.into_inner(), Either::Right("hello"));
Source

pub fn replace(&mut self, a: A) -> Either<A, B>

Replaces the value in this TwiceCell, moving it back to an unset state.

Safety is guaranteed by requiring a mutable reference.

§Examples
use twice_cell::TwiceCell;
use either::Either;

let mut cell: TwiceCell<i32, &'static str> = TwiceCell::new(123);
assert_eq!(cell.replace(456), Either::Left(123));

let mut cell = TwiceCell::new(123);
cell.set("goodbye").unwrap();
assert_eq!(cell.replace(456), Either::Right("goodbye"));
assert_eq!(cell.get(), None);

Trait Implementations§

Source§

impl<A: Clone, B: Clone> Clone for TwiceCell<A, B>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
Source§

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

Performs copy-assignment from source. Read more
Source§

impl<A: Debug, B: Debug> Debug for TwiceCell<A, B>

Source§

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

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

impl<A: Default, B> Default for TwiceCell<A, B>

Source§

fn default() -> Self

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

impl<A, B> From<B> for TwiceCell<A, B>

Source§

fn from(value: B) -> Self

Creates a new TwiceCell<A, B> which is already set to the given value.

Source§

impl<A: PartialEq, B: PartialEq> PartialEq for TwiceCell<A, B>

Source§

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

Tests for self and other values to be equal, and is used by ==.
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<A: Eq, B: Eq> Eq for TwiceCell<A, B>

Auto Trait Implementations§

§

impl<A, B> !Freeze for TwiceCell<A, B>

§

impl<A, B> !RefUnwindSafe for TwiceCell<A, B>

§

impl<A, B> Send for TwiceCell<A, B>
where A: Send, B: Send,

§

impl<A, B> !Sync for TwiceCell<A, B>

§

impl<A, B> Unpin for TwiceCell<A, B>
where A: Unpin, B: Unpin,

§

impl<A, B> UnwindSafe for TwiceCell<A, B>
where A: UnwindSafe, B: 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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
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.