#[derive(Clone, Debug)]
pub struct IteratorCache<I: Iterator> {
xs: I,
cache: Vec<I::Item>,
done: bool,
}
impl<I: Iterator> IteratorCache<I> {
pub const fn new(xs: I) -> IteratorCache<I> {
IteratorCache {
xs,
cache: Vec::new(),
done: false,
}
}
pub fn get(&mut self, index: usize) -> Option<&I::Item> {
if !self.done && index >= self.cache.len() {
self.cache
.extend((&mut self.xs).take(index - self.cache.len() + 1));
if index >= self.cache.len() {
self.done = true;
return None;
}
}
self.cache.get(index)
}
pub fn assert_get(&self, index: usize) -> &I::Item {
self.cache.get(index).unwrap()
}
pub fn known_len(&self) -> Option<usize> {
if self.done {
Some(self.cache.len())
} else {
None
}
}
}