#[macro_export]
macro_rules! collect {
($type:ty) => {
[].into_iter().collect::<$type>()
};
($type:ty; $n:expr) => {{
<$type>::with_capacity($n)
}};
($type:ty: $($item:expr),*) => {
[$($item),*].into_iter().collect::<$type>()
};
($type:ty: $($item:expr),*; $n:expr) => {{
let mut collection = <$type>::with_capacity($n);
collection.extend([$($item),*]);
collection
}};
($($item:expr),*) => {
[$($item),*].into_iter().collect()
};
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
#[test]
fn create_with_inferred_type() {
let collection: HashSet<i32> = collect![1, 2, 3];
assert_eq!(HashSet::from_iter([1, 2, 3].into_iter()), collection);
}
#[test]
fn create_with_inferred_type_with_no_items() {
let collection: HashSet<i32> = collect![];
assert_eq!(HashSet::new(), collection);
}
#[test]
fn create_with_inline_type() {
let collection = collect![HashSet<i32>: 1, 2, 3];
assert_eq!(HashSet::from_iter([1, 2, 3].into_iter()), collection);
}
#[test]
fn create_empty_with_inline_type() {
let collection = collect![HashSet<i32>];
assert_eq!(HashSet::new(), collection);
}
#[test]
fn create_with_capacity() {
let collection = collect![HashSet<i32>: 1, 2, 3; 14];
assert_eq!(14, collection.capacity());
assert_eq!(HashSet::from_iter([1, 2, 3].into_iter()), collection);
}
#[test]
fn create_empty_with_capacity() {
let collection = collect![HashSet<i32>; 14];
assert_eq!(14, collection.capacity());
assert_eq!(HashSet::new(), collection);
}
}