I'm working on the iterator adaptor which uses a HashMap internally. First, it matches all the input iterator keys with the map and flags them as matched. At the end I want to iterate over the map's values flagged as not matched.
Apparently, I need to store both the map and its Values iterator (which stores the state of the iteration) in the same struct, but I cannot figure out how to do it.
Here is an example without matching the input iterator to keep things simple:
use std::collections::hash_map::{HashMap, Values,};
use std::hash::Hash;
struct Foo<'a, K, V>
where K: 'a + Hash + Eq,
V: 'a + Clone,
{
map: HashMap<K, (V, bool)>,
values: Values<'a, K, (V, bool)>,
}
impl<'a, K, V> Foo<'a, K, V>
where K: 'a + Hash + Eq,
V: 'a + Clone,
{
fn new<I>(it: I) -> Self
where I: Iterator<Item=(K, V)>
{
// load the HashMap
let mut map: HashMap<K, (V, bool)> = HashMap::new();
for (k, v) in it {
map.insert(k, (v, false));
}
// I cannot use `let values = map.values();` since map will be moved to Foo.
Foo {map: map, values: ???}
}
}
impl<'a, K, V> Iterator for Foo<'a, K, V>
where K: 'a + Hash + Eq,
V: 'a + Clone,
{
type Item = V;
fn next(&mut self) -> Option<Self::Item> {
match self.values.next() {
loop {
match some.values.next() {
Some(v) if !v.1 => return Some(Clone::clone(&v.0)),
Some(_) => continue,
None => return None,
}
}
}
}
}
fn main() {
let it = (0..).zip("AB".chars());
let foo = Foo::new(it);
for v in foo {
println!("{}", v);
}
}
Thanks a lot for any suggestions.