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
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
#![warn(missing_docs)]
#![doc(html_root_url="https://docs.rs/maplit/")]

//! Macros for container literals with specific type.
//! 
//! ```
//! #[macro_use] extern crate maplit;
//!
//! # fn main() {
//! let map = hashmap!{
//!     "a" => 1,
//!     "b" => 2,
//! };
//! # }
//! ```
//!
//! The **maplit** crate uses `=>` syntax for the mapping macros. It is
//! not possible to use `:` as separator due to syntactic restrictions in
//! regular `macro_rules!` macros.
//!
//! Note that rust macros are flexible in which brackets you use for the invocation.
//! You can use them as `hashmap!{}` or `hashmap![]` or `hashmap!()`.
//! This crate suggests `{}` as the convention for the map & set macros,
//! it matches their `Debug` output.
//!
//! Generic container macros already exist elsewhere, so those are not provided
//! here at the moment.

#[macro_export]
/// Create a **HashMap** from a list of key-value pairs
///
/// ## Example
///
/// ```
/// #[macro_use] extern crate maplit;
/// # fn main() {
///
/// let map = hashmap!{
///     "a" => 1,
///     "b" => 2,
/// };
/// assert_eq!(map["a"], 1);
/// assert_eq!(map["b"], 2);
/// assert_eq!(map.get("c"), None);
/// # }
/// ```
macro_rules! hashmap {
    (@single $($x:tt)*) => (());
    (@count $($rest:expr),*) => (<[()]>::len(&[$(hashmap!(@single $rest)),*]));
    
    ($($key:expr => $value:expr,)+) => { hashmap!($($key => $value),+) };
    ($($key:expr => $value:expr),*) => {
        {
            let _cap = hashmap!(@count $($key),*);
            let mut _map = ::std::collections::HashMap::with_capacity(_cap);
            $(
                _map.insert($key, $value);
            )*
            _map
        }
    };
}

/// Create a **HashSet** from a list of elements.
///
/// ## Example
///
/// ```
/// #[macro_use] extern crate maplit;
/// # fn main() {
///
/// let set = hashset!{"a", "b"};
/// assert!(set.contains("a"));
/// assert!(set.contains("b"));
/// assert!(!set.contains("c"));
/// # }
/// ```
#[macro_export]
macro_rules! hashset {
    (@single $($x:tt)*) => (());
    (@count $($rest:expr),*) => (<[()]>::len(&[$(hashset!(@single $rest)),*]));
    
    ($($key:expr,)+) => { hashset!($($key),+) };
    ($($key:expr),*) => {
        {
            let _cap = hashset!(@count $($key),*);
            let mut _set = ::std::collections::HashSet::with_capacity(_cap);
            $(
                _set.insert($key);
            )*
            _set
        }
    };
}

#[macro_export]
/// Create a **BTreeMap** from a list of key-value pairs
///
/// ## Example
///
/// ```
/// #[macro_use] extern crate maplit;
/// # fn main() {
///
/// let map = btreemap!{
///     "a" => 1,
///     "b" => 2,
/// };
/// assert_eq!(map["a"], 1);
/// assert_eq!(map["b"], 2);
/// assert_eq!(map.get("c"), None);
/// # }
/// ```
macro_rules! btreemap {
    // trailing comma case
    ($($key:expr => $value:expr,)+) => (btreemap!($($key => $value),+));
    
    ( $($key:expr => $value:expr),* ) => {
        {
            let mut _map = ::std::collections::BTreeMap::new();
            $(
                _map.insert($key, $value);
            )*
            _map
        }
    };
}

#[macro_export]
/// Create a **BTreeSet** from a list of elements.
///
/// ## Example
///
/// ```
/// #[macro_use] extern crate maplit;
/// # fn main() {
///
/// let set = btreeset!{"a", "b"};
/// assert!(set.contains("a"));
/// assert!(set.contains("b"));
/// assert!(!set.contains("c"));
/// # }
/// ```
macro_rules! btreeset {
    ($($key:expr,)+) => (btreeset!($($key),+));
    
    ( $($key:expr),* ) => {
        {
            let mut _set = ::std::collections::BTreeSet::new();
            $(
                _set.insert($key);
            )*
            _set
        }
    };
}

/// Identity function. Used as the fallback for conversion.
#[doc(hidden)]
pub fn __id<T>(t: T) -> T { t }

