### OnceCell Initialization and Usage Example Source: https://docs.rs/once_cell/latest/once_cell/sync/struct.OnceCell.html Demonstrates initializing a OnceCell with a String value and retrieving it. This example shows basic usage with `get_or_init` and `get`. ```Rust use once_cell::sync::OnceCell; static CELL: OnceCell = OnceCell::new(); assert!(CELL.get().is_none()); std::thread::spawn(|| { let value: &String = CELL.get_or_init(|| { "Hello, World!".to_string() }); assert_eq!(value, "Hello, World!"); }).join().unwrap(); let value: Option<&String> = CELL.get(); assert!(value.is_some()); assert_eq!(value.unwrap().as_str(), "Hello, World!"); ``` -------------------------------- ### Example Usage of OnceCell Source: https://docs.rs/once_cell/latest/once_cell?search= Demonstrates a basic usage pattern for initializing a value using a OnceCell. ```rust let mut a = OnceCell::new(); let a = a.get_or_init(|| { // compute expensive value // ... 42 }); // a is now initialized, and the closure will not be called again. assert_eq!(*a, 42); // If you need to access the value mutably, you can use get_or_init_mut: let mut a = OnceCell::new(); let a = a.get_or_init_mut(|| { // compute expensive value // ... 42 }); // a is now initialized, and the closure will not be called again. assert_eq!(*a, 42); // You can also use `get_or_try_init` for fallible initializations: let mut a: OnceCell> = OnceCell::new(); let a = a.get_or_try_init(|| { // compute potentially fallible value // ... Ok(42) }); assert!(a.is_ok()); assert_eq!(*a.as_ref().unwrap(), 42); // If the closure returns an error, it will be returned and the cell will remain empty: let mut a: OnceCell> = OnceCell::new(); let res = a.get_or_try_init(|| Err(())); assert!(res.is_err()); assert!(a.get().is_none()); ``` -------------------------------- ### Compile-fail example for OnceRef set and swap Source: https://docs.rs/once_cell/latest/src/once_cell/race.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This example demonstrates a potential use-after-free error when `set` is used and the `OnceRef` is subsequently swapped, leading to a dangling reference. ```rust ```compile_fail use once_cell::race::OnceRef; let mut l = OnceRef::new(); { let y = 2; let mut r = OnceRef::new(); r.set(&y).unwrap(); core::mem::swap(&mut l, &mut r); } // l now contains a dangling reference to y eprintln!("uaf: {}", l.get().unwrap()); ``` ``` -------------------------------- ### OnceNonZeroUsize Initialization and Get Source: https://docs.rs/once_cell/latest/src/once_cell/race.rs.html?search=std%3A%3Avec Demonstrates creating a new empty OnceNonZeroUsize cell and retrieving its value. The get method uses Acquire ordering to ensure visibility of writes. ```rust use core::num::NonZeroUsize; use once_cell::race::OnceNonZeroUsize; let cell = OnceNonZeroUsize::new(); assert_eq!(cell.get(), None); let value = NonZeroUsize::new(1).unwrap(); cell.set(value).unwrap(); assert_eq!(cell.get(), Some(value)); ``` -------------------------------- ### Lazy Initialization Example Source: https://docs.rs/once_cell/latest/once_cell/unsync/struct.Lazy.html Demonstrates how to create and use a `Lazy` value. The initialization closure is only executed on the first access. ```rust use once_cell::unsync::Lazy; let lazy: Lazy = Lazy::new(|| { println!("initializing"); 92 }); println!("ready"); println!("{}", *lazy); println!("{}", *lazy); // Prints: // ready // initializing // 92 // 92 ``` -------------------------------- ### Sync OnceCell Example Source: https://docs.rs/once_cell/latest/once_cell/index.html Illustrates the use of the sync flavor of OnceCell for multi-threaded applications. It ensures thread-safe initialization. ```rust use once_cell::sync::OnceCell; static FOO: OnceCell = OnceCell::uninit(); fn main() { let foo = FOO.get_or_init(|| { // compute expensive value 3 }); assert_eq!(*foo, 3); } ``` -------------------------------- ### Create a new empty OnceBool Source: https://docs.rs/once_cell/latest/once_cell/race/struct.OnceBool.html Initializes a new OnceBool instance. This is the starting point before any value is set. ```rust pub const fn new() -> Self ``` -------------------------------- ### OnceRef compile-fail example (UAF) Source: https://docs.rs/once_cell/latest/src/once_cell/race.rs.html?search=u32+-%3E+bool A compile-fail example demonstrating a use-after-free (UAF) scenario with OnceRef. This highlights the danger of holding references to data that might be dropped or become invalid after a swap operation. ```Rust /// ```compile_fail /// use once_cell::race::OnceRef; /// /// let mut l = OnceRef::new(); /// /// { /// let y = 2; /// let mut r = OnceRef::new(); /// r.set(&y).unwrap(); /// core::mem::swap(&mut l, &mut r); /// } /// /// // l now contains a dangling reference to y /// eprintln!("uaf: {}", l.get().unwrap()); /// ``` ``` -------------------------------- ### Unsync OnceCell Example Source: https://docs.rs/once_cell/latest/once_cell/index.html Demonstrates the usage of the unsync flavor of OnceCell for single-threaded environments. Initialization panics on reentrancy. ```rust use once_cell::unsync::OnceCell; static FOO: OnceCell = OnceCell::uninit(); fn main() { let foo = FOO.get_or_init(|| { // compute expensive value 3 }); assert_eq!(*foo, 3); } ``` -------------------------------- ### OnceRef: Compile-fail example demonstrating dangling reference Source: https://docs.rs/once_cell/latest/src/once_cell/race.rs.html?search= This example demonstrates a potential use-after-free scenario with `OnceRef`. It shows how swapping `OnceRef` instances can lead to a dangling reference if not handled carefully, causing a compile-time error. ```rust /// ```compile_fail /// use once_cell::race::OnceRef; /// /// let mut l = OnceRef::new(); /// /// { /// let y = 2; /// let mut r = OnceRef::new(); /// r.set(&y).unwrap(); /// core::mem::swap(&mut l, &mut r); /// } /// /// // l now contains a dangling reference to y /// eprintln!("uaf: {}", l.get().unwrap()); /// ``` /// fn _dummy() {} ``` -------------------------------- ### OnceRef: Compile-fail Example (Dangling Reference) Source: https://docs.rs/once_cell/latest/src/once_cell/race.rs.html Demonstrates a compile-time failure scenario with OnceRef. This example shows how attempting to use a OnceRef after its referenced data has gone out of scope leads to a use-after-free error, caught by the compiler. ```rust /// ```compile_fail /// use once_cell::race::OnceRef; /// /// let mut l = OnceRef::new(); /// /// { /// let y = 2; /// let mut r = OnceRef::new(); /// r.set(&y).unwrap(); /// core::mem::swap(&mut l, &mut r); /// } /// /// // l now contains a dangling reference to y /// eprintln!("uaf: {}", l.get().unwrap()); /// ``` ``` -------------------------------- ### Unsynchronized OnceCell Example Source: https://docs.rs/once_cell/latest/src/once_cell/lib.rs.html?search=u32+-%3E+bool Demonstrates the usage of the unsync::OnceCell for single-threaded scenarios. It shows how to initialize a value once and access it. ```rust #![cfg_attr(not(feature = "std"), no_std)] #[cfg(feature = "alloc")] extern crate alloc; #[cfg(all(feature = "critical-section", not(feature = "std")))] #[path = "imp_cs.rs"] mod imp; #[cfg(all(feature = "std", feature = "parking_lot"))] #[path = "imp_pl.rs"] mod imp; #[cfg(all(feature = "std", not(feature = "parking_lot")))] #[path = "imp_std.rs"] mod imp; /// Single-threaded version of `OnceCell`. pub mod unsync { use core::cell::{Cell, UnsafeCell}; use core::fmt; use core::mem; use core::ops::{Deref, DerefMut}; use core::panic::{RefUnwindSafe, UnwindSafe}; /// A cell which can be written to only once. It is not thread safe. /// /// Unlike [`std::cell::RefCell`], a `OnceCell` provides simple `&` /// references to the contents. /// /// [`std::cell::RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html /// /// # Example /// ``` use once_cell::unsync::OnceCell; let cell = OnceCell::new(); assert!(cell.get().is_none()); let value = cell.get_or_init(|| 42); assert_eq!(*value, 42); assert!(cell.get().is_some()); let value2 = cell.get_or_init(|| panic!("this should not happen")); assert_eq!(*value2, 42); ``` pub struct OnceCell { inner: UnsafeCell>, } impl OnceCell { /// Creates a new empty `OnceCell`. #[inline] pub const fn new() -> OnceCell { OnceCell { inner: UnsafeCell::new(None) } } /// Returns a reference to the contained value, without initializing it. #[inline] pub fn get(&self) -> Option<&T> { unsafe { (*self.inner.get()).as_ref() } } /// Returns a mutable reference to the contained value, without initializing it. #[inline] pub fn get_mut(&mut self) -> Option<&mut T> { unsafe { (*self.inner.get()).as_mut() } } /// Initializes the `OnceCell` with the given value. /// /// Returns `Ok(())` if the cell was empty, and `Err(value)` if the cell /// was already initialized. /// /// # Example /// ``` use once_cell::unsync::OnceCell; let cell = OnceCell::new(); assert!(cell.set(42).is_ok()); assert_eq!(cell.get(), Some(&42)); assert!(cell.set(43).is_err()); ``` #[inline] pub fn set(&self, value: T) -> Result<(), T> { let inner = unsafe { &mut *self.inner.get() }; match inner { Some(_) => Err(value), None => { *inner = Some(value); Ok(()) } } } /// Initializes the `OnceCell` with the result of the closure `f`. /// /// If the cell is already initialized, the value is not changed. /// If the cell is empty, `f` is called, and its return value is stored /// in the cell. If `f` panics, the cell remains empty. /// /// # Example /// ``` use once_cell::unsync::OnceCell; let cell = OnceCell::new(); let value = cell.get_or_init(|| 42); assert_eq!(*value, 42); let value2 = cell.get_or_init(|| panic!("this should not happen")); assert_eq!(*value2, 42); ``` pub fn get_or_init(&self, f: F) -> &T where F: FnOnce() -> T, { self.get_or_try_init(|| Ok(f())) .unwrap_or_else(|_| panic!("initializer panicked")) } /// Initializes the `OnceCell` with the result of the closure `f`. /// /// If the cell is already initialized, the value is not changed. /// If the cell is empty, `f` is called, and its return value is stored /// in the cell. If `f` returns an `Err`, the cell remains empty. /// /// # Example /// ``` use once_cell::unsync::OnceCell; let cell = OnceCell::new(); let value = cell.get_or_try_init(|| Ok(42)).unwrap(); assert_eq!(*value, 42); let err = cell.get_or_try_init(|| Err::(()) .map_err(|_| panic!("this should not happen")) ).unwrap_err(); assert!(err.is_err()); ``` pub fn get_or_try_init(&self, f: F) -> Result<&T, E> where F: FnOnce() -> Result, { if let Some(value) = self.get() { return Ok(value); } match f() { Ok(value) => { match self.set(value) { Ok(_) => self.get().unwrap(), // Safe because we just set it Err(value) => { // This should not happen, because we checked that the cell is empty. // If it happens, it means that another thread has initialized the cell // between the check and the set. In this case, we just return the value // that was already in the cell. mem::forget(value); self.get().unwrap() // Safe because another thread has set it. } } } Err(err) => Err(err), } } /// Takes the value out of the `OnceCell`, leaving an empty cell. /// /// # Example /// ``` use once_cell::unsync::OnceCell; let cell = OnceCell::new(); cell.set(42).unwrap(); assert_eq!(cell.take(), Some(42)); assert!(cell.get().is_none()); assert_eq!(cell.take(), None); ``` pub fn take(&self) -> Option { let inner = unsafe { &mut *self.inner.get() }; inner.take() } } impl fmt::Debug for OnceCell { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.get() { Some(value) => fmt::Debug::fmt(value, f), None => f.debug_struct("OnceCell").finish(), } } } impl Clone for OnceCell { fn clone(&self) -> Self { let inner = unsafe { &*self.inner.get() }; OnceCell { inner: UnsafeCell::new(inner.clone()) } } } unsafe impl Send for OnceCell {} unsafe impl Sync for OnceCell {} impl UnwindSafe for OnceCell {} impl RefUnwindSafe for OnceCell {} } ``` -------------------------------- ### OnceRef.get_or_init() example Source: https://docs.rs/once_cell/latest/src/once_cell/race.rs.html?search=u32+-%3E+bool Initializes a OnceRef with a value using a closure if it's empty. If multiple threads call this concurrently, only one closure will be executed, but all threads will receive the same initialized value. ```Rust pub fn get_or_init(&self, f: F) -> &'a T where F: FnOnce() -> &'a T, { enum Void {} match self.get_or_try_init(|| Ok::<&'a T, Void>(f())) { Ok(val) => val, Err(void) => match void {}, } } ``` -------------------------------- ### Lazy Initialization and Access Source: https://docs.rs/once_cell/latest/src/once_cell/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to create a Lazy value and access its content after initialization. The `get` method returns `None` before initialization and `Some(&T)` afterwards. ```rust use once_cell::sync::Lazy; let lazy = Lazy::new(|| 92); assert_eq!(Lazy::get(&lazy), None); assert_eq!(&*lazy, &92); assert_eq!(Lazy::get(&lazy), Some(&92)); ``` -------------------------------- ### get_or_try_init Source: https://docs.rs/once_cell/latest/once_cell/sync/struct.OnceCell.html Gets the contents of the cell, initializing it with a closure if the cell was empty. If the cell was empty and the closure fails, an error is returned. Panics are propagated, and reentrant initialization is an error. ```APIDOC ## pub fn get_or_try_init(&self, f: F) -> Result<&T, E> ### Description Gets the contents of the cell, initializing it with `f` if the cell was empty. If the cell was empty and `f` failed, an error is returned. ### 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`. The exact outcome is unspecified. Current implementation deadlocks, but this may be changed to a panic in the future. ### Example ```rust use once_cell::sync::OnceCell; let cell = OnceCell::new(); assert_eq!(cell.get_or_try_init(|| Err(())), Err(())); assert!(cell.get().is_none()); let value = cell.get_or_try_init(|| -> Result { Ok(92) }); assert_eq!(value, Ok(&92)); assert_eq!(cell.get(), Some(&92)) ``` ``` -------------------------------- ### Example Usage of OnceCell Source: https://docs.rs/once_cell/latest/once_cell/index.html?search= Demonstrates a basic usage pattern for accessing a value initialized by a OnceCell. This snippet is illustrative and not directly executable without surrounding context. ```rust let _a = &a.b.a.b.a; ``` -------------------------------- ### get_or_try_init Source: https://docs.rs/once_cell/latest/src/once_cell/lib.rs.html Gets the contents of the cell, initializing it with a provided function if the cell was empty. If the initialization function fails, an error is returned. Panics if the initialization function panics or if reentrantly called. ```APIDOC ## get_or_try_init ### Description Gets the contents of the cell, initializing it with `f` if the cell was empty. If the cell was empty and `f` failed, an error is returned. This method is useful when the initialization process itself can fail. ### 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`. The current implementation deadlocks, but this may be changed to a panic in the future. ### Method Signature `pub fn get_or_try_init(&self, f: F) -> Result<&T, E> where F: FnOnce() -> Result` ### Example ```rust use once_cell::sync::OnceCell; let cell = OnceCell::new(); assert_eq!(cell.get_or_try_init(|| Err(())), Err(())); assert!(cell.get().is_none()); let value = cell.get_or_try_init(|| -> Result { Ok(92) }); assert_eq!(value, Ok(&92)); assert_eq!(cell.get(), Some(&92)) ``` ``` -------------------------------- ### get_or_init Source: https://docs.rs/once_cell/latest/src/once_cell/lib.rs.html Gets the contents of the cell, initializing it with a provided closure if the cell was empty. Panics if the closure panics or if reentrantly initialized. ```APIDOC ## get_or_init ### Description Gets the contents of the cell, initializing it with a closure `f` if the cell was empty. If the cell is already initialized, its existing value is returned. Panics if `f` panics or if reentrantly initialized. ### Method `get_or_init(&self, f: F) -> &T where F: FnOnce() -> T` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **f** (FnOnce() -> T) - A closure that returns the value to initialize the `OnceCell` with if it's empty. ### Request Example ```rust use once_cell::unsync::OnceCell; let cell = OnceCell::new(); let value = cell.get_or_init(|| 92); assert_eq!(value, &92); let value = cell.get_or_init(|| unreachable!()); // This will not be called assert_eq!(value, &92); ``` ### Response #### Success Response Returns a reference to the value inside the `OnceCell` (`&T`). This will be the newly initialized value if the cell was empty, or the existing value if it was already initialized. #### Response Example ```rust &92 ``` ### Panics * If the closure `f` panics. * If the cell is reentrantly initialized from within `f`. ``` -------------------------------- ### get_or_try_init Source: https://docs.rs/once_cell/latest/src/once_cell/lib.rs.html?search= Gets the contents of the cell, initializing it with a provided function if the cell was empty. If the cell was empty and the initialization function `f` returns an error, that error is returned. ```APIDOC ## get_or_try_init ### Description Gets the contents of the cell, initializing it with `f` if the cell was empty. If the cell was empty and `f` failed, an error is returned. ### 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`. The exact outcome is unspecified. Current implementation deadlocks, but this may be changed to a panic in the future. ### Method Signature `pub fn get_or_try_init(&self, f: F) -> Result<&T, E> where F: FnOnce() -> Result` ### Example ```rust use once_cell::sync::OnceCell; let cell = OnceCell::new(); assert_eq!(cell.get_or_try_init(|| Err(())), Err(())); assert!(cell.get().is_none()); let value = cell.get_or_try_init(|| -> Result { Ok(92) }); assert_eq!(value, Ok(&92)); assert_eq!(cell.get(), Some(&92)) ``` ``` -------------------------------- ### Get or Initialize OnceCell with a Closure Source: https://docs.rs/once_cell/latest/once_cell/sync/struct.OnceCell.html Shows how `get_or_init` can be used to lazily initialize a OnceCell with a value computed by a closure. It guarantees that the closure is executed at most once. ```Rust use once_cell::sync::OnceCell; let cell = OnceCell::new(); let value = cell.get_or_init(|| 92); assert_eq!(value, &92); let value = cell.get_or_init(|| unreachable!()); assert_eq!(value, &92); ``` -------------------------------- ### Using sync::OnceLock Source: https://docs.rs/once_cell/latest/once_cell?search= Shows how to use OnceLock from the sync module, which is equivalent to std::sync::OnceLock. ```rust use once_cell::sync::OnceLock; static NAME: OnceLock = OnceLock::new(); fn get_name() -> &'static str { NAME.get_or_init(|| "Alice".to_string()) } assert_eq!(get_name(), "Alice"); assert_eq!(get_name(), "Alice"); ``` -------------------------------- ### Get Reference to Initialized Lazy Value Source: https://docs.rs/once_cell/latest/once_cell/sync/struct.Lazy.html?search=u32+-%3E+bool Illustrates how to safely get an `Option<&T>` reference to the lazily initialized value using `Lazy::get` after it has been initialized. Before initialization, it returns `None`. ```rust use once_cell::sync::Lazy; let lazy = Lazy::new(|| 92); assert_eq!(Lazy::get(&lazy), None); assert_eq!(&*lazy, &92); assert_eq!(Lazy::get(&lazy), Some(&92)); ``` -------------------------------- ### AtomicU8 initialization logic Source: https://docs.rs/once_cell/latest/src/once_cell/imp_pl.rs.html?search=u32+-%3E+bool This snippet demonstrates the internal logic for initializing an `AtomicU8` state, handling different states like `INCOMPLETE`, `RUNNING`, and `COMPLETE` using compare-and-swap operations and parking/unparking mechanisms. ```rust fn initialize_inner(state: &AtomicU8, init: &mut dyn FnMut() -> bool) { loop { let exchange = state.compare_exchange_weak(INCOMPLETE, RUNNING, Ordering::Acquire, Ordering::Acquire); match exchange { Ok(_) => { let mut guard = Guard { state, new_state: INCOMPLETE }; if init() { guard.new_state = COMPLETE; } return; } Err(COMPLETE) => return, Err(RUNNING) => unsafe { let key = state as *const AtomicU8 as usize; parking_lot_core::park( key, || state.load(Ordering::Relaxed) == RUNNING, || (), |_, _| (), parking_lot_core::DEFAULT_PARK_TOKEN, None, ); }, Err(INCOMPLETE) => (), Err(_) => debug_assert!(false), } } } ``` -------------------------------- ### CloneToUninit Implementation Source: https://docs.rs/once_cell/latest/once_cell/unsync/struct.OnceCell.html Provides an experimental, nightly-only API for cloning data into uninitialized memory. ```APIDOC ### impl CloneToUninit for T where T: Clone, #### unsafe fn clone_to_uninit(&self, dest: *mut u8) Performs copy-assignment from `self` to `dest`. ``` -------------------------------- ### Get Mutable Reference to Lazy Value Source: https://docs.rs/once_cell/latest/once_cell/sync/struct.Lazy.html?search=u32+-%3E+bool Shows how to get a mutable `Option<&mut T>` reference to the lazily initialized value using `Lazy::get_mut`. This is useful for modifying the value after initialization. ```rust use once_cell::sync::Lazy; let mut lazy = Lazy::new(|| 92); assert_eq!(Lazy::get_mut(&mut lazy), None); assert_eq!(&*lazy, &92); assert_eq!(Lazy::get_mut(&mut lazy), Some(&mut 92)); ``` -------------------------------- ### Initialize OnceCell with get_or_try_init Source: https://docs.rs/once_cell/latest/once_cell/sync/struct.OnceCell.html Demonstrates initializing a `OnceCell` using `get_or_try_init`. This method attempts to initialize the cell if it's empty, returning an error if the initialization function fails. It's useful when the initialization process itself can fail. ```Rust use once_cell::sync::OnceCell; let cell = OnceCell::new(); assert_eq!(cell.get_or_try_init(|| Err(())), Err(())); assert!(cell.get().is_none()); let value = cell.get_or_try_init(|| -> Result { Ok(92) }); assert_eq!(value, Ok(&92)); assert_eq!(cell.get(), Some(&92)) ``` -------------------------------- ### Initializing OnceCell with get_or_try_init Source: https://docs.rs/once_cell/latest/once_cell/unsync/struct.OnceCell.html?search= Demonstrates `get_or_try_init` for initializing a `OnceCell` with a closure that returns a `Result`. It handles both successful initialization and errors from the closure, ensuring the cell remains uninitialized on failure. ```rust use once_cell::unsync::OnceCell; let cell = OnceCell::new(); assert_eq!(cell.get_or_try_init(|| Err(())), Err(())); assert!(cell.get().is_none()); let value = cell.get_or_try_init(|| -> Result { Ok(92) }); assert_eq!(value, Ok(&92)); assert_eq!(cell.get(), Some(&92)) ``` -------------------------------- ### Any for T Source: https://docs.rs/once_cell/latest/once_cell/sync/struct.OnceCell.html?search=std%3A%3Avec Provides the `type_id` method to get the TypeId of the instance. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method `type_id` ### Parameters None ### Return Value - `TypeId`: The unique identifier for the type of `self`. ``` -------------------------------- ### Any Implementation Source: https://docs.rs/once_cell/latest/once_cell/unsync/struct.OnceCell.html Provides a way to get the type's `TypeId`. ```APIDOC ### impl Any for T where T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. ``` -------------------------------- ### Initialize OnceBool with u32 using get_or_init Source: https://docs.rs/once_cell/latest/once_cell?search=u32+-%3E+bool Use `get_or_init` to initialize a `OnceBool` cell. The initialization function `f` must match the `u32` type, and the method returns a `bool`. ```rust once_cell::race::OnceBool::get_or_init(&OnceBool, F) -> bool where u32: F ``` -------------------------------- ### CloneToUninit for T Source: https://docs.rs/once_cell/latest/once_cell/sync/struct.OnceCell.html?search=std%3A%3Avec Nightly-only experimental API for cloning to uninitialized memory. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description Performs copy-assignment from `self` to `dest`. ### Method `clone_to_uninit` ### Parameters - `dest` (*mut u8): A pointer to the destination memory. ### Safety This function is unsafe and requires `T: Clone`. It is a nightly-only experimental API. ``` -------------------------------- ### OnceCell::get_or_init Source: https://docs.rs/once_cell/latest/once_cell/unsync/struct.OnceCell.html?search=std%3A%3Avec Gets the value from the cell, initializing it with a closure if it's empty. ```APIDOC ## OnceCell::get_or_init ### Description Gets the contents of the cell, initializing it with `f` if the cell was empty. ### Parameters * `f`: A closure that returns the value to initialize the cell with. ### Returns A reference to the initialized value in the cell. ### Panics * If `f` panics, the panic is propagated, and the cell remains uninitialized. * Reentrantly initializing the cell from `f` results in a panic. ### Example ```rust use once_cell::unsync::OnceCell; let cell = OnceCell::new(); let value = cell.get_or_init(|| 92); assert_eq!(value, &92); // Subsequent calls return the existing value without executing the closure let value = cell.get_or_init(|| unreachable!()); assert_eq!(value, &92); ``` ``` -------------------------------- ### OnceRef get Source: https://docs.rs/once_cell/latest/src/once_cell/race.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves an immutable reference to the value inside the OnceRef cell, if it has been set. ```rust let ptr = self.inner.load(Ordering::Acquire); unsafe { ptr.as_ref() } ``` -------------------------------- ### OnceCell Core API Overview Source: https://docs.rs/once_cell/latest/once_cell/index.html?search= Illustrates the basic interface of `OnceCell`, including methods for creation, setting a value, and retrieving it. ```rust impl OnceCell { const fn new() -> OnceCell { ... } fn set(&self, value: T) -> Result<(), T> { ... } fn get(&self) -> Option<&T> { ... } } ``` -------------------------------- ### Get value from OnceNonZeroUsize Source: https://docs.rs/once_cell/latest/src/once_cell/race.rs.html?search=u32+-%3E+bool Retrieves the stored `NonZeroUsize` value from the cell using `Ordering::Acquire`. ```rust pub fn get(&self) -> Option { let val = self.inner.load(Ordering::Acquire); NonZeroUsize::new(val) } ``` -------------------------------- ### Basic Lazy Initialization with OnceCell Source: https://docs.rs/once_cell/latest/once_cell/index.html?search= Demonstrates how to use OnceCell for lazy initialization of a resource, such as loading data from a file. The resource is loaded only when first accessed. ```Rust use std::sync::OnceCell; use std::path::Path; struct TestResource { path: &'static str, cell: OnceCell>, } impl TestResource { pub const fn new(path: &'static str) -> TestResource { TestResource { path, cell: OnceCell::new() } } pub fn bytes(&self) -> &[u8] { self.cell.get_or_init(|| { let dir = std::env::var("CARGO_MANIFEST_DIR").unwrap(); let path = Path::new(dir.as_str()).join(self.path); std::fs::read(&path).unwrap_or_else(|_err| { panic!("failed to load test resource: {}", path.display()) }) }).as_slice() } } static TEST_IMAGE: TestResource = TestResource::new("test_data/lena.png"); #[test] fn test_sobel_filter() { let rgb: &[u8] = TEST_IMAGE.bytes(); // ... } ``` -------------------------------- ### Create a OnceBox with an initial value Source: https://docs.rs/once_cell/latest/once_cell/race/struct.OnceBox.html Creates a new OnceBox and immediately sets it with a provided boxed value. ```rust pub fn with_value(value: Box) -> Self ``` -------------------------------- ### Lazy::get_mut Source: https://docs.rs/once_cell/latest/once_cell/sync/struct.Lazy.html?search= Gets the reference to the result of this lazy value if it was initialized, otherwise returns `None`. ```APIDOC ## Lazy::get_mut ### Description Gets the reference to the result of this lazy value if it was initialized, otherwise returns `None`. ### Method `get_mut` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * `this` - A mutable reference to the `Lazy` instance. ### Returns `Option<&mut T>`: `Some(&mut value)` if initialized, `None` otherwise. ``` -------------------------------- ### Lazy::get Source: https://docs.rs/once_cell/latest/once_cell/sync/struct.Lazy.html?search= Gets the reference to the result of this lazy value if it was initialized, otherwise returns `None`. ```APIDOC ## Lazy::get ### Description Gets the reference to the result of this lazy value if it was initialized, otherwise returns `None`. ### Method `get` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * `this` - A reference to the `Lazy` instance. ### Returns `Option<&T>`: `Some(&value)` if initialized, `None` otherwise. ``` -------------------------------- ### Runtime Resource Loading with OnceCell Source: https://docs.rs/once_cell/latest/once_cell/index.html?search= Demonstrates loading resources at runtime using `OnceCell` as an alternative to the `include_bytes!` macro, which can slow down test compilation. ```rust use std::path::Path; use once_cell::sync::OnceCell; pub struct TestResource { path: &'static str, cell: OnceCell>, } ``` -------------------------------- ### OnceNonZeroUsize::get Source: https://docs.rs/once_cell/latest/once_cell/race/struct.OnceNonZeroUsize.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets the underlying NonZeroUsize value from the cell if it has been initialized, otherwise returns None. ```APIDOC ## OnceNonZeroUsize::get ### Description Gets the underlying value. ### Method `fn get(&self) -> Option` ``` -------------------------------- ### OnceCell::get_mut Source: https://docs.rs/once_cell/latest/src/once_cell/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets a mutable reference to the contained value if the cell has been initialized, otherwise returns `None`. ```APIDOC ## OnceCell::get_mut ### Description Returns a mutable reference to the initialized value if the cell is full, otherwise returns `None`. ### Method `get_mut(&mut self) -> Option<&mut T>` ### Endpoint N/A (method) ### Parameters None ### Request Example ```rust use once_cell::sync::OnceCell; let mut cell: OnceCell = OnceCell::new(); assert_eq!(cell.get_mut(), None); let mut cell = OnceCell::with_value(42); assert_eq!(cell.get_mut(), Some(&mut 42)); ``` ### Response #### Success Response - `Some(&mut T)`: If the cell is initialized, containing a mutable reference to the value. - `None`: If the cell is not yet initialized. #### Response Example ```rust // See request example for output. ``` ``` -------------------------------- ### Resource Loading with OnceCell Source: https://docs.rs/once_cell/latest/once_cell/index.html?search=std%3A%3Avec Demonstrates loading a static resource file using `OnceCell` for lazy initialization. The resource is read from the file system only when first accessed. ```Rust use once_cell::sync::OnceCell; use std::path::Path; struct TestResource { path: &'static str, cell: OnceCell>, } impl TestResource { pub const fn new(path: &'static str) -> TestResource { TestResource { path, cell: OnceCell::new() } } pub fn bytes(&self) -> &[u8] { self.cell.get_or_init(|| { let dir = std::env::var("CARGO_MANIFEST_DIR").unwrap(); let path = Path::new(dir.as_str()).join(self.path); std::fs::read(&path).unwrap_or_else(|_err| { panic!("failed to load test resource: {}", path.display()) }) }).as_slice() } } static TEST_IMAGE: TestResource = TestResource::new("test_data/lena.png"); #[test] fn test_sobel_filter() { let rgb: &[u8] = TEST_IMAGE.bytes(); // ... } ``` -------------------------------- ### OnceCell::get Source: https://docs.rs/once_cell/latest/src/once_cell/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets an immutable reference to the value inside the OnceCell. Returns `None` if the cell has not been initialized. ```APIDOC ## `OnceCell::get()` ### Description Gets a reference to the underlying value. Returns `None` if the cell is empty. ### Method `pub fn get(&self) -> Option<&T>` ### Example ```rust use once_cell::unsync::OnceCell; let cell = OnceCell::new(); assert!(cell.get().is_none()); cell.set(10).unwrap(); assert_eq!(cell.get(), Some(&10)); ``` ``` -------------------------------- ### OnceBool get_or_init Source: https://docs.rs/once_cell/latest/src/once_cell/race.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets the boolean value, initializing with a closure if the cell is empty. Handles concurrent initializations. ```rust Self::from_usize(self.inner.get_or_init(|| Self::to_usize(f()))) ``` -------------------------------- ### OnceRef get Source: https://docs.rs/once_cell/latest/src/once_cell/race.rs.html?search=std%3A%3Avec Atomically loads and returns a reference to the contained value if it exists, using `Acquire` ordering. ```rust pub fn get(&self) -> Option<&'a T> { let ptr = self.inner.load(Ordering::Acquire); unsafe { ptr.as_ref() } } ``` -------------------------------- ### OnceBool::get_or_try_init signature Source: https://docs.rs/once_cell/latest/src/once_cell/imp_pl.rs.html?search=u32+-%3E+bool Shows the signature for `get_or_try_init` on `OnceBool`, indicating that the closure `F` must match `u32` and return a `Result`. ```rust fn get_or_try_init(&self, f: F) -> Result where F: FnOnce() -> Result, u32: From, ``` -------------------------------- ### OnceNonZeroUsize::get_unchecked Source: https://docs.rs/once_cell/latest/once_cell/race/struct.OnceNonZeroUsize.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets the underlying NonZeroUsize value without checking if the cell is initialized. Use with caution. ```APIDOC ## OnceNonZeroUsize::get_unchecked ### Description Get the reference to the underlying value, without checking if the cell is initialized. ### Safety Caller must ensure that the cell is in initialized state, and that the contents are acquired by (synchronized to) this thread. ### Method `unsafe fn get_unchecked(&self) -> NonZeroUsize` ``` -------------------------------- ### Initialize OnceBool with u32 using get_or_try_init Source: https://docs.rs/once_cell/latest/once_cell?search=u32+-%3E+bool Use `get_or_try_init` for fallible initialization of a `OnceBool` cell. The initialization function `f` must match the `u32` type, and the method returns a `Result`. ```rust once_cell::race::OnceBool::get_or_try_init(&OnceBool, F) -> Result where u32: F ``` -------------------------------- ### CloneToUninit experimental API Source: https://docs.rs/once_cell/latest/once_cell/race/struct.OnceBox.html An experimental nightly-only API for cloning data into uninitialized memory. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Building Cyclic Data Structures with LateInit Source: https://docs.rs/once_cell/latest/once_cell/index.html?search=u32+-%3E+bool Demonstrates the usage of LateInit to create mutually referential data structures (a cycle). The `init` method is used to establish the references after the initial default construction. ```Rust #[derive(Default)] struct A<'a> { b: LateInit<&'a B<'a>>, } #[derive(Default)] struct B<'a> { a: LateInit<&'a A<'a>> } fn build_cycle() { let a = A::default(); let b = B::default(); a.b.init(&b); b.a.init(&a); } ``` -------------------------------- ### OnceCell Methods Source: https://docs.rs/once_cell/latest/src/once_cell/imp_pl.rs.html Provides documentation for the core methods of OnceCell, including initialization, state checking, and value retrieval. These methods are marked as `pub(crate)` indicating they are intended for internal use within the crate. ```APIDOC ## OnceCell Methods ### `new()` - **Description**: Creates a new, uninitialized `OnceCell`. - **Signature**: `pub(crate) const fn new() -> OnceCell` ### `with_value(value: T)` - **Description**: Creates a new `OnceCell` initialized with the given value. - **Signature**: `pub(crate) const fn with_value(value: T) -> OnceCell` ### `is_initialized()` - **Description**: Checks if the `OnceCell` has been initialized. - **Safety**: Synchronizes with `store` to `value` via Release/Acquire semantics. - **Signature**: `pub(crate) fn is_initialized(&self) -> bool` ### `initialize(f: F)` - **Description**: Initializes the `OnceCell` by calling the provided closure `f`. If the closure returns `Ok(T)`, the value is stored. If it returns `Err(E)`, the error is returned, and the cell remains uninitialized. This method handles potential panics and re-entrant calls within the closure. - **Safety**: The closure `f` must be safe to call and must not cause deadlocks if it re-enters `OnceCell` methods. - **Signature**: `pub(crate) fn initialize(&self, f: F) -> Result<(), E> where F: FnOnce() -> Result` ### `wait()` - **Description**: Blocks the current thread until the `OnceCell` is initialized. Uses `parking_lot_core::park` for efficient waiting. - **Signature**: `pub(crate) fn wait(&self)` ### `get_unchecked()` - **Description**: Returns an unchecked reference to the underlying value. This is an unsafe operation that bypasses initialization checks. - **Safety**: Caller must ensure the cell is initialized and synchronized. - **Signature**: `pub(crate) unsafe fn get_unchecked(&self) -> &T` ### `get_mut()` - **Description**: Returns a mutable reference to the underlying value if the cell is initialized. This method requires mutable access to the `OnceCell`. - **Safety**: Safe because it requires exclusive access (`&mut self`). - **Signature**: `pub(crate) fn get_mut(&mut self) -> Option<&mut T>` ### `into_inner()` - **Description**: Consumes the `OnceCell` and returns the contained value, or `None` if it was empty. - **Signature**: `pub(crate) fn into_inner(self) -> Option` ``` -------------------------------- ### OnceBool get Source: https://docs.rs/once_cell/latest/src/once_cell/race.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves the boolean value from the cell, if set. Converts the internal usize representation to Option. ```rust self.inner.get().map(Self::from_usize) ``` -------------------------------- ### OnceBox::new Source: https://docs.rs/once_cell/latest/once_cell/race/struct.OnceBox.html?search=u32+-%3E+bool Creates a new, empty OnceBox. This is the initial state before any value is set or initialized. ```APIDOC ## OnceBox::new ### Description Creates a new empty cell. ### Method `const fn new() -> Self` ### Returns A new, empty `OnceBox` instance. ``` -------------------------------- ### OnceBool Source: https://docs.rs/once_cell/latest/src/once_cell/race.rs.html Represents a thread-safe boolean cell that can be written to only once. It provides methods to get, set, and initialize the boolean value. ```APIDOC ## OnceBool ### Description A thread-safe cell which can be written to only once. ### Methods #### `new()` Creates a new empty cell. - **Returns**: A new `OnceBool` instance. #### `get()` Gets the underlying boolean value if the cell has been initialized. - **Returns**: `Some(bool)` if the cell contains a value, `None` otherwise. #### `set(value: bool)` Sets the contents of this cell to `value`. Returns `Ok(())` if the cell was empty and `Err(())` if it was full. - **Parameters**: - `value` (bool) - The boolean value to set. - **Returns**: `Result<(), ()>` indicating success or if the cell was already set. #### `get_or_init(f: F)` Gets the contents of the cell, initializing it with `f` if the cell was empty. If several threads concurrently run `get_or_init`, more than one `f` can be called, but all threads will return the same value. - **Parameters**: - `f` (FnOnce() -> bool) - A closure that returns a boolean value to initialize the cell. - **Returns**: The boolean value stored in the cell. #### `get_or_try_init(f: F)` Gets the contents of the cell, initializing it with `f` if the cell was empty. If the cell was empty and `f` failed, an error is returned. If several threads concurrently run `get_or_init`, more than one `f` can be called, but all threads will return the same value. - **Parameters**: - `f` (FnOnce() -> Result) - A closure that returns a `Result` containing a boolean value or an error. - **Returns**: `Result` containing the initialized boolean value or an error if initialization failed. ``` -------------------------------- ### get_or_try_init Source: https://docs.rs/once_cell/latest/src/once_cell/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets the contents of the cell, initializing it with a provided function if the cell was empty. If the cell was empty and the initialization function `f` fails, an error is returned. Panics are propagated, and reentrant initialization is an error. ```APIDOC ## get_or_try_init ### Description Gets the contents of the cell, initializing it with `f` if the cell was empty. If the cell was empty and `f` failed, an error is returned. ### 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`. The exact outcome is unspecified. ### Signature ```rust pub fn get_or_try_init(&self, f: F) -> Result<&T, E> where F: FnOnce() -> Result ``` ### Example ```rust use once_cell::sync::OnceCell; let cell = OnceCell::new(); assert_eq!(cell.get_or_try_init(|| Err(())), Err(())); assert!(cell.get().is_none()); let value = cell.get_or_try_init(|| -> Result { Ok(92) }); assert_eq!(value, Ok(&92)); assert_eq!(cell.get(), Some(&92)) ``` ```