✨ Safe, global singletons initialized at program start

Overview

crates.io docs.rs license

magic_static

Safe, global singletons initialized at program start.

Usage

Simply add magic_static as a dependency in your Cargo.toml to get started:

[dependencies]
magic_static = "*"

bare-metal

If your target doesn't support atomics or threads, enable the bare-metal feature flag in your Cargo.toml:

[dependencies]
magic_static = { version = "*", features = ["bare-metal"] }

Example

= std::sync::Mutex::new(()); } } // You can also modularize your magic statics like so: mod baz { magic_static! { pub(super) static ref MAGIC: usize = { println!("Magic!"); 42 }; pub(super) static ref BAR: std::sync::Mutex<()> = std::sync::Mutex::new(()); } #[magic_static::main( MAGIC, BAR )] // The `magic_statics!` macro (NOT `magic_static!`) can generate this function for you pub fn magic_static() {} } #[magic_static::main( foo::MAGIC, foo::BAR, mod baz // This will initialize all magic statics in `baz` )] fn main() { println!("Hello, world!"); } ">
#[macro_use]
extern crate magic_static;

mod foo {
    magic_static! {
        pub(super) static ref MAGIC: usize = {
            println!("Magic!");
            42
        };

        pub(super) static ref BAR: std::sync::Mutex<()> = std::sync::Mutex::new(());
    }
}

// You can also modularize your magic statics like so:
mod baz {
    magic_static! {
        pub(super) static ref MAGIC: usize = {
            println!("Magic!");
            42
        };

        pub(super) static ref BAR: std::sync::Mutex<()> = std::sync::Mutex::new(());
    }

    #[magic_static::main(
        MAGIC,
        BAR
    )]
    // The `magic_statics!` macro (NOT `magic_static!`) can generate this function for you
    pub fn magic_static() {}
}

#[magic_static::main(
    foo::MAGIC,
    foo::BAR,
    mod baz // This will initialize all magic statics in `baz`
)]
fn main() {
    println!("Hello, world!");
}

Comparison to lazy_static

lazy_statics are initialized on first-use and are targetted towards multithreaded applications.

Every time a lazy_static is dereferenced, it must check whether it has been initialized yet. This is usually extremely cheap, and the resulting reference can be stored for use in hot loops (for example), but in some cases you may prefer no checks at all, i.e. a more lightweight solution.

magic_static only performs these checks in debug builds, making it a more ergonomic choice for single-threaded and performance-critical applications.

The downside of using magic_static is that you must manually initialize each magic_static in your main function or somewhere appropriate. See above for an example.

You might also like...
A program written in Rust, that allows the user to find the current location of the International Space Station and see it on a map.

ISS Location ViewFinder A program written in Rust, that allows the user to find the current location of the International Space Station and see it on

Soufflé is a variant of Datalog for tool designers crafting analyses in Horn clauses. Soufflé synthesizes a native parallel C++ program from a logic specification.

Welcome! This is the official repository for the Soufflé language project. The Soufflé language is similar to Datalog (but has terms known as records)

Noir Pay - Fork of the Light Protocol Program for local testing / optimisation.

Noir Pay v0 Built on Light Protocol Noir Pay will be directly built ontop of the Light Protocol SDK and provide users with a beautifully simple privat

Program a Raspberry Pi Pico with pure Rust

pi-pico-rs Program a Raspberry Pi Pico with pure Rust. Get Started Install the latest version of Rust and the thumbv6m-none-eabi target. This is the p

A simple program for handling Ethiopian calendar dates.

Mek’ut’erīya A simple program for handling Ethiopian calendar dates. Installation cargo install --git https://github.com/frectonz/mek-ut-er-ya If you

A bare metal STM32F103C8T6/STM32F103 MCU program written in pure Rust
A bare metal STM32F103C8T6/STM32F103 MCU program written in pure Rust

A bare metal (register level) STM32F103C8T6/STM32F103 MCU program written in pure Rust without any IDE, SDK, HAL or library, and no assembly code, the only tool required is the Rust compiler.

Rust program to monitor Windows 10 Registry keys for changes or modifications.

RegMon This Rust program monitors changes to multiple registry keys in Windows 10 and writes the changes to a text file. It also periodically sends a

An example repository on how to start building graph applications on streaming data. Just clone and start building 💻 💪
An example repository on how to start building graph applications on streaming data. Just clone and start building 💻 💪

An example repository on how to start building graph applications on streaming data. Just clone and start building 💻 💪

The Polkadot Hackathon Global Series North America edition is the second in a series of hackathons that brings the cutting edge of blockchain to a global community.

Polkadot Hackathon Project We are translating Uniswap v2 to Ink. Dependencies Install cargo-contract for building Ink contracts: cargo install dylint-

Statically allocated, runtime initialized cell.

