Skip to content

Instantly share code, notes, and snippets.

@ucarion
Created December 22, 2014 23:37
Show Gist options
  • Save ucarion/600372b6498abc8215d0 to your computer and use it in GitHub Desktop.
Save ucarion/600372b6498abc8215d0 to your computer and use it in GitHub Desktop.
Rust each_cons
#![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