#cell #static #runtime #static-mut

static_cell

Statically allocated, initialized at runtime cell

3 releases (1 stable)

Uses new Rust 2021

1.0.0 Aug 22, 2022
0.0.0 Aug 21, 2022

#249 in Rust patterns

Download history 89/week @ 2022-08-16 303/week @ 2022-08-23 402/week @ 2022-08-30 326/week @ 2022-09-06 272/week @ 2022-09-13 285/week @ 2022-09-20 373/week @ 2022-09-27 474/week @ 2022-10-04 389/week @ 2022-10-11 474/week @ 2022-10-18 550/week @ 2022-10-25 661/week @ 2022-11-01 2003/week @ 2022-11-08 1537/week @ 2022-11-15 1648/week @ 2022-11-22 1276/week @ 2022-11-29

6,668 downloads per month
Used in fewer than 8 crates

MIT/Apache

8KB

static-cell

crates.io crates.io Documentation

Statically allocated, initialized at runtime cell.

StaticCell provides a no-std-compatible, no-alloc way to reserve memory at compile time for a value, but initialize it at runtime, and get a 'static reference to it.

This is useful in the following scenarios:

  • You need &'static T, but T can't be constructed in const context so you can't simply use a static.
  • You need &'static mut T, not just &'static T.

Example

use static_cell::StaticCell;

// Statically allocate memory for a `u32`.
static SOME_INT: StaticCell<u32> = 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);

Alternatives

  • If you can use alloc, you can use Box::leak().
  • If you're OK with unsafe, you can use static mut THING: MaybeUninit<T>.

Interoperability

This crate uses atomic-polyfill, so on targets without native atomics you must import a crate that provides a critical-section implementation. See the critical-section README for details.

Minimum Supported Rust Version (MSRV)

This crate is guaranteed to compile on stable Rust 1.56 and up. It might compile with older versions but that may change in any new patch release.

License

This work is licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~49KB