vecmap/
macros.rs

1/// Create an `VecMap` from a list of key-value pairs
2///
3/// ## Example
4///
5/// ```
6/// use vecmap::vecmap;
7///
8/// let map = vecmap!{
9///     "a" => 1,
10///     "b" => 2,
11/// };
12/// assert_eq!(map["a"], 1);
13/// assert_eq!(map["b"], 2);
14/// assert_eq!(map.get("c"), None);
15///
16/// // "a" is the first key
17/// assert_eq!(map.keys().next(), Some(&"a"));
18/// ```
19#[macro_export]
20macro_rules! vecmap {
21    ($($key:expr => $value:expr,)+) => { $crate::vecmap!($($key => $value),+) };
22    ($($key:expr => $value:expr),*) => {
23        {
24            // Note: `stringify!($key)` is just here to consume the repetition,
25            // but we throw away that string literal during constant evaluation.
26            const CAP: usize = <[()]>::len(&[$({ stringify!($key); }),*]);
27            let mut map = $crate::VecMap::with_capacity(CAP);
28            $(
29                map.insert($key, $value);
30            )*
31            map
32        }
33    };
34}
35
36/// Create an `VecSet` from a list of values
37///
38/// ## Example
39///
40/// ```
41/// use vecmap::vecset;
42///
43/// let set = vecset!{"a", "b"};
44/// assert!(set.contains("a"));
45/// assert!(set.contains("b"));
46/// assert!(!set.contains("c"));
47///
48/// // "a" is the first value
49/// assert_eq!(set.iter().next(), Some(&"a"));
50/// ```
51#[macro_export]
52macro_rules! vecset {
53    ($($value:expr,)+) => { $crate::vecset!($($value),+) };
54    ($($value:expr),*) => {
55        {
56            // Note: `stringify!($key)` is just here to consume the repetition,
57            // but we throw away that string literal during constant evaluation.
58            const CAP: usize = <[()]>::len(&[$({ stringify!($value); }),*]);
59            let mut set = $crate::VecSet::with_capacity(CAP);
60            $(
61                set.insert($value);
62            )*
63            set
64        }
65    };
66}