1use core::iter::Peekable;
2
3/// An iterator for deduping the key of a sorted iterator.
4/// When encountering the duplicated key, only the last key-value pair is yielded.
5///
6/// Used by [`BTreeMap::bulk_build_from_sorted_iter`][1].
7///
8/// [1]: crate::collections::BTreeMap::bulk_build_from_sorted_iter
9pub struct DedupSortedIter<K, V, I>
10where
11 I: Iterator<Item = (K, V)>,
12{
13 iter: Peekable<I>,
14}
15
16impl<K, V, I> DedupSortedIter<K, V, I>
17where
18 I: Iterator<Item = (K, V)>,
19{
20 pub fn new(iter: I) -> Self {
21 Self { iter: iter.peekable() }
22 }
23}
24
25impl<K, V, I> Iterator for DedupSortedIter<K, V, I>
26where
27 K: Eq,
28 I: Iterator<Item = (K, V)>,
29{
30 type Item = (K, V);
31
32 fn next(&mut self) -> Option<(K, V)> {
33 loop {
34 let next: (K, V) = match self.iter.next() {
35 Some(next: (K, V)) => next,
36 None => return None,
37 };
38
39 let peeked: &(K, V) = match self.iter.peek() {
40 Some(peeked: &(K, V)) => peeked,
41 None => return Some(next),
42 };
43
44 if next.0 != peeked.0 {
45 return Some(next);
46 }
47 }
48 }
49}
50