utils/
iter.rs

1//!
2//!  iter.rs
3//!
4//!  Created by Mitchell Nordine at 11:27AM on November 07, 2014.
5//!
6//!  A collection of custom iterators for iterating things!
7//!
8
9pub use self::sample_on::SampleOn;
10
11pub mod sample_on {
12
13    /// Sample from the current iterator every time an iteration occurs on another iterator.
14    /// This is primarily used for binding an iterator to another timed iterator. i.e.
15    /// `(0..1000).sample_on(Fps::new(60.0))`.
16    pub trait SampleOn: Sized + Iterator {
17        #[inline]
18        fn sample_on<O: Iterator>(self, other: O) -> Items<Self, O> {
19            Items { sample: self, on: other, last_sample: None, is_infinite: false }
20        }
21    }
22
23    /// Iterator returned from the `sample_on` method.
24    pub struct Items<A, B> where A: Iterator, B: Iterator {
25        sample: A,
26        on: B,
27        last_sample: Option<A::Item>,
28        is_infinite: bool,
29    }
30
31    impl<A, B> Items<A, B> where A: Iterator, B: Iterator {
32        /// Construct a never-ending signal.
33        #[inline]
34        pub fn infinite(self) -> Items<A, B> {
35            Items { is_infinite: true, ..self }
36        }
37    }
38
39    impl<A, B> Iterator for Items<A, B>
40        where
41            A: Iterator,
42            B: Iterator,
43            A::Item: Clone
44    {
45        type Item = A::Item;
46        fn next(&mut self) -> Option<A::Item> {
47            while let None = self.on.next() {}
48            match self.sample.next() {
49                None => if self.is_infinite { self.last_sample.clone() } else { None },
50                Some(sample) => {
51                    self.last_sample = Some(sample.clone());
52                    Some(sample)
53                },
54            }
55        }
56    }
57
58}