Statically allocated, runtime initialized cell.

Overview

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.

You might also like...
JavaScript/TypeScript runtime Deno was meant to be.

Project Bueno (temporary name) Bueno is a web-standards focused JS/TS runtime with as much tooling built-in as possible. It is meant to be both a lear

excss is a small, simple, zero-runtime CSS-in-JS library with just two APIs.

excss excss is a small, simple, zero-runtime CSS-in-JS library with just two APIs.

A heap allocated runtime for deeply recursive algorithms.

Reblessive A heap allocated runtime for deeply recursive algorithms. Turn your cursed recursive algorithm into a blessed heap allocated structure whic

✨ Safe, global singletons initialized at program start

✨ magic_static Safe, global singletons initialized at program start. Usage Simply add magic_static as a dependency in your Cargo.toml to get started:

A stack-allocated box that stores trait objects.

This crate allows saving DST objects in the provided buffer. It allows users to create global dynamic objects on a no_std environment without a global allocator.

Cryptography-oriented big integer library with constant-time, stack-allocated (no_std-friendly) implementations of modern formulas

RustCrypto: Cryptographic Big Integers Pure Rust implementation of a big integer library which has been designed from the ground-up for use in cryptog

Stack buffer provides alternatives to Buf{Reader,Writer} allocated on the stack instead of the heap.

StackBuf{Reader,Writer} Stack buffer provides alternatives to BufReader and BufWriter allocated on the stack instead of the heap. Its implementation i

An implementation of Joshua Yanovski's Ghost Cell paper.

A novel safe and zero-cost borrow-checking paradigm from the GhostCell paper. Motivation A number of collections, such as linked-lists, binary-trees,

A cell-based esoteric programming language

Tape A cell-based esoteric programming language Tape is a cell-based, brainfuck-like programming language that has a readable syntax and a non-wasted

Like a cell, but make lifetimes dynamic instead of ownership

LendingCell is a mutable container that allows you to get an owned reference to the same object. When the owned reference is dropped, ownership return

Simulator of viral infection spread and containment in cell monolayer.

Overview VIS-A-VIS is an agent-based simulator of viral infection spread and viral infection self-containment in a monolayer of cell. The simulation m

The H3 Compressor: A compression scheme tailored for H3 cell indexes.

thc — The H3 Compressor This library allows to compress an H3 cell set into a compacted space-efficient representation. This is especially useful for

An alternative to `qcell` and `ghost-cell` that instead uses const generics

Purpose This crate is another attempt at the ghost-cell / qcell saga of cell crates. This provides an alternative to std::cell::RefCell that can allow

Thread-safe cell based on atomic pointers to externally stored data

Simple thread-safe cell PtrCell is an atomic cell type that allows safe, concurrent access to shared data. No std, no data races, no nasal demons (UB)

A rust drawing library for high quality data plotting for both WASM and native, statically and realtimely đŸĻ€ 📈🚀
A rust drawing library for high quality data plotting for both WASM and native, statically and realtimely đŸĻ€ 📈🚀

Plotters - A Rust drawing library focus on data plotting for both WASM and native applications đŸĻ€ 📈 🚀 Plotters is drawing library designed for rende

Orion lang is a lispy programming language that is strongly and statically typed.
Orion lang is a lispy programming language that is strongly and statically typed.

Orion Orion is a lisp inspired statically typed programming language written in Rust Install To install orion you can either: Download binary from the

EXPERIMENTAL: Bitcoin Core Prometheus exporter based on User-Space, Statically Defined Tracing and eBPF.

bitcoind-observer An experimental Prometheus metric exporter for Bitcoin Core based on Userspace, Statically Defined Tracing and eBPF. This demo is ba

A statically-typed, interpreted programming language, with generics and type inference

Glide A programming language. Currently, this includes: Static typing Generics, with monomorphization Type inference on function calls func identityT

Statically sized matrix using a definition with const generics

Statically sized matrix using a definition with const generics

Comments
  • Allow creating initialized `StaticCell`.

    Allow creating initialized `StaticCell`.

    Add StaticCell::new_with_value to create an initialized StaticCell which can be taken and restored.

    Example

    static DMA_BUF: StaticCell<[u8; 1024]> = StaticCell::new_with_value([0; 1024]);
    
    fn start_dma_transfer(buf: &'static mut [u8; 1024]) {
      // ...
    }
    
    fn stop_dma_transfer() -> &'static mut [u8; 1024] {
      // ...
    }
    
    fn main() {
      start_dma_transfer(DMA_BUF.take().unwrap());
    }
    
    fn interrupt() {
      let buf = stop_dma_transfer();
      DMA_BUF.restore(buf);
    }
    

    Also, a question regarding init_with, which claims

    The advantage over [StaticCell::init] is that this method allows the closure to construct the T value in-place directly inside the StaticCell, saving stack space.

    Where/how is this guaranteed? Does it depend on the platform or compiler optimizations?

    At least with the following example, it clearly doesn't work as described as it results in a stack overflow:

    std::thread::Builder::new()
      .name("init_with".to_string())
      .stack_size(512)
      .spawn(|| {
        static BUF: StaticCell<[u8; 4096]> = StaticCell::new();
        let buf = BUF.init_with(|| [1; 4096]);
    
        let mut count = 0;
        for b in buf {
          count += *b as usize;
        }
    
        assert_eq!(count, 4096);
      })
      .unwrap()
      .join();
    
    opened by reitermarkus 4
  • Add `StaticCell::uninit()`

    Add `StaticCell::uninit()`

    Sometimes I find myself using something that could be distilled to ARRAY.init([0; BIG_NUMBER]), where

    let arr = ARRAY.uninit();
    unsafe {
        arr.as_mut_ptr().write_bytes(0x00, BIG_NUMBER);
        arr.assume_init_mut()
    }
    

    Would guarantee no unnecessary memcpys or stack usage.

    opened by zRedShift 1
  • Compare to once_cell

    Compare to once_cell

    It seems once_cell is what "most people" use for this case (some use cases would also have been served by lazy_static, which would be one of the "related creates" listed on once_cell's readme). Having it as an alternative and listing the ups and downs seems practical.

    opened by chrysn 1
Owner
Rust async for embedded
null
Like a cell, but make lifetimes dynamic instead of ownership

LendingCell is a mutable container that allows you to get an owned reference to the same object. When the owned reference is dropped, ownership return

Kalle Samuels 19 Dec 15, 2022
An alternative to `qcell` and `ghost-cell` that instead uses const generics

Purpose This crate is another attempt at the ghost-cell / qcell saga of cell crates. This provides an alternative to std::cell::RefCell that can allow

SpencerBeige 5 Feb 9, 2023
Thread-safe cell based on atomic pointers to externally stored data

Simple thread-safe cell PtrCell is an atomic cell type that allows safe, concurrent access to shared data. No std, no data races, no nasal demons (UB)

Nikolay Levkovsky 3 Mar 23, 2024
A statically typed language that can deeply improve the Python ecosystem

The Erg Programming Language This is the main source code repository for Erg. This contains the compiler and documentation. æ—ĨæœŦčĒž | įŽ€äŊ“中文 | įšéĢ”中文 Erg can

The Erg Programming Language 2.1k Jan 1, 2023
Statically verified Rust struct field names as strings.

field Statically verified struct field names as strings. See the documentation for more details. Installation Add the following to your Cargo manifest

Indraneel Mahendrakumar 3 Jul 9, 2023
A parser combinator that is fully statically dispatched and supports both sync/async.

XParse A parser combinator that is fully statically dispatched and supports both sync & async parsing. How to use An example of a very simple JSON par

Alsein 4 Nov 27, 2023
zero runtime cost default arguments in rust

Default Arguments in Rust Enables default arguments in rust by macro in zero cost. Just wrap function with default_args! and macro with name of functi

Jaeyong Sung 73 Sep 6, 2022
Capability-based Linux Runtime

r-linux Capability-based Linux Runtime The r-linux project provides direct access to the application programming interfaces of the linux kernel. This

null 81 Nov 12, 2022
Rust-based language and runtime for cross-platform app development

Pax Pax is a cross-platform rendering engine & Rust framework for interactive graphics, animations, and GUIs. Pax extends the Rust programming languag

Pax 75 Dec 19, 2022
A superset of PHP with extended syntax and runtime capabilities.

PXP PXP is a superset of the PHP programming language that provides an extended set of syntax rules and language features to improve developer experie

PXP 188 Jan 29, 2023