Skip to content

Instantly share code, notes, and snippets.

@monadplus
Created May 4, 2022 07:21
Show Gist options
  • Save monadplus/3ccb050681e105739b9a9fb046d10deb to your computer and use it in GitHub Desktop.
Save monadplus/3ccb050681e105739b9a9fb046d10deb to your computer and use it in GitHub Desktop.
Rust: hash_map!()
#[macro_export]
macro_rules! hash_map {
($($key:expr => $val:expr),* ,) => (
$crate::hash_map!($($key => $val),*)
);
($($key:expr => $val:expr),*) => {
{
let mut dict = ::std::collections::HashMap::new();
$( dict.insert($key, $val); )*
dict
}
};
}
#[macro_export]
macro_rules! expr_count {
() => (0);
($e:expr) => (1);
($e:expr; $($other_e:expr);*) => ({
1 $(+ $crate::expr_count!($other_e) )*
});
($e:expr; $($other_e:expr);* ; ) => (
$crate::expr_count! { $e; $($other_e);* }
);
}
#[macro_export]
macro_rules! hash_map {
($($key:expr => $val:expr),* ,) => (
$crate::hash_map!($($key => $val),*)
);
($($key:expr => $val:expr),*) => {
{
let capacity = $crate::expr_count!($($key);*);
let mut dict = ::std::collections::HashMap::with_capacity(capacity);
$( dict.insert($key, $val); )*
dict
}
};
}
#[test]
fn hashmap_macro() {
let dict: HashMap<u64, u64> = hash_map!(0 => 0, 1 => 2);
assert_eq!(dict.get(&0u64), Some(&0u64));
assert_eq!(dict.get(&1u64), Some(&2u64));
let dict: HashMap<u64, u64> = hash_map!{
0 => 0,
1 => 2,
};
assert_eq!(dict.get(&0u64), Some(&0u64));
assert_eq!(dict.get(&1u64), Some(&2u64));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment