Skip to content

Instantly share code, notes, and snippets.

@skull-squadron
Created May 30, 2024 05:40
Show Gist options
  • Save skull-squadron/e6a684892857518b8fa4655c10d10095 to your computer and use it in GitHub Desktop.
Save skull-squadron/e6a684892857518b8fa4655c10d10095 to your computer and use it in GitHub Desktop.
new_lazy_static
#[macro_export]
macro_rules! new_lazy_static {
($(#[$a:meta])* $v:vis fn $i:ident() -> &$t:ty $b:block $($rest:tt)*) => {
__new_lazy_static_inner!($(#[$a])*, $v, $i, Box<&$t>, $t, Box::new($b));
new_lazy_static!($($rest)*);
};
($(#[$a:meta])* $v:vis fn $i:ident() -> $t:ty $b:block $($rest:tt)*) => {
__new_lazy_static_inner!($(#[$a])*, $v, $i, $t, $t, $b);
new_lazy_static!($($rest)*);
};
() => ()
}
macro_rules! __new_lazy_static_inner {
($(#[$a:meta])*, $v:vis, $i:ident, $ot:ty, $t:ty, $($b:tt)+) => {
$(#[$a])*
$v fn $i() -> &'static $t {
static VALUE: std::sync::OnceLock<$ot> = std::sync::OnceLock::new();
VALUE.get_or_init(|| $($b)+)
}
}
}
#[cfg(test)]
mod test {
#[test]
fn one_val_works() {
new_lazy_static! {
fn hi() -> i8 {
10
}
}
assert_eq!(hi(), &10_i8);
assert_eq!(hi(), &10_i8);
}
#[test]
fn one_str_works() {
new_lazy_static! {
fn food() -> &str {
"yummy"
}
}
assert_eq!(food(), "yummy");
assert_eq!(food(), "yummy");
}
#[test]
fn two_works() {
new_lazy_static! {
fn food() -> &str {
"yummy"
}
fn hi() -> i8 {
10
}
}
assert_eq!(hi(), &10_i8);
assert_eq!(hi(), &10_i8);
assert_eq!(food(), "yummy");
assert_eq!(food(), "yummy");
}
#[test]
fn hashmap_works() {
new_lazy_static! {
fn magic() -> std::collections::HashMap<usize, usize> {
[(2, 3), (4, 5)].into()
}
}
let res = [(2, 3), (4, 5)].into();
assert_eq!(magic(), &res);
assert_eq!(magic(), &res);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment