3 /// Create an `IndexMap` from a list of key-value pairs
8 /// use indexmap::indexmap;
10 /// let map = indexmap!{
14 /// assert_eq!(map["a"], 1);
15 /// assert_eq!(map["b"], 2);
16 /// assert_eq!(map.get("c"), None);
18 /// // "a" is the first key
19 /// assert_eq!(map.keys().next(), Some(&"a"));
21 macro_rules
! indexmap
{
22 (@single $
($x
:tt
)*) => (());
23 (@count $
($rest
:expr
),*) => (<[()]>::len(&[$
($
crate::indexmap
!(@single $rest
)),*]));
25 ($
($key
:expr
=> $value
:expr
,)+) => { $crate::indexmap!($($key => $value),+) }
;
26 ($
($key
:expr
=> $value
:expr
),*) => {
28 let _cap
= $
crate::indexmap
!(@count $
($key
),*);
29 let mut _map
= $
crate::IndexMap
::with_capacity(_cap
);
31 _map
.insert($key
, $value
);
40 /// Create an `IndexSet` from a list of values
45 /// use indexmap::indexset;
47 /// let set = indexset!{
51 /// assert!(set.contains("a"));
52 /// assert!(set.contains("b"));
53 /// assert!(!set.contains("c"));
55 /// // "a" is the first value
56 /// assert_eq!(set.iter().next(), Some(&"a"));
58 macro_rules
! indexset
{
59 (@single $
($x
:tt
)*) => (());
60 (@count $
($rest
:expr
),*) => (<[()]>::len(&[$
($
crate::indexset
!(@single $rest
)),*]));
62 ($
($value
:expr
,)+) => { $crate::indexset!($($value),+) }
;
63 ($
($value
:expr
),*) => {
65 let _cap
= $
crate::indexset
!(@count $
($value
),*);
66 let mut _set
= $
crate::IndexSet
::with_capacity(_cap
);
75 // generate all the Iterator methods by just forwarding to the underlying
76 // self.iter and mapping its element.
77 macro_rules
! iterator_methods
{
78 // $map_elt is the mapping function from the underlying iterator's element
79 // same mapping function for both options and iterators
81 fn next(&mut self) -> Option
<Self::Item
> {
82 self.iter
.next().map($map_elt
)
85 fn size_hint(&self) -> (usize, Option
<usize>) {
89 fn count(self) -> usize {
93 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {
94 self.iter
.nth(n
).map($map_elt
)
97 fn last(mut self) -> Option
<Self::Item
> {
101 fn collect
<C
>(self) -> C
103 C
: FromIterator
<Self::Item
>,
105 // NB: forwarding this directly to standard iterators will
106 // allow it to leverage unstable traits like `TrustedLen`.
107 self.iter
.map($map_elt
).collect()
112 macro_rules
! double_ended_iterator_methods
{
113 // $map_elt is the mapping function from the underlying iterator's element
114 // same mapping function for both options and iterators
116 fn next_back(&mut self) -> Option
<Self::Item
> {
117 self.iter
.next_back().map($map_elt
)