### StaticCell::try_uninit() - Safely Get Uninitialized Memory Source: https://context7.com/embassy-rs/static-cell/llms.txt Attempts to get a mutable reference to the uninitialized memory of a StaticCell. It returns `Some(&'static mut MaybeUninit)` if the cell has not yet been initialized, and `None` otherwise. This method is useful for safe manual initialization in concurrent scenarios, preventing race conditions. ```rust use static_cell::StaticCell; static DATA: StaticCell = StaticCell::new(); fn initialize() -> bool { if let Some(uninit) = DATA.try_uninit() { uninit.write(0xDEADBEEF); return true; } false } fn main() { assert!(initialize()); // First call succeeds assert!(!initialize()); // Second call fails } ``` -------------------------------- ### StaticCell::uninit() - Get Uninitialized Memory Source: https://context7.com/embassy-rs/static-cell/llms.txt Returns a mutable reference to the uninitialized memory of a StaticCell. This allows for manual construction of the value using `MaybeUninit`, offering fine-grained control over initialization. It is primarily used when you need to construct a value in place within a static context. ```rust use static_cell::StaticCell; use std::mem::MaybeUninit; static CUSTOM: StaticCell> = StaticCell::new(); fn main() { // Get uninitialized memory let uninit: &'static mut MaybeUninit> = CUSTOM.uninit(); // Manually construct in-place let value: &'static mut Vec = uninit.write(Vec::new()); value.push(10); value.push(20); value.push(30); assert_eq!(value.len(), 3); assert_eq!(value[0], 10); } ``` -------------------------------- ### Rust: Initialize StaticCell with Vec and Counter Source: https://context7.com/embassy-rs/static-cell/llms.txt Demonstrates creating and initializing `StaticCell` instances for a `Vec` and a `u32` counter. It reserves memory at compile time and defers initialization until runtime, returning mutable static references. Panics if already initialized. ```rust use static_cell::StaticCell; // Allocate memory at compile time in static storage static MY_CELL: StaticCell> = StaticCell::new(); static COUNTER: StaticCell = StaticCell::new(); fn initialize_globals() { // Initialize at runtime with actual values let buffer: &'static mut Vec = MY_CELL.init(Vec::with_capacity(1024)); buffer.push(42); let count: &'static mut u32 = COUNTER.init(0); *count += 1; assert_eq!(buffer[0], 42); assert_eq!(*count, 1); } ``` -------------------------------- ### Rust: Concurrent initialization with StaticCell::try_init Source: https://context7.com/embassy-rs/static-cell/llms.txt Demonstrates safe concurrent initialization of a `StaticCell` using `try_init`. Multiple threads attempt to initialize the cell; only the first one to succeed returns `Some` with a mutable reference. Other threads receive `None`. This ensures that the initialization logic runs exactly once. ```rust use static_cell::StaticCell; use std::thread; static SHARED_RESOURCE: StaticCell = StaticCell::new(); fn main() { let handles: Vec<_> = (0..5).map(|i| { thread::spawn(move || { // Only one thread will successfully initialize if let Some(s) = SHARED_RESOURCE.try_init(format!("Thread {} won", i)) { println!("Initialized by thread {}", i); return true; } false }) }).collect(); let results: Vec = handles.into_iter() .map(|h| h.join().unwrap()) .collect(); // Exactly one thread succeeded assert_eq!(results.iter().filter(|&&x| x).count(), 1); } ``` -------------------------------- ### StaticCell::try_init_with() Source: https://context7.com/embassy-rs/static-cell/llms.txt Attempts in-place initialization using a closure. Returns `None` if the cell is already initialized, combining the safety of `try_init` with the efficiency of `init_with` for concurrent scenarios. ```APIDOC ## StaticCell::try_init_with() ### Description Attempts in-place initialization using a closure, returning `None` if already initialized, combining the benefits of `try_init` and `init_with` for concurrent scenarios with large types. ### Method Instance method ### Endpoint N/A (Rust library function) ### Parameters - **closure** (FnOnce() -> T) - Required - A closure that returns the value to initialize the `StaticCell` with. ### Request Example ```rust use static_cell::StaticCell; static CONFIG: StaticCell<[u8; 4096]> = StaticCell::new(); fn load_config() -> Option<&'static mut [u8; 4096]> { CONFIG.try_init_with(|| { // Expensive initialization done in-place let mut buffer = [0u8; 4096]; // Simulate loading config data buffer[0] = 0xCA; buffer[1] = 0xFE; buffer }) } fn main() { if let Some(config) = load_config() { assert_eq!(config[0], 0xCA); assert_eq!(config[1], 0xFE); } // Second attempt returns None assert!(load_config().is_none()); } ``` ### Response #### Success Response (200) - **`Option<&'static mut T>`** - `Some` containing a mutable static reference if initialization was successful, `None` otherwise. ### Response Example N/A ``` -------------------------------- ### Rust: Initialize StaticCell with a fixed-size array Source: https://context7.com/embassy-rs/static-cell/llms.txt Shows how to initialize a `StaticCell` containing a fixed-size byte array (`[u8; 64]`). The `init` method is used to provide the initial value, and a mutable static reference is returned. Subsequent calls to `init` on the same cell would panic. ```rust use static_cell::StaticCell; static BUFFER: StaticCell<[u8; 64]> = StaticCell::new(); fn main() { // Initialize once and get mutable static reference let buf: &'static mut [u8; 64] = BUFFER.init([0u8; 64]); buf[0] = 0xFF; buf[63] = 0xAA; assert_eq!(buf[0], 0xFF); assert_eq!(buf[63], 0xAA); // This would panic - cell already initialized: // BUFFER.init([1u8; 64]); } ``` -------------------------------- ### StaticCell::init() Source: https://context7.com/embassy-rs/static-cell/llms.txt Initializes the `StaticCell` with a value and returns a `&'static mut` reference. It panics if the cell is already initialized to enforce one-time initialization. ```APIDOC ## StaticCell::init() ### Description Initializes the `StaticCell` with a value and returns a `&'static mut` reference, panicking if the cell is already initialized to ensure one-time initialization semantics. ### Method Instance method ### Endpoint N/A (Rust library function) ### Parameters - **value** (T) - Required - The value to initialize the `StaticCell` with. ### Request Example ```rust use static_cell::StaticCell; static BUFFER: StaticCell<[u8; 64]> = StaticCell::new(); fn main() { // Initialize once and get mutable static reference let buf: &'static mut [u8; 64] = BUFFER.init([0u8; 64]); buf[0] = 0xFF; buf[63] = 0xAA; assert_eq!(buf[0], 0xFF); assert_eq!(buf[63], 0xAA); // This would panic - cell already initialized: // BUFFER.init([1u8; 64]); } ``` ### Response #### Success Response (200) - **`&'static mut T`** - A mutable static reference to the initialized value. ### Response Example N/A ``` -------------------------------- ### Rust: Concurrent in-place initialization with StaticCell::try_init_with Source: https://context7.com/embassy-rs/static-cell/llms.txt Shows thread-safe, in-place initialization of a large array (`[u8; 4096]`) within a `StaticCell` using `try_init_with`. This combines the benefits of `try_init` for concurrent safety and `init_with` for avoiding stack allocation. The closure is executed only on the first successful call. ```rust use static_cell::StaticCell; static CONFIG: StaticCell<[u8; 4096]> = StaticCell::new(); fn load_config() -> Option<&'static mut [u8; 4096]> { CONFIG.try_init_with(|| { // Expensive initialization done in-place let mut buffer = [0u8; 4096]; // Simulate loading config data buffer[0] = 0xCA; buffer[1] = 0xFE; buffer }) } fn main() { if let Some(config) = load_config() { assert_eq!(config[0], 0xCA); assert_eq!(config[1], 0xFE); } // Second attempt returns None assert!(load_config().is_none()); } ``` -------------------------------- ### StaticCell::try_init() Source: https://context7.com/embassy-rs/static-cell/llms.txt Attempts to initialize the `StaticCell`. Returns `Some(&'static mut T)` on successful initialization or `None` if the cell has already been initialized, enabling safe concurrent initialization. ```APIDOC ## StaticCell::try_init() ### Description Attempts to initialize the `StaticCell`, returning `Some(&'static mut T)` on success or `None` if already initialized, enabling safe concurrent initialization attempts. ### Method Instance method ### Endpoint N/A (Rust library function) ### Parameters - **value** (T) - Required - The value to initialize the `StaticCell` with. ### Request Example ```rust use static_cell::StaticCell; use std::thread; static SHARED_RESOURCE: StaticCell = StaticCell::new(); fn main() { let handles: Vec<_> = (0..5).map(|i| { thread::spawn(move || { // Only one thread will successfully initialize if let Some(s) = SHARED_RESOURCE.try_init(format!("Thread {} won", i)) { println!("Initialized by thread {}", i); return true; } false }) }).collect(); let results: Vec = handles.into_iter() .map(|h| h.join().unwrap()) .collect(); // Exactly one thread succeeded assert_eq!(results.iter().filter(|&&x| x).count(), 1); } ``` ### Response #### Success Response (200) - **`Option<&'static mut T>`** - `Some` containing a mutable static reference if initialization was successful, `None` otherwise. ### Response Example N/A ``` -------------------------------- ### StaticCell::init_with() Source: https://context7.com/embassy-rs/static-cell/llms.txt Initializes the `StaticCell` using a closure that constructs the value in-place. This method avoids stack allocation for large types, preventing potential stack overflows. ```APIDOC ## StaticCell::init_with() ### Description Initializes the `StaticCell` using a closure that constructs the value in-place, avoiding stack allocation and preventing stack overflow for large types. ### Method Instance method ### Endpoint N/A (Rust library function) ### Parameters - **closure** (FnOnce() -> T) - Required - A closure that returns the value to initialize the `StaticCell` with. ### Request Example ```rust use static_cell::StaticCell; // Large type that would overflow stack if constructed there static LARGE_ARRAY: StaticCell<[u64; 10000]> = StaticCell::new(); fn initialize_large_data() { // Construct in-place within the StaticCell, no stack usage let array: &'static mut [u64; 10000] = LARGE_ARRAY.init_with(|| { let mut arr = [0u64; 10000]; for i in 0..10000 { arr[i] = i as u64; } arr }); assert_eq!(array[0], 0); assert_eq!(array[9999], 9999); } ``` ### Response #### Success Response (200) - **`&'static mut T`** - A mutable static reference to the initialized value. ### Response Example N/A ``` -------------------------------- ### StaticCell::new() Source: https://context7.com/embassy-rs/static-cell/llms.txt Creates an empty `StaticCell` that reserves memory at compile time but defers initialization until runtime. This returns a const-constructable cell suitable for static contexts. ```APIDOC ## StaticCell::new() ### Description Creates an empty `StaticCell` that reserves memory at compile time but defers initialization until runtime, returning a const-constructable cell that can be used in static contexts. ### Method Associated function (constructor-like) ### Endpoint N/A (Rust library function) ### Parameters None ### Request Example ```rust use static_cell::StaticCell; // Allocate memory at compile time in static storage static MY_CELL: StaticCell> = StaticCell::new(); static COUNTER: StaticCell = StaticCell::new(); fn initialize_globals() { // Initialize at runtime with actual values let buffer: &'static mut Vec = MY_CELL.init(Vec::with_capacity(1024)); buffer.push(42); let count: &'static mut u32 = COUNTER.init(0); *count += 1; assert_eq!(buffer[0], 42); assert_eq!(*count, 1); } ``` ### Response N/A (Rust initialization) ### Response Example N/A ``` -------------------------------- ### make_static! Macro - Create Static Mutable Reference Source: https://context7.com/embassy-rs/static-cell/llms.txt The `make_static!` macro converts any given value into a `&'static mut` reference by utilizing an internal `StaticCell`. It supports the use of linker attributes, such as `#[link_section]`, for custom memory placement, although this requires the `type_alias_impl_trait` nightly feature. This macro simplifies the creation of mutable static variables. ```rust #![feature(type_alias_impl_trait)] use static_cell::make_static; fn main() { // Simple value conversion let x: &'static mut u32 = make_static!(42); *x += 10; assert_eq!(*x, 52); // Complex type let vec: &'static mut Vec = make_static!(vec![ "hello".to_string(), "world".to_string() ]); vec.push("!".to_string()); assert_eq!(vec.len(), 3); // With linker section attribute for custom placement let buf = make_static!( [0u8; 4096], #[link_section = ".external_ram.bss"] ); buf[0] = 0xFF; } ``` -------------------------------- ### Initialize StaticCell at Runtime in Rust Source: https://github.com/embassy-rs/static-cell/blob/main/README.md Demonstrates how to use `StaticCell` to allocate memory for a value at compile time and initialize it at runtime. This provides a &'static mut reference. Subsequent calls to `init()` on the same `StaticCell` will panic. ```rust use static_cell::StaticCell; // Statically allocate memory for a `u32`. static SOME_INT: StaticCell = StaticCell::new(); // Initialize it at runtime. This returns a `&'static mut`. let x: &'static mut u32 = SOME_INT.init(42); assert_eq!(*x, 42); // Trying to call `.init()` again would panic, because the StaticCell is already initialized. // SOME_INT.init(42); ``` -------------------------------- ### Rust: Initialize large array in StaticCell using init_with Source: https://context7.com/embassy-rs/static-cell/llms.txt Illustrates using `init_with` to construct a large array (`[u64; 10000]`) in-place within a `StaticCell`. This method avoids stack allocation, preventing stack overflows for large data structures. The closure provided to `init_with` is executed only once upon initialization. ```rust use static_cell::StaticCell; // Large type that would overflow stack if constructed there static LARGE_ARRAY: StaticCell<[u64; 10000]> = StaticCell::new(); fn initialize_large_data() { // Construct in-place within the StaticCell, no stack usage let array: &'static mut [u64; 10000] = LARGE_ARRAY.init_with(|| { let mut arr = [0u64; 10000]; for i in 0..10000 { arr[i] = i as u64; } arr }); assert_eq!(array[0], 0); assert_eq!(array[9999], 9999); } ``` -------------------------------- ### ConstStaticCell::new() - Create Const Static Cell Source: https://context7.com/embassy-rs/static-cell/llms.txt Creates a `ConstStaticCell` with a value that is initialized at compile time. This is ideal for large, zero-initialized buffers that should reside in the BSS segment, thereby not consuming flash memory. The value can be taken once at runtime. ```rust use static_cell::ConstStaticCell; // Large buffer initialized at compile time, placed in BSS static ZERO_BUFFER: ConstStaticCell<[u8; 8192]> = ConstStaticCell::new([0u8; 8192]); static DMA_BUFFER: ConstStaticCell<[u32; 1024]> = ConstStaticCell::new([0u32; 1024]); fn setup_dma() -> &'static mut [u32; 1024] { // Take ownership of the buffer let buffer = DMA_BUFFER.take(); buffer[0] = 0x12345678; buffer } fn main() { let buf = setup_dma(); assert_eq!(buf[0], 0x12345678); } ``` -------------------------------- ### ConstStaticCell::try_take() - Safely Attempt to Take Const Value Source: https://context7.com/embassy-rs/static-cell/llms.txt Safely attempts to take ownership of the const-initialized value from a `ConstStaticCell`. It returns `Some(&'static mut T)` if the value has not yet been taken, and `None` otherwise. This method is crucial for concurrent contexts, allowing multiple threads to safely attempt acquisition without panicking. ```rust use static_cell::ConstStaticCell; use std::thread; static SHARED_BUFFER: ConstStaticCell> = ConstStaticCell::new(Vec::new()); fn main() { let handles: Vec<_> = (0..3).map(|i| { thread::spawn(move || { if let Some(mut buf) = SHARED_BUFFER.try_take() { buf.push(i); println!("Thread {} acquired buffer", i); return Some(buf.len()); } None }) }).collect(); let results: Vec> = handles.into_iter() .map(|h| h.join().unwrap()) .collect(); // Only one thread gets the buffer assert_eq!(results.iter().filter(|x| x.is_some()).count(), 1); } ``` -------------------------------- ### ConstStaticCell::take() - Take Ownership of Const Value Source: https://context7.com/embassy-rs/static-cell/llms.txt Takes ownership of the const-initialized value from a `ConstStaticCell`, returning a `&'static mut` reference to it. This operation panics if the value has already been taken, ensuring that only one mutable reference exists at any time. It is suitable for scenarios requiring single, exclusive access to a statically initialized resource. ```rust use static_cell::ConstStaticCell; static SCRATCH: ConstStaticCell<[u8; 512]> = ConstStaticCell::new([0xFF; 512]); fn main() { // Take the buffer once let buffer: &'static mut [u8; 512] = SCRATCH.take(); buffer[0] = 0x00; buffer[511] = 0x00; assert_eq!(buffer[0], 0x00); assert_eq!(buffer[511], 0x00); // This would panic - already taken: // SCRATCH.take(); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.