/// Macro that converts the keys or key-value pairs passed to another maplit
/// macro. The default conversion is to use the [`Into`] trait, if no
/// custom conversion is passed.
///
/// The syntax is:
///
/// `convert_args!(` `keys=` *function* `,` `values=` *function* `,`
///     *macro_name* `!(` [ *key* => *value* [, *key* => *value* ... ] ] `))`
/// 
/// Here *macro_name* is any other maplit macro and either or both of the
/// explicit `keys=` and `values=` parameters can be omitted.
///
/// [`Into`]: https://doc.rust-lang.org/std/convert/trait.Into.html
///
///
/// # Examples
///
/// ```
/// #[macro_use] extern crate maplit;
/// # fn main() {
///
/// use std::collections::HashMap;
/// use std::collections::BTreeSet;
///
/// // a. Use the default conversion with the Into trait.
/// // Here this converts both the key and value string literals to `String`,
/// // but we need to specify the map type exactly!
///
/// let map1: HashMap<String, String> = convert_args!(hashmap!(
///     "a" => "b",
///     "c" => "d",
/// ));
///
/// // b. Specify an explicit custom conversion for the keys. If we don't specify
/// // a conversion for the values, they are not converted at all.
///
/// let map2 = convert_args!(keys=String::from, hashmap!(
///     "a" => 1,
///     "c" => 2,
/// ));
///
/// // Note: map2 is a HashMap<String, i32>, but we didn't need to specify the type
/// let _: HashMap<String, i32> = map2;
///
/// // c. convert_args! works with all the maplit macros -- and macros from other
/// // crates that have the same "signature".
/// // For example, btreeset and conversion from &str to Vec<u8>.
///
/// let set: BTreeSet<Vec<u8>> = convert_args!(btreeset!(
///     "a", "b", "c", "d", "a", "e", "f",
/// ));
/// assert_eq!(set.len(), 6);
///
///
/// # }
/// ```
#[macro_export]
macro_rules! convert_args {
    (keys=$kf:expr, $macro_name:ident !($($k:expr),* $(,)*)) => {
        $macro_name! { $(($kf)($k)),* }
    };
    (keys=$kf:expr, values=$vf:expr, $macro_name:ident !($($k:expr),* $(,)*)) => {
        $macro_name! { $(($kf)($k)),* }
    };
    (keys=$kf:expr, values=$vf:expr, $macro_name:ident !( $($k:expr => $v:expr),* $(,)*)) => {
        $macro_name! { $(($kf)($k) => ($vf)($v)),* }
    };
    (keys=$kf:expr, $macro_name:ident !($($rest:tt)*)) => {
        convert_args! {
            keys=$kf, values=$crate::__id,
            $macro_name !(
                $($rest)*
            )
        }
    };
    (values=$vf:expr, $macro_name:ident !($($rest:tt)*)) => {
        convert_args! {
            keys=$crate::__id, values=$vf,
            $macro_name !(
                $($rest)*
            )
        }
    };
    ($macro_name:ident ! $($rest:tt)*) => {
        convert_args! {
            keys=::std::convert::Into::into, values=::std::convert::Into::into,
            $macro_name !
            $($rest)*
        }
    };
}

#[test]
fn test_hashmap() {
    use std::collections::HashMap;
    use std::collections::HashSet;
    let names = hashmap!{
        1 => "one",
        2 => "two",
    };
    assert_eq!(names.len(), 2);
    assert_eq!(names[&1], "one");
    assert_eq!(names[&2], "two");
    assert_eq!(names.get(&3), None);
    
    let empty: HashMap<i32, i32> = hashmap!{};
    assert_eq!(empty.len(), 0);

    let _nested_compiles = hashmap!{
        1 => hashmap!{0 => 1 + 2,},
        2 => hashmap!{1 => 1,},
    };

    let _: HashMap<String, i32> = convert_args!(keys=String::from, hashmap!(
        "one" => 1,
        "two" => 2,
    ));

    let _: HashMap<String, i32> = convert_args!(keys=String::from, values=__id, hashmap!(
        "one" => 1,
        "two" => 2,
    ));

    let names: HashSet<String> = convert_args!(hashset!(
        "one",
        "two",
    ));
    assert!(names.contains("one"));
    assert!(names.contains("two"));

    let lengths: HashSet<usize> = convert_args!(keys=str::len, hashset!(
        "one",
        "two",
    ));
    assert_eq!(lengths.len(), 1);

    let _no_trailing: HashSet<usize> = convert_args!(keys=str::len, hashset!(
        "one",
        "two"
    ));
}

#[test]
fn test_btreemap() {
    use std::collections::BTreeMap;
    let names = btreemap!{
        1 => "one",
        2 => "two",
    };
    assert_eq!(names.len(), 2);
    assert_eq!(names[&1], "one");
    assert_eq!(names[&2], "two");
    assert_eq!(names.get(&3), None);
    
    let empty: BTreeMap<i32, i32> = btreemap!{};
    assert_eq!(empty.len(), 0);

    let _nested_compiles = btreemap!{
        1 => btreemap!{0 => 1 + 2,},
        2 => btreemap!{1 => 1,},
    };
}