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
#![deny(rustdoc::broken_intra_doc_links)]
#![deny(unused)]

//! # More Collection Macros
//!
//! This library provides a set of useful macros for creating [std collections], similar to the
//! default `vec!` macro
//!
//! [std collections]: std::collections
//!
//! # Comprehension
//!
//! These macros enable list/map comprehension similar to what's present in python.
//! For example, the following python code
//! ```python
//! list = [x*x for x in range(0,10)]
//! dict = {x : x*x for x in range(0,10)}
//! ```
//! is equivalent to the following rust code
//! ```rust
//! # #[macro_use] extern crate more_collection_macros;
//!
//! let list = list![x*x; x in 0..10];
//! let dict = map!{x => x*x; x in 0..10};
//! ```
//!
//! # Namespace-like
//!
//! With maps, you can also use identifiers as keys, which are then converted to `&'static str` keys.
//! ```
//! # #[macro_use] extern crate more_collection_macros;
//! map!{
//!     field1: 0,
//!     field2: 1
//! };
//! ```
//! You can't repeat fields with those notation. The following will give a _runtime_ error.
//! ```should_panic
//! # #[macro_use] extern crate more_collection_macros;
//! map!{
//!     field1: 0,
//!     field1: 1
//! };
//! ```


/// Create a map. Can either provide a function-like dictionary comprehension, or provide a list of
/// tuples containing a key and value to create a map.
///
/// Can use identifiers as keys, which are converted to [Strings](std::string::String)
///
/// # Example
/// ```
/// # #[macro_use] extern crate more_collection_macros;
/// # use std::collections::HashMap;
/// let dict: HashMap<&str, u32> = map! {
///     field: 15,
///     field2: 18
/// };
///
/// # assert_eq!(dict["field"], 15);
/// # assert_eq!(dict["field2"], 18);
///
/// let map = map! [("field", 15), ("field2", 18)];
/// assert_eq!(dict, map);
/// ```
#[macro_export]
macro_rules! map {
    ($( ($key:expr, $value:expr) ),* $(,)?) => {
        [$(($key, $value)),*].into_iter().collect::<std::collections::HashMap<_, _>>()
    };
    (
        $($key:ident : $value:expr),*
        $(,)?
    ) => {

        $crate::map!(
            std::collections::HashMap::<&'static str, _>::new(),
            $(
                stringify!($key) => $value
            ),*
        )

    };
    (
        $map:expr,
        $($key:expr => $value:expr),*
        $(,)?
    ) => {
        {
            use std::collections::HashMap;
            let mut map: HashMap<_, _> = $map;

            $(
            {
                let key = $key;
                if !map.contains_key(&key) {
                    let value = $value;
                    map.insert(key, value);

                } else {
                    panic!("{key} already in dict")
                }
            }
            )*

            map
        }
    };
    (
        $($key:expr => $value:expr),*
        $(,)?
    ) => {
        $crate::map!(std::collections::HashMap::new(), $($key => $value),*)
    };
    ($key:expr => $value:expr; $v:ident in $range:expr) => {
        $crate::iter![($key, $value); $v in $range].collect::<std::collections::HashMap<_, _>>()
    };
    ($key:expr => $value:expr; $v:ident in $range:expr; if $cond:expr) => {
        $crate::iter![($key, $value); $v in $range; if $cond].collect::<std::collections::HashMap<_, _>>()
    };
}

/// Creates a basic iter using the python-style list comprehension syntax
#[macro_export]
macro_rules! set {
    () => {
        std::collections::HashSet::new()
    };
    ($ty:ty) => {
        std::collections::HashSet::<$ty>::new()
    };
    ($($key:expr),* $(,)?) => {
        std::collections::HashSet::<_>::from_iter(vec![$($key),*])
    };
    ($($tok:tt)*) => {
        std::iter::Iterator::collect::<std::collections::HashSet<_>>($crate::iter!($($tok)*))
    };
}



/// Creates a basic iter using the python-style list comprehension syntax
#[macro_export]
macro_rules! iter {
    ($ex:expr; $v:ident in $range:expr) => {
        IntoIterator::into_iter($range).map(|$v| $ex)
    };
    ($ex:expr; $v:ident in $range:expr; if $cond:expr) => {
        IntoIterator::into_iter($range)
            .filter(|$v| $cond)
            .map(|$v| $ex)
    };
}


/// A wrapper around [iter](crate::iter) that collects into a vector
#[macro_export]
macro_rules! list {
    ($($tok:tt)*) => {
        std::iter::Iterator::collect::<std::vec::Vec<_>>($crate::iter!($($tok)*))
    };
}


#[cfg(test)]
mod tests {
    use std::collections::{HashMap, HashSet};
    use super::*;

    #[test]
    fn map() {
        let map = map! {
            "key1".to_string() => "value1",
            "key2".to_string() => "value2",
        };

        let expected = vec![(format!("key1"), "value1"), (format!("key2"), "value2")]
            .into_iter()
            .collect::<HashMap<_, _>>();

        assert_eq!(map, expected);
    }

    #[test]
    fn basic_dict() {
        let dict: HashMap<_, &str> = map! {
            key1: "value1",
            key2: "value2"
        };

        let expected = map! {
            "key1" => "value1",
            "key2" => "value2",
        };

        assert_eq!(dict, expected);
    }

    #[test]
    fn alt_dict() {
        assert_eq!(
            map! { "a" => 1u32, "b" => 2u32},
            map! { a: 1u32, b: 2u32}
        )
    }

    #[test]
    #[should_panic]
    fn repeat_keys() {
        let _dict: HashMap<_, i32> = map! {
            key1: 0,
            key2: 1,
            key3: 4,
            key2: 4,
        };
    }

    #[test]
    fn iterators() {
        let iter: Vec<i32> = iter!(a*a; a in 0..=5).collect();
        assert_eq!(iter, vec![0, 1, 4, 9, 16, 25]);
        let iter: Vec<i32> = iter!(a*a; a in 0..=5; if a % 2 == 0).collect();
        assert_eq!(iter, vec![0, 4, 16]);
        let list = list!(a*a; a in 0..=5; if a % 2 == 0);
        assert_eq!(list, iter);
    }

    #[test]
    fn map_comprehension() {
        let map = map![i => i*i; i in 0..=5];
        let expected = map![
            0 => 0,
            1 => 1,
            2 => 4,
            3 => 9,
            4 => 16,
            5 => 25
        ];
        assert_eq!(map, expected);
        let map = map![i => i*i; i in 0..=5; if i %2 == 0];
        let expected = map![
            0 => 0,
            2 => 4,
            4 => 16,
        ];
        assert_eq!(map, expected);
    }

    #[test]
    fn sets() {
        assert_eq!(set!(), HashSet::<()>::new());
        assert_eq!(set!(u32), HashSet::new());
        assert_eq!(set!(1, 2, 3), HashSet::from_iter([1, 2, 2, 3, 3, 3]));
        assert_eq!(set!(x; x in 0..3), set!(0, 1, 2));
        assert_eq!(set!(x; x in 0..4; if x % 2 == 1), set!(1, 3));
    }
}