Created
January 17, 2019 03:36
-
-
Save rust-play/d0355001e90db38d1bccce9af76e8ef6 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 Flatten<I, S> | |
where | |
I: Iterator, | |
S: Iterator, | |
{ | |
base: I, | |
inner: S, | |
} | |
impl<I> Flatten<I, <I::Item as IntoIterator>::IntoIter> | |
where | |
I: Iterator, | |
<I as Iterator>::Item: IntoIterator, | |
{ | |
fn new (mut it: I) -> Flatten<I, <I::Item as IntoIterator>::IntoIter> { | |
let inner = it.next().unwrap().into_iter(); | |
Flatten { | |
base: it, | |
inner, | |
} | |
} | |
} | |
impl<I> Iterator for Flatten<I, <I::Item as IntoIterator>::IntoIter> | |
where | |
I: Iterator, | |
<I as Iterator>::Item: IntoIterator, | |
{ | |
type Item = <<I as Iterator>::Item as IntoIterator>::Item; | |
fn next(&mut self) -> Option<<I::Item as IntoIterator>::Item> { | |
loop { | |
match self.inner.next() { | |
Some(a) => return Some(a), | |
None => {}, | |
} | |
match self.base.next() { | |
Some(a) => self.inner = a.into_iter(), | |
None => return None, | |
} | |
} | |
} | |
} | |
fn main() { | |
let mut hilly = vec![[1, 2, 3], [4, 5, 6]]; | |
println!("{:?}", Flatten::new(hilly.iter()).collect::<Vec<_>>()); | |
hilly.clear(); | |
println!("{:?}", Flatten::new(hilly.iter()).collect::<Vec<_>>()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment