3 unstable releases

0.2.1 Jul 25, 2024
0.2.0 Jul 18, 2024
0.1.0 Jul 17, 2024

#448 in No standard library

Download history 207/week @ 2024-07-12 464/week @ 2024-07-19 804/week @ 2024-07-26 530/week @ 2024-08-02 263/week @ 2024-08-09 295/week @ 2024-08-16 309/week @ 2024-08-23 559/week @ 2024-08-30 728/week @ 2024-09-06 302/week @ 2024-09-13 396/week @ 2024-09-20 183/week @ 2024-09-27 493/week @ 2024-10-04 1236/week @ 2024-10-11

2,355 downloads per month

GPL-3.0-or-later OR Apache-2…

8KB
132 lines

lazyinit

Crates.io Docs.rs CI

Initialize a static value lazily.

Unlike lazy_static, which hardcodes the initialization routine in a macro, you can initialize the value in any way.

Examples

use lazyinit::LazyInit;

static VALUE: LazyInit<u32> = LazyInit::new();
assert!(!VALUE.is_inited());
// println!("{}", *VALUE); // panic: use uninitialized value
assert_eq!(VALUE.get(), None);

VALUE.init_once(233);
// VALUE.init_once(666); // panic: already initialized
assert!(VALUE.is_inited());
assert_eq!(*VALUE, 233);
assert_eq!(VALUE.get(), Some(&233));

Only one of the multiple initializations can succeed:

use lazyinit::LazyInit;
use std::time::Duration;

const N: usize = 16;
static VALUE: LazyInit<usize> = LazyInit::new();

let threads = (0..N)
    .map(|i| {
        std::thread::spawn(move || {
            std::thread::sleep(Duration::from_millis(10));
            VALUE.call_once(|| i)
        })
    })
    .collect::<Vec<_>>();

let mut ok = 0;
for (i, thread) in threads.into_iter().enumerate() {
    if thread.join().unwrap().is_some() {
        ok += 1;
        assert_eq!(*VALUE, i);
    }
}

assert_eq!(ok, 1);

No runtime deps