maplit/lib.rs
1#![warn(missing_docs)]
2#![warn(unused_results)]
3#![doc(html_root_url="https://docs.rs/maplit/1/")]
4
5//! Macros for container literals with specific type.
6//!
7//! ```
8//! #[macro_use] extern crate maplit;
9//!
10//! # fn main() {
11//! let map = hashmap!{
12//! "a" => 1,
13//! "b" => 2,
14//! };
15//! # }
16//! ```
17//!
18//! The **maplit** crate uses `=>` syntax to separate the key and value for the
19//! mapping macros. (It was not possible to use `:` as separator due to syntactic
20//! restrictions in regular `macro_rules!` macros.)
21//!
22//! Note that rust macros are flexible in which brackets you use for the invocation.
23//! You can use them as `hashmap!{}` or `hashmap![]` or `hashmap!()`.
24//!
25//! Generic container macros already exist elsewhere, so those are not provided
26//! here at the moment.
27
28#[macro_export]
29/// Create a **HashMap** from a list of key-value pairs
30///
31/// ## Example
32///
33/// ```
34/// #[macro_use] extern crate maplit;
35/// # fn main() {
36///
37/// let map = hashmap!{
38/// "a" => 1,
39/// "b" => 2,
40/// };
41/// assert_eq!(map["a"], 1);
42/// assert_eq!(map["b"], 2);
43/// assert_eq!(map.get("c"), None);
44/// # }
45/// ```
46macro_rules! hashmap {
47 (@single $($x:tt)*) => (());
48 (@count $($rest:expr),*) => (<[()]>::len(&[$(hashmap!(@single $rest)),*]));
49
50 ($($key:expr => $value:expr,)+) => { hashmap!($($key => $value),+) };
51 ($($key:expr => $value:expr),*) => {
52 {
53 let _cap = hashmap!(@count $($key),*);
54 let mut _map = ::std::collections::HashMap::with_capacity(_cap);
55 $(
56 let _ = _map.insert($key, $value);
57 )*
58 _map
59 }
60 };
61}
62
63/// Create a **HashSet** from a list of elements.
64///
65/// ## Example
66///
67/// ```
68/// #[macro_use] extern crate maplit;
69/// # fn main() {
70///
71/// let set = hashset!{"a", "b"};
72/// assert!(set.contains("a"));
73/// assert!(set.contains("b"));
74/// assert!(!set.contains("c"));
75/// # }
76/// ```
77#[macro_export]
78macro_rules! hashset {
79 (@single $($x:tt)*) => (());
80 (@count $($rest:expr),*) => (<[()]>::len(&[$(hashset!(@single $rest)),*]));
81
82 ($($key:expr,)+) => { hashset!($($key),+) };
83 ($($key:expr),*) => {
84 {
85 let _cap = hashset!(@count $($key),*);
86 let mut _set = ::std::collections::HashSet::with_capacity(_cap);
87 $(
88 let _ = _set.insert($key);
89 )*
90 _set
91 }
92 };
93}
94
95#[macro_export]
96/// Create a **BTreeMap** from a list of key-value pairs
97///
98/// ## Example
99///
100/// ```
101/// #[macro_use] extern crate maplit;
102/// # fn main() {
103///
104/// let map = btreemap!{
105/// "a" => 1,
106/// "b" => 2,
107/// };
108/// assert_eq!(map["a"], 1);
109/// assert_eq!(map["b"], 2);
110/// assert_eq!(map.get("c"), None);
111/// # }
112/// ```
113macro_rules! btreemap {
114 // trailing comma case
115 ($($key:expr => $value:expr,)+) => (btreemap!($($key => $value),+));
116
117 ( $($key:expr => $value:expr),* ) => {
118 {
119 let mut _map = ::std::collections::BTreeMap::new();
120 $(
121 let _ = _map.insert($key, $value);
122 )*
123 _map
124 }
125 };
126}
127
128#[macro_export]
129/// Create a **BTreeSet** from a list of elements.
130///
131/// ## Example
132///
133/// ```
134/// #[macro_use] extern crate maplit;
135/// # fn main() {
136///
137/// let set = btreeset!{"a", "b"};
138/// assert!(set.contains("a"));
139/// assert!(set.contains("b"));
140/// assert!(!set.contains("c"));
141/// # }
142/// ```
143macro_rules! btreeset {
144 ($($key:expr,)+) => (btreeset!($($key),+));
145
146 ( $($key:expr),* ) => {
147 {
148 let mut _set = ::std::collections::BTreeSet::new();
149 $(
150 _set.insert($key);
151 )*
152 _set
153 }
154 };
155}
156
157/// Identity function. Used as the fallback for conversion.
158#[doc(hidden)]
159pub fn __id<T>(t: T) -> T { t }
160
161/// Macro that converts the keys or key-value pairs passed to another maplit
162/// macro. The default conversion is to use the [`Into`] trait, if no
163/// custom conversion is passed.
164///
165/// The syntax is:
166///
167/// `convert_args!(` `keys=` *function* `,` `values=` *function* `,`
168/// *macro_name* `!(` [ *key* => *value* [, *key* => *value* ... ] ] `))`
169///
170/// Here *macro_name* is any other maplit macro and either or both of the
171/// explicit `keys=` and `values=` parameters can be omitted.
172///
173/// [`Into`]: https://doc.rust-lang.org/std/convert/trait.Into.html
174///
175///
176/// # Examples
177///
178/// ```
179/// #[macro_use] extern crate maplit;
180/// # fn main() {
181///
182/// use std::collections::HashMap;
183/// use std::collections::BTreeSet;
184///
185/// // a. Use the default conversion with the Into trait.
186/// // Here this converts both the key and value string literals to `String`,
187/// // but we need to specify the map type exactly!
188///
189/// let map1: HashMap<String, String> = convert_args!(hashmap!(
190/// "a" => "b",
191/// "c" => "d",
192/// ));
193///
194/// // b. Specify an explicit custom conversion for the keys. If we don't specify
195/// // a conversion for the values, they are not converted at all.
196///
197/// let map2 = convert_args!(keys=String::from, hashmap!(
198/// "a" => 1,
199/// "c" => 2,
200/// ));
201///
202/// // Note: map2 is a HashMap<String, i32>, but we didn't need to specify the type
203/// let _: HashMap<String, i32> = map2;
204///
205/// // c. convert_args! works with all the maplit macros -- and macros from other
206/// // crates that have the same "signature".
207/// // For example, btreeset and conversion from &str to Vec<u8>.
208///
209/// let set: BTreeSet<Vec<u8>> = convert_args!(btreeset!(
210/// "a", "b", "c", "d", "a", "e", "f",
211/// ));
212/// assert_eq!(set.len(), 6);
213///
214///
215/// # }
216/// ```
217#[macro_export]
218macro_rules! convert_args {
219 (keys=$kf:expr, $macro_name:ident !($($k:expr),* $(,)*)) => {
220 $macro_name! { $(($kf)($k)),* }
221 };
222 (keys=$kf:expr, values=$vf:expr, $macro_name:ident !($($k:expr),* $(,)*)) => {
223 $macro_name! { $(($kf)($k)),* }
224 };
225 (keys=$kf:expr, values=$vf:expr, $macro_name:ident !( $($k:expr => $v:expr),* $(,)*)) => {
226 $macro_name! { $(($kf)($k) => ($vf)($v)),* }
227 };
228 (keys=$kf:expr, $macro_name:ident !($($rest:tt)*)) => {
229 convert_args! {
230 keys=$kf, values=$crate::__id,
231 $macro_name !(
232 $($rest)*
233 )
234 }
235 };
236 (values=$vf:expr, $macro_name:ident !($($rest:tt)*)) => {
237 convert_args! {
238 keys=$crate::__id, values=$vf,
239 $macro_name !(
240 $($rest)*
241 )
242 }
243 };
244 ($macro_name:ident ! $($rest:tt)*) => {
245 convert_args! {
246 keys=::std::convert::Into::into, values=::std::convert::Into::into,
247 $macro_name !
248 $($rest)*
249 }
250 };
251}
252
253#[test]
254fn test_hashmap() {
255 use std::collections::HashMap;
256 use std::collections::HashSet;
257 let names = hashmap!{
258 1 => "one",
259 2 => "two",
260 };
261 assert_eq!(names.len(), 2);
262 assert_eq!(names[&1], "one");
263 assert_eq!(names[&2], "two");
264 assert_eq!(names.get(&3), None);
265
266 let empty: HashMap<i32, i32> = hashmap!{};
267 assert_eq!(empty.len(), 0);
268
269 let _nested_compiles = hashmap!{
270 1 => hashmap!{0 => 1 + 2,},
271 2 => hashmap!{1 => 1,},
272 };
273
274 let _: HashMap<String, i32> = convert_args!(keys=String::from, hashmap!(
275 "one" => 1,
276 "two" => 2,
277 ));
278
279 let _: HashMap<String, i32> = convert_args!(keys=String::from, values=__id, hashmap!(
280 "one" => 1,
281 "two" => 2,
282 ));
283
284 let names: HashSet<String> = convert_args!(hashset!(
285 "one",
286 "two",
287 ));
288 assert!(names.contains("one"));
289 assert!(names.contains("two"));
290
291 let lengths: HashSet<usize> = convert_args!(keys=str::len, hashset!(
292 "one",
293 "two",
294 ));
295 assert_eq!(lengths.len(), 1);
296
297 let _no_trailing: HashSet<usize> = convert_args!(keys=str::len, hashset!(
298 "one",
299 "two"
300 ));
301}
302
303#[test]
304fn test_btreemap() {
305 use std::collections::BTreeMap;
306 let names = btreemap!{
307 1 => "one",
308 2 => "two",
309 };
310 assert_eq!(names.len(), 2);
311 assert_eq!(names[&1], "one");
312 assert_eq!(names[&2], "two");
313 assert_eq!(names.get(&3), None);
314
315 let empty: BTreeMap<i32, i32> = btreemap!{};
316 assert_eq!(empty.len(), 0);
317
318 let _nested_compiles = btreemap!{
319 1 => btreemap!{0 => 1 + 2,},
320 2 => btreemap!{1 => 1,},
321 };
322}