index_map/
iter.rs

1use super::{IndexMap, OptionIndex};
2use core::fmt;
3use core::iter::{Enumerate, ExactSizeIterator, IntoIterator, Iterator};
4use core::slice;
5
6/// An iterator over the entries of a `IndexMap`.
7///
8/// This `struct` is created by the [`iter`](IndexMap::iter) method on [`IndexMap`]. See its
9/// documentation for more.
10///
11/// # Example
12/// ```
13/// use index_map::IndexMap;
14///
15/// let mut map = IndexMap::new();
16/// map.insert("a");
17/// let iter = map.iter();
18/// ```
19pub struct Iter<'a, T> {
20    inner: Enumerate<slice::Iter<'a, OptionIndex<T>>>,
21    len: usize,
22}
23
24impl<T> Clone for Iter<'_, T> {
25    fn clone(&self) -> Self {
26        Self {
27            inner: self.inner.clone(),
28            len: self.len,
29        }
30    }
31}
32
33impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        f.debug_list().entries(self.clone()).finish()
36    }
37}
38
39impl<'a, T> Iterator for Iter<'a, T> {
40    type Item = (usize, &'a T);
41
42    fn next(&mut self) -> Option<Self::Item> {
43        while let Some((i, item)) = self.inner.next() {
44            if let OptionIndex::Some(val) = item {
45                self.len -= 1;
46                return Some((i, val));
47            }
48        }
49        None
50    }
51
52    fn size_hint(&self) -> (usize, Option<usize>) {
53        (self.len, Some(self.len))
54    }
55}
56
57impl<T> ExactSizeIterator for Iter<'_, T> {}
58
59impl<'a, T> IntoIterator for &'a IndexMap<T> {
60    type Item = (usize, &'a T);
61    type IntoIter = Iter<'a, T>;
62
63    fn into_iter(self) -> Self::IntoIter {
64        Iter {
65            inner: self.data.iter().enumerate(),
66            len: self.len(),
67        }
68    }
69}
70
71/// A mutable iterator over the entries of a `IndexMap`.
72///
73/// This `struct` is created by the [`iter_mut`](IndexMap::iter_mut) method on [`IndexMap`]. See its
74/// documentation for more.
75///
76/// # Example
77/// ```
78/// use index_map::IndexMap;
79///
80/// let mut map = IndexMap::new();
81/// map.insert("a");
82/// let iter = map.iter_mut();
83/// ```
84#[derive(Debug)]
85pub struct IterMut<'a, T> {
86    inner: Enumerate<slice::IterMut<'a, OptionIndex<T>>>,
87    len: usize,
88}
89
90impl<'a, T> Iterator for IterMut<'a, T> {
91    type Item = (usize, &'a mut T);
92
93    fn next(&mut self) -> Option<Self::Item> {
94        while let Some((i, item)) = self.inner.next() {
95            if let OptionIndex::Some(val) = item {
96                self.len -= 1;
97                return Some((i, val));
98            }
99        }
100        None
101    }
102
103    fn size_hint(&self) -> (usize, Option<usize>) {
104        (self.len, Some(self.len))
105    }
106}
107
108impl<T> ExactSizeIterator for IterMut<'_, T> {}
109
110impl<'a, T> IntoIterator for &'a mut IndexMap<T> {
111    type Item = (usize, &'a mut T);
112    type IntoIter = IterMut<'a, T>;
113
114    fn into_iter(self) -> Self::IntoIter {
115        IterMut {
116            len: self.len(),
117            inner: self.data.iter_mut().enumerate(),
118        }
119    }
120}
121
122/// An owning iterator over the entries of a `IndexMap`.
123///
124/// This `struct` is created by the [`into_iter`](IndexMap::into_iter) method on [`IndexMap`]
125/// (provided by the `IntoIterator` trait). See its documentation for more.
126///
127/// # Example
128/// ```
129/// use index_map::IndexMap;
130///
131/// let mut map = IndexMap::new();
132/// map.insert("a");
133/// let iter = map.into_iter();
134/// ```
135#[derive(Clone)]
136pub struct IntoIter<T> {
137    inner: Enumerate<alloc::vec::IntoIter<OptionIndex<T>>>,
138    len: usize,
139}
140
141impl<T> Iterator for IntoIter<T> {
142    type Item = (usize, T);
143
144    fn next(&mut self) -> Option<Self::Item> {
145        while let Some((i, item)) = self.inner.next() {
146            if let OptionIndex::Some(item) = item {
147                self.len -= 1;
148                return Some((i, item));
149            }
150        }
151        None
152    }
153
154    fn size_hint(&self) -> (usize, Option<usize>) {
155        (self.len, Some(self.len))
156    }
157}
158
159impl<T> ExactSizeIterator for IntoIter<T> {}
160
161impl<T> IntoIterator for IndexMap<T> {
162    type Item = (usize, T);
163    type IntoIter = IntoIter<T>;
164
165    fn into_iter(self) -> Self::IntoIter {
166        IntoIter {
167            len: self.len(),
168            inner: self.data.into_iter().enumerate(),
169        }
170    }
171}
172
173/// A draining iterator over the entries of a `IndexMap`.
174///
175/// This `struct` is created by the [`drain`](IndexMap::drain) method on [`IndexMap`]. See its
176/// documentation for more.
177///
178/// # Example
179/// ```
180/// use index_map::IndexMap;
181///
182/// let mut map = IndexMap::new();
183/// map.insert("a");
184/// let iter = map.drain();
185/// ```
186pub struct Drain<'a, T> {
187    inner: Enumerate<alloc::vec::Drain<'a, OptionIndex<T>>>,
188    len: usize,
189}
190
191impl<T> Iterator for Drain<'_, T> {
192    type Item = (usize, T);
193
194    fn next(&mut self) -> Option<Self::Item> {
195        while let Some((i, item)) = self.inner.next() {
196            if let OptionIndex::Some(item) = item {
197                self.len -= 1;
198                return Some((i, item));
199            }
200        }
201        None
202    }
203
204    fn size_hint(&self) -> (usize, Option<usize>) {
205        (self.len, Some(self.len))
206    }
207}
208
209impl<T> ExactSizeIterator for Drain<'_, T> {}
210
211/// An iterator over the keys of a `IndexMap`.
212///
213/// This `struct` is created by the [`keys`](IndexMap::keys) method on [`IndexMap`]. See its
214/// documentation for more.
215///
216/// # Example
217/// ```
218/// use index_map::IndexMap;
219///
220/// let mut map = IndexMap::new();
221/// map.insert("a");
222/// let iter_keys = map.keys();
223/// ```
224pub struct Keys<'a, T> {
225    inner: Iter<'a, T>,
226}
227
228impl<T> Clone for Keys<'_, T> {
229    fn clone(&self) -> Self {
230        Self {
231            inner: self.inner.clone(),
232        }
233    }
234}
235
236impl<'a, T> fmt::Debug for Keys<'a, T> {
237    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238        f.debug_list().entries(self.clone()).finish()
239    }
240}
241
242impl<'a, T> Iterator for Keys<'a, T> {
243    type Item = usize;
244
245    fn next(&mut self) -> Option<Self::Item> {
246        Some(self.inner.next()?.0)
247    }
248
249    fn size_hint(&self) -> (usize, Option<usize>) {
250        (self.inner.len, Some(self.inner.len))
251    }
252}
253
254impl<T> ExactSizeIterator for Keys<'_, T> {}
255
256/// An iterator over the values of a `IndexMap`.
257///
258/// This `struct` is created by the [`values`](IndexMap::values) method on [`IndexMap`]. See its
259/// documentation for more.
260///
261/// # Example
262/// ```
263/// use index_map::IndexMap;
264///
265/// let mut map = IndexMap::new();
266/// map.insert("a");
267/// let iter_values = map.values();
268/// ```
269pub struct Values<'a, T> {
270    inner: Iter<'a, T>,
271}
272
273impl<T> Clone for Values<'_, T> {
274    fn clone(&self) -> Self {
275        Self {
276            inner: self.inner.clone(),
277        }
278    }
279}
280
281impl<'a, T: fmt::Debug> fmt::Debug for Values<'a, T> {
282    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283        f.debug_list().entries(self.clone()).finish()
284    }
285}
286
287impl<'a, T> Iterator for Values<'a, T> {
288    type Item = &'a T;
289
290    fn next(&mut self) -> Option<Self::Item> {
291        Some(self.inner.next()?.1)
292    }
293
294    fn size_hint(&self) -> (usize, Option<usize>) {
295        (self.inner.len, Some(self.inner.len))
296    }
297}
298
299impl<T> ExactSizeIterator for Values<'_, T> {}
300
301/// A mutable iterator over the values of a `IndexMap`.
302///
303/// This `struct` is created by the [`values_mut`](IndexMap::values_mut) method on [`IndexMap`]. See
304/// its documentation for more.
305///
306/// # Example
307/// ```
308/// use index_map::IndexMap;
309///
310/// let mut map = IndexMap::new();
311/// map.insert("a");
312/// let iter_values = map.values_mut();
313/// ```
314#[derive(Debug)]
315pub struct ValuesMut<'a, T> {
316    inner: IterMut<'a, T>,
317}
318
319impl<'a, T> Iterator for ValuesMut<'a, T> {
320    type Item = &'a mut T;
321
322    fn next(&mut self) -> Option<Self::Item> {
323        Some(self.inner.next()?.1)
324    }
325
326    fn size_hint(&self) -> (usize, Option<usize>) {
327        (self.inner.len, Some(self.inner.len))
328    }
329}
330
331impl<T> ExactSizeIterator for ValuesMut<'_, T> {}
332
333impl<T> IndexMap<T> {
334    /// An iterator visiting all keys in ascending order.
335    /// The iterator element type is `usize`.
336    ///
337    /// # Examples
338    /// ```
339    /// use index_map::IndexMap;
340    ///
341    /// let mut map = IndexMap::new();
342    /// map.insert("a");
343    /// map.insert("b");
344    /// map.insert("c");
345    ///
346    /// for key in map.keys() {
347    ///     println!("{}", key);
348    /// }
349    /// ```
350    pub fn keys(&self) -> Keys<'_, T> {
351        Keys { inner: self.iter() }
352    }
353
354    /// An iterator visiting all values in ascending order of their keys.
355    /// The iterator element type is `&T`.
356    ///
357    /// # Examples
358    /// ```
359    /// use index_map::IndexMap;
360    ///
361    /// let mut map = IndexMap::new();
362    /// map.insert("a");
363    /// map.insert("b");
364    /// map.insert("c");
365    ///
366    /// for val in map.values() {
367    ///     println!("{}", val);
368    /// }
369    /// ```
370    pub fn values(&self) -> Values<'_, T> {
371        Values { inner: self.iter() }
372    }
373
374    /// An iterator visiting all values mutably in ascending order of their keys.
375    /// The iterator element type is `&mut T`.
376    ///
377    /// # Examples
378    /// ```
379    /// use index_map::IndexMap;
380    ///
381    /// let mut map = IndexMap::new();
382    /// map.insert(2);
383    /// map.insert(4);
384    /// map.insert(6);
385    ///
386    /// for val in map.values_mut() {
387    ///     *val *= 2;
388    /// }
389    ///
390    /// for val in map.values() {
391    ///     println!("{}", val);
392    /// }
393    /// ```
394    pub fn values_mut(&mut self) -> ValuesMut<'_, T> {
395        ValuesMut {
396            inner: self.iter_mut(),
397        }
398    }
399
400    /// An iterator visiting all key-value pairs in ascending order of keys.
401    /// The iterator element type is `(usize, &T)`.
402    ///
403    /// # Examples
404    /// ```
405    /// use index_map::IndexMap;
406    ///
407    /// let mut map = IndexMap::new();
408    /// map.insert("a");
409    /// map.insert("b");
410    /// map.insert("c");
411    ///
412    /// for (key, val) in map.iter() {
413    ///     println!("key: {} val: {}", key, val);
414    /// }
415    /// ```
416    pub fn iter(&self) -> Iter<'_, T> {
417        <&IndexMap<T>>::into_iter(self)
418    }
419
420    /// An iterator visiting all key-value pairs in ascending order of keys, with mutable references
421    /// to the values.
422    /// The iterator element type is `(usize, &mut T)`.
423    ///
424    /// # Examples
425    /// ```
426    /// use index_map::IndexMap;
427    ///
428    /// let mut map = IndexMap::new();
429    /// map.insert(2);
430    /// map.insert(4);
431    /// map.insert(6);
432    ///
433    /// // Update all values
434    /// for (_, val) in map.iter_mut() {
435    ///     *val *= 2;
436    /// }
437    ///
438    /// for (key, val) in map.iter() {
439    ///     println!("key: {} val: {}", key, val);
440    /// }
441    /// ```
442    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
443        <&mut IndexMap<T>>::into_iter(self)
444    }
445
446    /// Clears the map, returning all key-value pairs as an iterator. Keeps the
447    /// allocated memory for reuse.
448    ///
449    /// # Examples
450    /// ```
451    /// use index_map::IndexMap;
452    ///
453    /// let mut a = IndexMap::new();
454    /// a.insert("a");
455    /// a.insert("b");
456    ///
457    /// let mut iter = a.drain();
458    /// assert_eq!(iter.next(), Some((0, "a")));
459    /// assert_eq!(iter.next(), Some((1, "b")));
460    /// assert_eq!(iter.next(), None);
461    /// # drop(iter);
462    ///
463    /// assert!(a.is_empty());
464    /// ```
465    pub fn drain(&mut self) -> Drain<'_, T> {
466        let len = self.len();
467        self.len = 0;
468        Drain {
469            len,
470            inner: self.data.drain(..).enumerate(),
471        }
472    }
473}
474
475#[cfg(test)]
476mod tests {
477    use super::IndexMap;
478
479    #[test]
480    fn test_iter() {
481        let mut map = IndexMap::new();
482        let a = map.insert("a");
483        let b = map.insert("b");
484        let c = map.insert("c");
485        map.remove(b);
486        let mut iter = map.iter().map(|(i, v)| (i, *v));
487        assert_eq!(iter.next(), Some((a, "a")));
488        assert_eq!(iter.next(), Some((c, "c")));
489        assert_eq!(iter.next(), None);
490
491        assert_eq!(b, map.insert("b"));
492        let mut iter = map.iter().map(|(i, v)| (i, *v));
493        assert_eq!(iter.next(), Some((a, "a")));
494        assert_eq!(iter.next(), Some((b, "b")));
495        assert_eq!(iter.next(), Some((c, "c")));
496        assert_eq!(iter.next(), None);
497    }
498
499    #[test]
500    fn test_iter_mut() {
501        let mut map = IndexMap::new();
502        let a = map.insert(1);
503        let b = map.insert(2);
504        let c = map.insert(3);
505        map.iter_mut().for_each(|(_, val)| *val *= 2);
506
507        let mut map = map.iter().map(|(i, v)| (i, *v));
508
509        assert_eq!(map.next(), Some((a, 2)));
510        assert_eq!(map.next(), Some((b, 4)));
511        assert_eq!(map.next(), Some((c, 6)));
512        assert_eq!(map.next(), None);
513    }
514
515    #[test]
516    fn test_keys() {
517        let mut map = IndexMap::new();
518        let a = map.insert("a");
519        let b = map.insert("b");
520        let c = map.insert("c");
521        map.remove(b);
522
523        let mut keys = map.keys();
524        assert_eq!(keys.next(), Some(a));
525        assert_eq!(keys.next(), Some(c));
526        assert_eq!(keys.next(), None);
527
528        assert_eq!(b, map.insert("b"));
529
530        let mut keys = map.keys();
531        assert_eq!(keys.next(), Some(a));
532        assert_eq!(keys.next(), Some(b));
533        assert_eq!(keys.next(), Some(c));
534        assert_eq!(keys.next(), None);
535    }
536
537    #[test]
538    fn test_values() {
539        let mut map = IndexMap::new();
540        map.insert("a");
541        let b = map.insert("b");
542        map.insert("c");
543        map.remove(b);
544        let mut iter = map.values().map(|v| *v);
545        assert_eq!(iter.next(), Some("a"));
546        assert_eq!(iter.next(), Some("c"));
547        assert_eq!(iter.next(), None);
548
549        assert_eq!(b, map.insert("b"));
550        let mut iter = map.values().map(|v| *v);
551        assert_eq!(iter.next(), Some("a"));
552        assert_eq!(iter.next(), Some("b"));
553        assert_eq!(iter.next(), Some("c"));
554        assert_eq!(iter.next(), None);
555    }
556
557    #[test]
558    fn test_values_mut() {
559        let mut map = IndexMap::new();
560        map.insert(1);
561        map.insert(2);
562        map.insert(3);
563        map.values_mut().for_each(|val| *val *= 2);
564
565        let mut map = map.values().map(|v| *v);
566
567        assert_eq!(map.next(), Some(2));
568        assert_eq!(map.next(), Some(4));
569        assert_eq!(map.next(), Some(6));
570        assert_eq!(map.next(), None);
571    }
572}