1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//! Delay iterator
//!
//! A simpler iterator than `clock::Clock` that delays between executions with non-adaptive
//! intervals.

use std::{iter, thread, time};

/// Simple iterable delay
///
/// Iterating over this structure will insert `delay` between each iteration, starting after the
/// first.
pub struct Delay {
    /// Delay duration
    delay: time::Duration,

    /// Notes whether or not we are on the first tick. Used to skip the delay on first iteration.
    first_tick: bool,
}

impl Delay {
    /// Creates a new delay
    #[inline]
    pub fn new(delay: time::Duration) -> Delay {
        Delay {
            delay,
            first_tick: true,
        }
    }

    /// Creates a new delay that delays first
    #[inline]
    pub fn delayed(delay: time::Duration) -> Delay {
        Delay {
            delay,
            first_tick: false,
        }
    }
}

impl<'a> iter::Iterator for Delay {
    type Item = ();

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.first_tick {
            self.first_tick = false;
        } else {
            thread::sleep(self.delay);
        }

        Some(())
    }
}