Created
February 2, 2016 06:02
-
-
Save pierric/213a1fbd4d4dec85d806 to your computer and use it in GitHub Desktop.
Split over an iterator in Rust
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 Split<I, P> { | |
iter: I, | |
pred: P, | |
} | |
impl<I, P> Iterator for Split<I,P> where I: Iterator, P: Fn(&I::Item) -> bool { | |
type Item = Vec<I::Item>; | |
fn next(&mut self) -> Option<Vec<I::Item>> { | |
let ref p = self.pred; | |
let not_p = |x: &I::Item| !p(x); | |
let mut i = self.iter.by_ref().skip_while(p).take_while(not_p); | |
match i.next() { | |
None => None, | |
Some(x) => { | |
let mut v = Vec::new(); | |
v.push(x); | |
v.extend(i); | |
Some(v) | |
} | |
} | |
} | |
} | |
fn split<I: Iterator, P: Fn(&I::Item) -> bool>(iter: I, pred: P) -> Split<I, P> { | |
Split { iter: iter, pred: pred} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment