I have a Rc<RefCell<HashSet>>
that is stored in exactly 2 HashMap
indices, and I'm struggling to write an Iterator over one of those indices; this is my current attempt:
use std::cell::Ref;
use std::cell::RefCell;
use std::collections::hash_map;
use std::collections::hash_set;
use std::collections::HashMap;
use std::collections::HashSet;
use std::rc::Rc;
struct Store
{
index1: HashMap<u32, Rc<RefCell<HashSet<u32>>>>,
index2: HashMap<u32, Rc<RefCell<HashSet<u32>>>>,
}
struct StoreIter<'a>
{
index_iterator: hash_map::Iter<'a, u32, Rc<RefCell<HashSet<u32>>>>,
objects: Ref<'a, HashSet<u32>>,
object_iterator: Ref<'a,hash_set::Iter<'a, u32>>,
next: Option<(u32, u32)>
}
impl Store {
fn new() -> Store {
let twos: Rc<RefCell<HashSet<u32>>> =
Rc::new(RefCell::new([ 2, 4, 6, 8, 10 ].iter().cloned().collect()));
let threes: Rc<RefCell<HashSet<u32>>> =
Rc::new(RefCell::new([ 3, 6, 9, 12, 15 ].iter().cloned().collect()));
let mut index1 = HashMap::new();
index1.insert(2, twos.clone());
index1.insert(3, threes.clone());
let mut index2 = HashMap::new();
index2.insert(3, twos);
index2.insert(2, threes);
Store {
index1,
index2
}
}
fn iter<'a>(&'a self) -> StoreIter<'a>
{
let mut i1it = self.index1.iter();
let i1n = i1it.next().unwrap();
let objects: Ref<'a, HashSet<u32>> = i1n.1.borrow();
let mut oit: Ref<'a, hash_set::Iter<'a, u32>> = Ref::map(Ref::clone(&objects), |o| o.iter());
let oin: u32 = *oit.next().unwrap();
StoreIter {
index_iterator: i1it,
objects: objects,
object_iterator: oit,
next: Some((*i1n.0, oin))
}
}
}
impl<'a> Iterator for StoreIter<'a>
{
type Item = (u32, u32);
fn next(&mut self) -> Option<Self::Item>
{
None
}
}
fn main() {
let store = Store::new();
for item in store.iter() {
println!("{:?}", item);
}
}
The current error is that the function in Ref::map
should return a reference. I think I need some container that I can store in StoreIter
alongside the objects
Ref
, which guarantees the lifetime of 'a
, but I can't quite square that circle. Any ideas?
Thanks,
Alex