map/map.rs
1/// Create a new map collection and insert key-value pairs.
2///
3/// Example with tuple syntax:
4///
5/// ```
6/// # use ::map::*;
7/// let m = map!((1, 2), (3, 4));
8/// ```
9///
10/// Example with arrow syntax:
11///
12/// ```
13/// # use ::map::*;
14/// let m = map!(1 => 2, 3 => 4);
15/// ```
16///
17/// Example with multiple lines and tuple syntax:
18///
19/// ```
20/// # use ::map::*;
21/// let m = map!(
22/// (1, 2),
23/// (3, 4),
24/// );
25/// ```
26///
27/// Example with multiple lines and arrow syntax:
28///
29/// ```rust
30/// # use ::map::*;
31/// let m = map!(
32/// 1 => 2,
33/// 3 => 4,
34/// );
35/// ```
36///
37/// Equivalent Rust standard code:
38///
39/// ```
40/// # use std::collections::HashMap;
41/// let mut m = HashMap::new();
42/// m.insert(1, 2);
43/// m.insert(3, 4);
44/// ```
45///
46#[allow(unused_macros)]
47#[macro_export]
48macro_rules! map {
49 // tuple syntax
50 ( $(( $k:expr, $v:expr )),* $(,)?) => {
51 {
52 let mut m = ::std::collections::HashMap::new();
53 $(
54 m.insert($k, $v);
55 )*
56 m
57 }
58 };
59 // arrow syntax
60 ( $( $k:expr => $v:expr ),* $(,)?) => {
61 {
62 let mut m = ::std::collections::HashMap::new();
63 $(
64 m.insert($k, $v);
65 )*
66 m
67 }
68 };
69}
70
71#[cfg(test)]
72mod test {
73
74 mod tuple_syntax {
75
76 mod one_line {
77 use std::collections::HashMap;
78
79 #[test]
80 fn trailing_comma() {
81 let x = map!((1, 2), (3, 4),);
82 assert_eq!(x, HashMap::from([(1, 2), (3, 4)]));
83 }
84
85 #[test]
86 fn no_trailing_comma() {
87 let x = map!((1, 2), (3, 4));
88 assert_eq!(x, HashMap::from([(1, 2), (3, 4)]));
89 }
90 }
91
92 mod multiple_lines {
93 use std::collections::HashMap;
94
95 #[test]
96 fn trailing_comma() {
97 let x = map!(
98 (1, 2),
99 (3, 4),
100 );
101 assert_eq!(x, HashMap::from([(1, 2), (3, 4)]));
102 }
103
104 #[test]
105 fn no_trailing_comma() {
106 let x = map!(
107 (1, 2),
108 (3, 4)
109 );
110 assert_eq!(x, HashMap::from([(1, 2), (3, 4)]));
111 }
112 }
113 }
114
115 mod arrow_syntax {
116
117 mod one_line {
118 use std::collections::HashMap;
119
120 #[test]
121 fn trailing_comma() {
122 let x = map!(1 => 2, 3 => 4,);
123 assert_eq!(x, HashMap::from([(1, 2), (3, 4)]));
124 }
125
126 #[test]
127 fn no_trailing_comma() {
128 let x = map!(1 => 2, 3 => 4);
129 assert_eq!(x, HashMap::from([(1, 2), (3, 4)]));
130 }
131 }
132
133 mod multiple_lines {
134 use std::collections::HashMap;
135
136 #[test]
137 fn trailing_comma() {
138 let x = map!(
139 1 => 2,
140 3 => 4,
141 );
142 assert_eq!(x, HashMap::from([(1, 2), (3, 4)]));
143 }
144
145 #[test]
146 fn no_trailing_comma() {
147 let x = map!(
148 1 => 2,
149 3 => 4
150 );
151 assert_eq!(x, HashMap::from([(1, 2), (3, 4)]));
152 }
153 }
154 }
155
156}