use std::collections::HashMap; use std::collections::hash_map::Entry; use std::hash::Hash; use std::fmt; use std::iter::FusedIterator;
/// An iterator adapter to filter out duplicate elements. /// /// See [`.unique_by()`](crate::Itertools::unique) for more information. #[derive(Clone)] #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pubstruct UniqueBy<I: Iterator, V, F> {
iter: I, // Use a Hashmap for the Entry API in order to prevent hashing twice. // This can maybe be replaced with a HashSet once `get_or_insert_with` // or a proper Entry API for Hashset is stable and meets this msrv
used: HashMap<V, ()>,
f: F,
}
/// Create a new `UniqueBy` iterator. pubfn unique_by<I, V, F>(iter: I, f: F) -> UniqueBy<I, V, F> where V: Eq + Hash,
F: FnMut(&I::Item) -> V,
I: Iterator,
{
UniqueBy {
iter,
used: HashMap::new(),
f,
}
}
// count the number of new unique keys in iterable (`used` is the set already seen) fn count_new_keys<I, K>(mut used: HashMap<K, ()>, iterable: I) -> usize where I: IntoIterator<Item=K>,
K: Hash + Eq,
{ let iter = iterable.into_iter(); let current_used = used.len();
used.extend(iter.map(|key| (key, ())));
used.len() - current_used
}
impl<I, V, F> Iterator for UniqueBy<I, V, F> where I: Iterator,
V: Eq + Hash,
F: FnMut(&I::Item) -> V
{ type Item = I::Item;
impl<I> FusedIterator for Unique<I> where I: FusedIterator,
I::Item: Eq + Hash + Clone
{}
/// An iterator adapter to filter out duplicate elements. /// /// See [`.unique()`](crate::Itertools::unique) for more information. #[derive(Clone)] #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pubstruct Unique<I: Iterator> {
iter: UniqueBy<I, I::Item, ()>,
}
impl<I> fmt::Debug for Unique<I> where I: Iterator + fmt::Debug,
I::Item: Hash + Eq + fmt::Debug,
{
debug_fmt_fields!(Unique, iter);
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.