Created
December 22, 2014 23:37
-
-
Save ucarion/600372b6498abc8215d0 to your computer and use it in GitHub Desktop.
Rust each_cons
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
#![feature(slicing_syntax)] | |
use std::collections::RingBuf; | |
fn main() { | |
let xs = &[1i, 2i, 3i, 4i, 5i]; | |
let mut iter = EachCons { iter: xs.iter(), n: 3, buffer: RingBuf::new() }; | |
for x in iter { | |
println!("{}", x); | |
} | |
} | |
pub struct EachCons<A, T> where T: Iterator<A> { | |
iter: T, | |
n: uint, | |
buffer: RingBuf<A> | |
} | |
impl<A: Clone, T: Iterator<A>> Iterator<Vec<A>> for EachCons<A, T> { | |
fn next(&mut self) -> Option<Vec<A>> { | |
for x in self.iter { | |
self.buffer.push_back(x); | |
if self.buffer.len() > self.n { | |
self.buffer.pop_front(); | |
} | |
if self.buffer.len() == self.n { | |
let (slice, _) = self.buffer.as_slices(); | |
let mut v = Vec::new(); | |
v.push_all(slice); | |
return Some(v); | |
} else { | |
continue | |
} | |
} | |
None | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment