pub struct State<T> {
pub inner: UnsafeCell<Option<T>>,
}
Fields
inner: UnsafeCell<Option<T>>
Implementations
sourceimpl<T> State<T>
impl<T> State<T>
sourcepub fn get(&self) -> Option<&T>
pub fn get(&self) -> Option<&T>
Gets the reference to the underlying value.
Returns None
if the state is empty.
sourcepub fn get_mut(&mut self) -> Option<&mut T>
pub fn get_mut(&mut self) -> Option<&mut T>
Gets the mutable reference to the underlying value.
Returns None
if the state is empty.
sourcepub fn get_or_init<F>(&self, f: F) -> &Twhere
F: FnOnce() -> T,
pub fn get_or_init<F>(&self, f: F) -> &Twhere
F: FnOnce() -> T,
Gets the contents of the state, initializing it with f
if the state was empty.
Panics
If f
panics, the panic is propagated to the caller, and the state
remains uninitialized.
It is an error to reentrantly initialize the state from f
. Doing
so results in a panic.
Examples
use zoon::State;
let state = State::new();
let value = state.get_or_init(|| 92);
assert_eq!(value, &92);
let value = state.get_or_init(|| unreachable!());
assert_eq!(value, &92);
sourcepub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>where
F: FnOnce() -> Result<T, E>,
pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>where
F: FnOnce() -> Result<T, E>,
Gets the contents of the state, initializing it with f
if
the state was empty. If the state was empty and f
failed, an
error is returned.
Panics
If f
panics, the panic is propagated to the caller, and the state
remains uninitialized.
It is an error to reentrantly initialize the state from f
. Doing
so results in a panic.
Examples
use zoon::State;
let state = State::new();
assert_eq!(state.get_or_try_init(|| Err(())), Err(()));
assert!(state.get().is_none());
let value = state.get_or_try_init(|| -> Result<i32, ()> {
Ok(92)
});
assert_eq!(value, Ok(&92));
assert_eq!(state.get(), Some(&92))
sourcepub fn into_inner(self) -> Option<T>
pub fn into_inner(self) -> Option<T>
Consumes the state, returning the wrapped value.
Returns None
if the state was empty.
Examples
use zoon::State;
let state: State<String> = State::new();
assert_eq!(state.into_inner(), None);
let state = State::new();
state.set("hello".to_string()).unwrap();
assert_eq!(state.into_inner(), Some("hello".to_string()));
sourcepub fn take(&mut self) -> Option<T>
pub fn take(&mut self) -> Option<T>
Takes the value out of this State
, moving it back to an uninitialized state.
Has no effect and returns None
if the State
hasn’t been initialized.
Safety is guaranteed by requiring a mutable reference.
Examples
use zoon::State;
let mut state: State<String> = State::new();
assert_eq!(state.take(), None);
let mut state = State::new();
state.set("hello".to_string()).unwrap();
assert_eq!(state.take(), Some("hello".to_string()));
assert_eq!(state.get(), None);