lit2 1.0.9

Collection helper libraries and “literal” macros for HashMap, HashSet, BTreeMap, and BTreeSet.
Documentation
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
#![warn(missing_docs)]
#![warn(unused_results)]
#![doc(html_root_url="https://docs.rs/lit2/1/")]

//! Macros for container literals with specific type.
//!
//! ```
//! use lit2::*;
//!
//! # fn main() {
//! let map = hashmap!{
//!     "a" => 1,
//!     "b" => 2,
//! };
//! 
//! let set = set!{1, 2, 3};
//! # }
//! ```
//!
//! The **lit2** crate uses `=>` syntax to separate the key and value for the
//! mapping macros. It is also possible to use the `:` separator, but the keys cannot
//! be expressions.
//!
//! Note that rust macros are flexible in which brackets you use for the invocation.
//! You can use them as `hashmap!{}` or `hashmap![]` or `hashmap!()`.
//!
//! Generic container macros already exist elsewhere, so those are not provided
//! here at the moment.

#[macro_export(local_inner_macros)]
/// Create a **HashMap** from a list of key-value pairs
///
/// ## Example
///
/// ```
/// use lit2::*;
/// # 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);
            $(
                let _ = _map.insert($key, $value);
            )*
            _map
        }
    };
}

#[macro_export(local_inner_macros)]
/// Create a **HashMap** with `specific type` from a list of key-value pairs
///
/// ## Example
///
/// ```
/// use maplit::*;
/// use std::collections::HashMap;
/// struct Foo;
/// struct Bar;
///
/// trait Zoo {}
///
/// impl Zoo for Foo {}
/// impl Zoo for Bar {}
///
/// # fn main() {
/// let map = hashmap_ex!(
///     HashMap<_, Box<dyn Zoo>>,
///     {
///         "a" => Box::new(Foo {}),
///         "b" => Box::new(Bar {}),
///     }
/// );
/// # }
/// ```
macro_rules! hashmap_ex {
    (@single $($x:tt)*) => (());
    (@count $($rest:expr),*) => (<[()]>::len(&[$(hashmap_ex!(@single $rest)),*]));

    ($t:ty, { $($key:expr => $value:expr,)+ } ) => { hashmap_ex!($t, { $($key => $value),+ }) };
    ($t:ty, { $($key:expr => $value:expr),* } ) => {
        {
            let _cap = hashmap_ex!(@count $($key),*);
            let mut _map: $t = ::std::collections::HashMap::with_capacity(_cap);
            $(
                let _ = _map.insert($key, $value);
            )*
            _map
        }
    };
}

#[macro_export(local_inner_macros)]
/// A slightly more concise version of "hashmap!" for the concision-minded. Create a **HashMap** from a list of key-value pairs
///
/// ## Example
///
/// ```
/// use lit2::*;
/// # fn main() {
///
/// let map = map!{
///     "a": 1,
///     "b": 2,
/// };
/// assert_eq!(map["a"], 1);
/// assert_eq!(map["b"], 2);
/// assert_eq!(map.get("c"), None);
/// # }
/// ```
macro_rules! map{
    ( $($key:tt : $val:expr),* $(,)? ) =>{{
        #[allow(unused_mut)]
        let mut map = ::std::collections::HashMap::with_capacity(hashmap!(@count $($key),* ));
        $(
            #[allow(unused_parens)]
            let _ = map.insert($key, $val);
        )*
        map
    }};
    (@replace $_t:tt $e:expr ) => { $e };
    (@count $($t:tt)*) => { <[()]>::len(&[$( map!(@replace $t ()) ),*]) }
}

#[macro_export(local_inner_macros)]
/// Alias of "map!". Create a **HashMap** from a list of key-value pairs
///
/// ## Example
///
/// ```
/// use lit2::*;
/// # fn main() {
///
/// let map = dict!{
///     "a": 1,
///     "b": 2,
/// };
/// assert_eq!(map["a"], 1);
/// assert_eq!(map["b"], 2);
/// assert_eq!(map.get("c"), None);
/// # }
/// ```
macro_rules! dict{
    ( $($key:tt : $val:expr),* $(,)? ) =>{{
        #[allow(unused_mut)]
        let mut map = ::std::collections::HashMap::with_capacity(hashmap!(@count $($key),* ));
        $(
            #[allow(unused_parens)]
            let _ = map.insert($key, $val);
        )*
        map
    }};
    (@replace $_t:tt $e:expr ) => { $e };
    (@count $($t:tt)*) => { <[()]>::len(&[$( map!(@replace $t ()) ),*]) }
}

/// Create a **HashSet** from a list of elements.
///
/// ## Example
///
/// ```
/// use lit2::*;
/// # fn main() {
///
/// let set = hashset!{"a", "b"};
/// assert!(set.contains("a"));
/// assert!(set.contains("b"));
/// assert!(!set.contains("c"));
/// # }
/// ```
#[macro_export(local_inner_macros)]
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);
            $(
                let _ = _set.insert($key);
            )*
            _set
        }
    };
}

/// Alias of "hashset!". Create a **HashSet** from a list of elements.
///
/// ## Example
///
/// ```
/// use lit2::*;
/// # fn main() {
///
/// let set = set!{"a", "b"};
/// assert!(set.contains("a"));
/// assert!(set.contains("b"));
/// assert!(!set.contains("c"));
/// # }
/// ```
#[macro_export(local_inner_macros)]
macro_rules! set {
    (@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);
            $(
                let _ = _set.insert($key);
            )*
            _set
        }
    };
}

#[macro_export(local_inner_macros)]
/// Create a **BTreeMap** from a list of key-value pairs
///
/// ## Example
///
/// ```
/// use lit2::*;
/// # 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();
            $(
                let _ = _map.insert($key, $value);
            )*
            _map
        }
    };
}

#[macro_export(local_inner_macros)]
/// Create a **BTreeSet** from a list of elements.
///
/// ## Example
///
/// ```
/// use lit2::*;
/// # 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 lit2
/// 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 lit2 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
///
/// **Note** To use `convert_args`, the macro that is being wrapped
/// must itself be brought into the current scope with `#[macro_use]` or `use`.
///
/// # Examples
///
/// ```
/// use lit2::*;
/// # 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 lit2 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(local_inner_macros)]
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_hashmap_ex() {
    use std::collections::HashMap;
    let names: HashMap<i32, &str> = hashmap_ex!{
        HashMap<i32, &str>,
        {
            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_ex!{
        HashMap<i32, i32>, {}
    };
    assert_eq!(empty.len(), 0);

    let _nested_compiles = hashmap_ex!{
        HashMap<i32, _>,
        {
            1 => hashmap!{0 => 1 + 2,},
            2 => hashmap!{1 => 1,},
        }
    };

    struct Foo(i32);
    struct Bar(i32);

    trait Ret {
        fn ret(&self) -> i32;
    }

    impl Ret for Foo {
        fn ret(&self) -> i32 { self.0 }
    }
    impl Ret for Bar {
        fn ret(&self) -> i32 { self.0 }
    }

    let func_map = hashmap_ex!(
        HashMap<_, Box<dyn Ret>>,
        {
            "foo" => Box::new(Foo(1)),
            "bar" => Box::new(Bar(2)),
        }
    );

    assert_eq!(func_map["foo"].ret(), 1);
    assert_eq!(func_map["bar"].ret(), 2);
}

#[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,},
    };
}