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
54
55
56
57
58
59
60
61
62
63
64
65
use crate::sys::Timer;
use futures::{try_ready, Async, Poll, Stream};
use std::io;
use std::time::Duration;

/// A stream that yields once every time a fixed amount of time elapses.
///
/// Instances of `Interval` perform no work.
pub struct Interval {
    e: Option<tokio_reactor::PollEvented<Timer>>,
}

impl Interval {
    /// Create a new `Interval` instance that yields at now + `interval`, and every subsequent
    /// `interval`.
    pub fn new(interval: Duration) -> io::Result<Self> {
        if interval.as_secs() == 0 && interval.subsec_nanos() == 0 {
            // this would be interpreted as "inactive timer" by timerfd_settime
            return Ok(Self { e: None });
        }

        let mut timer = tokio_reactor::PollEvented::new(Timer::new()?);

        // arm the timer
        timer.get_mut().set(libc::itimerspec {
            // first expiry
            it_value: libc::timespec {
                tv_sec: interval.as_secs() as i64,
                tv_nsec: i64::from(interval.subsec_nanos()),
            },
            // subsequent expiry intervals
            it_interval: libc::timespec {
                tv_sec: interval.as_secs() as i64,
                tv_nsec: i64::from(interval.subsec_nanos()),
            },
        })?;

        Ok(Self { e: Some(timer) })
    }
}

impl Stream for Interval {
    type Item = ();
    type Error = io::Error;
    fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
        if self.e.is_none() {
            return Ok(Async::Ready(Some(())));
        }

        let ready = mio::Ready::readable();
        try_ready!(self.e.as_mut().unwrap().poll_read_ready(ready));

        // do a read to reset
        match self.e.as_mut().unwrap().get_mut().check() {
            Ok(_) => Ok(Async::Ready(Some(()))),
            Err(e) => {
                if e.kind() == io::ErrorKind::WouldBlock {
                    self.e.as_mut().unwrap().clear_read_ready(ready)?;
                    return Ok(Async::NotReady);
                }
                Err(e)
            }
        }
    }
}