Created
May 4, 2022 07:21
-
-
Save monadplus/3ccb050681e105739b9a9fb046d10deb to your computer and use it in GitHub Desktop.
Rust: hash_map!()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[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 | |
} | |
}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[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 | |
} | |
}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[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