static-cell Statically allocated, initialized at runtime cell. StaticCell provides a no-std-compatible, no-alloc way to reserve memory at compile time

A pure, low-level tensor program representation enabling tensor program optimization via program rewriting

Glenside is a pure, low-level tensor program representation which enables tensor program optimization via program rewriting, using rewriting frameworks such as the egg equality saturation library.

Isolates Jibri pods from their Deployment when they start recording or livestreaming, and cleans them up when they finish.

jibri-pod-controller: A tool for managing the scaling of large Jibri deployments in Kubernetes. When managing a large Jibri deployment, you usually wa

Distrod is a meta-distro for WSL 2 which runs Systemd as init process. You can run Ubuntu, Arch, and et.c with systemd in a minute. Distrod also has built-in auto-start feature on Windows startup and port forwarding abiltiy.
Distrod is a meta-distro for WSL 2 which runs Systemd as init process. You can run Ubuntu, Arch, and et.c with systemd in a minute. Distrod also has built-in auto-start feature on Windows startup and port forwarding abiltiy.

Distrod - WSL2 Distros with Systemd! Distrod is a systemd-based meta-distro for WSL2 that allows you to install Ubuntu, Arch Linux, Gentoo and many ot

A small utility that moves the start menu to the top-center of the screen in Windows 11.
A small utility that moves the start menu to the top-center of the screen in Windows 11.

TopCenterStart11 A small utility that moves the start menu to the top-center of the screen in Windows 11. As of right now, this application can only p

A place to start when building webgl apps in Bevy. Use this to avoid writing the boilerplate.

Template Bevy project with WebGL enabled Prerequisites cargo install cargo-make Build and serve WASM version Set your local ip address in Makefile.to

Stopwatch lib for rust. Start, pause, reset and lap like any stopwatch.

Chronometer Stopwatch lib for rust. Start, pause, reset and lap like any stopwatch. Nothing special I'm just learning rust. Getting Started Add this l

Start and stop system for applications to save your budget on hourly billing VPS.

Start and stop system (STT) Start and stop system for applications to save your budget on hourly billing VPS. Service A service consists of start/stop

A library to listen to global hotkeys in Rust

Rust Hotkey A library to listen to global hotkeys in Rust How to use See the examples folder for how to use this library. OS Support This lib aims to

Node/Electron library for global key listening.

GlobalKey Building cargo install nj-cli nj-cli build --release Calling from node npm i globalkey # or yarn add globalkey const globalkey = require(

Node/Electron library for global key listening.

GlobalKey Building cargo install nj-cli nj-cli build --release Calling from node npm i globalkey # or yarn add globalkey const globalkey = require(

Will 20 Dec 15, 2022
A partial actor pattern with a global orchestrator.

orchestra The orchestra pattern is a partial actor pattern, with a global orchestrator regarding relevant work items. proc-macro The proc macro provid

Parity Technologies 12 Dec 9, 2022
This crate allows you to safely initialize Dynamically Sized Types (DST) using only safe Rust.

This crate allows you to safely initialize Dynamically Sized Types (DST) using only safe Rust.

Christofer Nolander 11 Dec 22, 2022
Fast, initializable, and thread safe static variables

tagged_cell Fast, initializable, and thread safe static variables Overview Borrows the excellent ZST based tagging implementation (linked below) to gu

David Schwarz 8 Nov 10, 2022
untyped-arena provides an Arena allocator implementation that is safe and untyped with minimal complexity

untyped-arena untyped-arena provides an Arena allocator implementation that is safe and untyped with minimal complexity Usage let arena = Arena::new()

Max Bruce 1 Jan 9, 2022
Type-safe IPC for Tauri using GraphQL

Tauri Plugin graphql A plugin for Tauri that enables type-safe IPC through GraphQL. Install Rust [dependencies] tauri-plugin-graphql = "0.2" JavaScrip

Jonas Kruckenberg 40 Dec 29, 2022
A safe `Pin`-based intrusive doubly-linked list in Rust

pin-list This crate provides PinList, a safe Pin-based intrusive doubly linked list. Example A thread-safe unfair async mutex. use pin_project_lite::p

Sabrina Jewson 7 Oct 26, 2022
Waits until the exit code of a program is zero

Waitz A rust utility to wait that a program exits with 0. You need to wait for something to start up and don't know when it finishes?

Max Strübing 15 Apr 10, 2022
A program written in pure Rust to query music info from mpd and display it in a notification.

musinfo A program written in pure Rust to query music info from mpd and display it in a notification. Note: Cover art is expected to be placed at /tmp

Cpt.Howdy 10 Aug 16, 2022
Wait Service is a pure rust program to test and wait on the availability of a service.

Wait Service Wait Service is a pure rust program to test and wait on the availability of a service.

Magic Len (Ron Li) 3 Jan 18, 2022