for_loop_iterator/
lib.rs

1#[cfg(test)]
2mod test;
3/// Iterator that acts like a traditional for loop
4pub struct ForLoopIterator<Item> 
5{
6    current_value: Item,
7    while_predicate: Box<dyn Fn(&Item) -> bool>,
8    next_value_function: Box<dyn Fn(&Item) -> Item>
9}
10impl<Item> ForLoopIterator<Item> {
11    /// Creates an iterator that behaves similarly to a traditional for loop
12    /// * `init`: initial value
13    /// * `pred`: predicate that returns true if the value should be outputted
14    /// * `next`: function that creates the next value given the previous
15    /// # Examples
16    /// ```ignore
17    /// let mut iter = ForLoopIterator::new(
18    ///     10,
19    ///     |i| i > &0,
20    ///     |i| i - &2
21    /// );
22    /// assert_eq!(iter.next(), Some(10));
23    /// assert_eq!(iter.next(), Some(8));
24    /// let mut iter = iter.skip(2);
25    /// assert_eq!(iter.next(), Some(2));
26    /// assert_eq!(iter.next(), None);
27    /// ```
28    /// The values can be of any type.
29    /// ```ignore
30    /// struct MyStruct(i32);
31    /// let mut it = ForLoopIterator::new(
32	/// 	MyStruct(0),
33	/// 	|i| i.0 < 10i32,
34	/// 	|i| MyStruct(i.0+1)
35	/// );
36	/// assert_eq!(it.next(), Some(MyStruct(0)));
37	/// assert_eq!(it.next(), Some(MyStruct(1)));
38	/// assert_eq!(it.next(), Some(MyStruct(2)));
39    /// // etc
40    /// ```
41    pub fn new(init: Item, pred: impl Fn(&Item) -> bool + 'static, next: impl Fn(&Item) -> Item + 'static) -> ForLoopIterator<Item> 
42        // where
43        //     PredType: Fn(Item) -> bool,/*Fn<Item, Output = bool>*/
44        //     NextFnType: Fn(Item) -> Item
45    {
46        ForLoopIterator {
47            current_value: init,
48            while_predicate: Box::new(pred),
49            next_value_function: Box::new(next)
50        }
51    }
52}
53impl<Item> Iterator for ForLoopIterator<Item> {
54    type Item = Item;
55
56    fn next(&mut self) -> Option<Self::Item> {
57        use std::mem;
58
59        if !(self.while_predicate)(&self.current_value) {
60            return None;
61        }
62        let mut swap_with = (self.next_value_function)(&self.current_value);
63        mem::swap(&mut self.current_value, &mut swap_with);
64        Some(swap_with)
65    }
66}