1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#[macro_export]
macro_rules! hash_map {
    () => { std::collections::HashMap::with_capacity(16) };

    ($key: expr => $value: expr) => {
        // follow Java's HashMap.
        hash_map!($key => $value; 16)
    };
    ($key: expr => $value: expr; $init_capacity: expr) => {
        {
            let mut hash_map = std::collections::HashMap::with_capacity($init_capacity);
            hash_map.insert($key, $value);
            hash_map
        }
    };

    ($($key: expr => $value: expr),*) => {
        vec![$(($key, $value)),*].into_iter().collect::<std::collections::HashMap<_, _>>()
    };
    ($($key: expr => $value: expr,)*) => {
        hash_map!($($key => $value),*)
    };
}

#[cfg(test)]
mod test {
    use std::collections::HashMap;

    #[test]
    fn test_hash_map_macro_without_params() {
        let expected: HashMap<i32, i32> = HashMap::with_capacity(16);
        let product: HashMap<i32, i32> = hash_map!();
        assert_eq!(expected, product);
    }

    #[test]
    fn test_hash_map_macro_with_one_param() {
        let mut expected = HashMap::with_capacity(16);
        expected.insert("hello", "world");
        let product = hash_map!("hello" => "world");
        assert_eq!(expected, product);
    }

    #[test]
    fn test_hash_map_macro_with_capacity() {
        let mut expected = HashMap::with_capacity(20);
        expected.insert("hello", "world");
        let product = hash_map!("hello" => "world"; 20);
        assert_eq!(expected, product);
    }

    #[test]
    fn test_hash_map_macro_with_any_params() {
        let mut expected = HashMap::with_capacity(16);
        expected.insert("hello", "world");
        expected.insert("world", "hello");
        let product = hash_map! {
            "hello" => "world",
            "world" => "hello",
        };
        assert_eq!(expected, product);
    }

    #[test]
    fn test_hash_map_macro_with_any_params_and_without_trailing_comma() {
        let mut expected = HashMap::with_capacity(16);
        expected.insert("hello", "world");
        expected.insert("world", "hello");
        let product = hash_map! {
            "hello" => "world",
            "world" => "hello"
        };
        assert_eq!(expected, product);
    }
}