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.

Revisions

  1. ucarion created this gist Dec 22, 2014.
    43 changes: 43 additions & 0 deletions each_cons.rs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    #![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
    }
    }