Struct mycelium_util::sync::InitOnce
pub struct InitOnce<T> { /* private fields */ }
Expand description
A cell which may be initialized a single time after it is created.
This can be used as a safer alternative to static mut
.
For performance-critical use-cases, this type also has a get_unchecked
method, which dereferences the cell without checking if it has been
initialized. This method is unsafe and should be used with caution —
incorrect usage can result in reading uninitialized memory.
Implementations§
§impl<T> InitOnce<T>
impl<T> InitOnce<T>
pub const fn uninitialized() -> InitOnce<T>
Available on non-loom
only.
pub const fn uninitialized() -> InitOnce<T>
loom
only.Returns a new InitOnce
in the uninitialized state.
pub fn try_init(&self, value: T) -> Result<(), TryInitError<T>>
pub fn try_init(&self, value: T) -> Result<(), TryInitError<T>>
Initialize the cell to value
, returning an error if it has already
been initialized.
If the cell has already been initialized, the returned error contains the value.
pub fn init(&self, value: T) -> &T
pub fn init(&self, value: T) -> &T
Initialize the cell to value
, panicking if it has already been
initialized.
Panics
If the cell has already been initialized.
pub fn try_get(&self) -> Option<&T>
pub fn try_get(&self) -> Option<&T>
Borrow the contents of this InitOnce
cell, if it has been
initialized. Otherwise, if the cell has not yet been initialized, this
returns None
.
pub fn get(&self) -> &T
pub fn get(&self) -> &T
Borrow the contents of this InitOnce
cell, or panic if it has not
been initialized.
Panics
If the cell has not yet been initialized.
pub fn get_or_else(&self, f: impl FnOnce() -> T) -> &T
pub fn get_or_else(&self, f: impl FnOnce() -> T) -> &T
Borrow the contents of this InitOnce
cell, or initialize it with the
provided closure.
If the cell has been initialized, this returns the current value. Otherwise, it calls the closure, puts the returned value from the closure in the cell, and borrows the current value.
pub unsafe fn get_unchecked(&self) -> &T
pub unsafe fn get_unchecked(&self) -> &T
Borrow the contents of this InitOnce
cell, without checking
whether it has been initialized.
Safety
The caller is responsible for ensuring that the value has already been initialized.
In debug mode, this still checks the state of the cell, so if it has yet to be initialized, this will panic. However, in release mode builds, this is completely unchecked. If the value has not yet been initialized, this may return a pointer to uninitialized memory! It may also return a pointer to memory that is currently being written to.
If you see this method panic in debug mode, please, please re-check your code.