#init #initialization #hook #one-time

init-hook

Guaranteed one-time initialization

2 stable releases

Uses new Rust 2024

new 2.0.0 Mar 19, 2025
1.0.0 Mar 19, 2025

#6 in #one-time

Download history 132/week @ 2025-03-14

132 downloads per month

MIT/Apache

10KB
54 lines

License License Cargo Documentation

Init Hook

This crate allows registering functions for guaranteed initialization during main

Example

use std::sync::atomic::{AtomicUsize, Ordering};
static COUNTER: AtomicUsize = AtomicUsize::new(0);

// Register function to be called exactly once during init
#[init_hook::call_on_init]
fn init_once() {
    COUNTER.fetch_add(1, Ordering::Release);
}

// Registered functions can also be unsafe
#[init_hook::call_on_init]
unsafe fn init_once_unchecked() {
    COUNTER.fetch_add(1, Ordering::Release);
}

fn main() {
    // This is enforced by a pre-main assertion to always be included exactly once
    init_hook::init!();
    assert_eq!(COUNTER.load(Ordering::Acquire), 2);
}

Platform support

Linux macOS Windows FreeBSD OpenBSD illumos Other
💚 💚 💚 💚 💚 💚

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~0.6–1MB
~23K SLoC