Created
November 11, 2019 19:17
-
-
Save rust-play/89a790f3285f1345a74b5e23ce895cac to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Interleave<I, T> where I: Iterator<Item = T> { | |
outer: Box<dyn Iterator<Item = (usize, I)>>, | |
skip: Vec<usize>, | |
} | |
impl<I, T> Interleave<I, T> where I: Iterator<Item = T> { | |
pub fn new(iter: impl Iterator<Item = I> + Clone + 'static) -> Self { | |
Self { | |
outer: Box::new(iter.enumerate().cycle()) as Box<dyn Iterator<Item = (usize, I)>>, | |
skip: Vec::new() | |
} | |
} | |
} | |
impl<I, T> Iterator for Interleave<I, T> where I: Iterator<Item = T> { | |
type Item = T; | |
fn next(&mut self) -> Option<T> { | |
let mut zdone = false; | |
while let Some((n, inner)) = self.outer.next() { | |
let skip = if let Some(s) = self.skip.get_mut(n) { | |
*s += 1; | |
*s | |
} else { | |
assert_eq!(n, self.skip.len()); | |
self.skip.push(0); | |
0 | |
}; | |
let t = inner.skip(skip).next(); | |
if t.is_none() { | |
if n == 0 { | |
if zdone { return None; } | |
else { zdone = true; } | |
} | |
continue; | |
} | |
return t; | |
} | |
None | |
} | |
} | |
fn main () { | |
let a = vec![1,4,7]; | |
let b = vec![2,5,8]; | |
let c = vec![3,6,9,10]; | |
let i = vec![a.into_iter(),b.into_iter(),c.into_iter()]; | |
let t = Interleave::new(i.into_iter()); | |
for n in t.take(20) { | |
println!("{}", n); | |
} | |
println!("done") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment