dedup_sorted_iter.rs - source
Description: Source of the Rust file `library/alloc/src/collections/btree/dedup_sorted_iter.rs`.

#
alloc/collections/btree/
dedup_sorted_iter.rs

    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(super) 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(super) 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 = match self.iter.next() {
    35                Some(next) => next,
    36                None => return None,
    37            };
    38
    39            let peeked = match self.iter.peek() {
    40                Some(peeked) => peeked,
    41                None => return Some(next),
    42            };
    43
    44            if next.0 != peeked.0 {
    45                return Some(next);
    46            }
    47        }
    48    }
    49}