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
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#![deny(missing_docs)]

//! Crate that implements a timer with a `sleep` method that can be cancelled.
//!
//! # Example
//!
//! ```
//! use std::time::Duration;
//! use cancellable_timer::*;
//!
//! fn main() {
//!     let (mut timer, canceller) = Timer::new2().unwrap();
//!
//!     // Spawn a thread that will cancel the timer after 2s.
//!     std::thread::spawn(move || {
//!         std::thread::sleep(Duration::from_secs(2));
//!         println!("Stop the timer.");
//!         canceller.cancel();
//!     });
//!
//!     println!("Wait 10s");
//!     let r = timer.sleep(Duration::from_secs(10));
//!     println!("Done: {:?}", r);
//! }
//! ```

extern crate mio;

use std::io;
use std::time::Duration;

use mio::*;

/// A timer object that can be used to put the current thread to sleep
/// or to start a callback after a given amount of time.
pub struct Timer {
    poll: Poll,
    token: Token,
    _registration: Registration,
    events: Events,
}

/// An object that allows cancelling the associated [Timer](struct.Timer.html).
#[derive(Clone)]
pub struct Canceller {
    set_readiness: SetReadiness,
}

impl Timer {
    /// Create a [Timer](struct.Timer.html) and its associated [Canceller](struct.Canceller.html).
    pub fn new2() -> io::Result<(Self, Canceller)> {
        let poll = Poll::new()?;

        let token = Token(0);
        let (registration, set_readiness) = Registration::new2();
        poll.register(&registration, token, Ready::readable(), PollOpt::edge())?;

        Ok((
            Timer {
                poll,
                token,
                _registration: registration,
                events: Events::with_capacity(4),
            },
            Canceller { set_readiness },
        ))
    }

    /// Put the current thread to sleep until the given time has
    /// elapsed or the timer is cancelled.
    ///
    /// Returns:
    /// * Ok(()) if the given time has elapsed.
    /// * An [Error](https://docs.rust-lang.org/std/io/struct.Error.html)
    /// of kind [ErrorKind::Interrupted](https://docs.rust-lang.org/std/io/enum.ErrorKind.html)
    /// if the timer has been cancelled.
    /// * Some other [Error](https://docs.rust-lang.org/std/io/struct.Error.html)
    /// if something goes wrong.
    pub fn sleep(&mut self, duration: Duration) -> io::Result<()> {
        self.poll.poll(&mut self.events, Some(duration))?;
        for event in self.events.iter() {
            if event.token() == self.token {
                return Err(io::Error::new(
                    io::ErrorKind::Interrupted,
                    "timer cancelled",
                ));
            }
        }
        Ok(())
    }

    /// Run a callback on a new thread after a specified amount of time.
    /// The callback is not run if `after` returns an error.
    ///
    /// Otherwise, the callback is given:
    /// * Ok(()) if the amount of time has elapsed.
    /// * An [Error](https://docs.rust-lang.org/std/io/struct.Error.html)
    /// of kind [ErrorKind::Interrupted](https://docs.rust-lang.org/std/io/enum.ErrorKind.html)
    /// if the timer has been cancelled.
    /// * Some other [Error](https://docs.rust-lang.org/std/io/struct.Error.html)
    /// if something goes wrong.
    pub fn after<F>(wait: Duration, callback: F) -> io::Result<Canceller>
    where
        F: FnOnce(io::Result<()>),
        F: Send + 'static,
    {
        let (mut timer, canceller) = Timer::new2()?;
        std::thread::Builder::new().spawn(move || {
            callback(timer.sleep(wait));
        })?;
        Ok(canceller)
    }
}

impl Canceller {
    /// Cancel the associated [Timer](struct.Timer.html).
    pub fn cancel(&self) -> io::Result<()> {
        self.set_readiness.set_readiness(Ready::readable())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::thread;

    #[test]
    fn uninterrupted_sleep() {
        let (mut timer, _) = Timer::new2().unwrap();
        let r = timer.sleep(Duration::from_secs(1));
        assert!(r.is_ok());
    }

    #[test]
    fn cancel_before_sleep() {
        let (mut timer, canceller) = Timer::new2().unwrap();
        canceller.cancel().unwrap();
        let r = timer.sleep(Duration::from_secs(1));
        assert_eq!(r.unwrap_err().kind(), io::ErrorKind::Interrupted);
    }

    #[test]
    fn cancel_during_sleep() {
        let (mut timer, canceller) = Timer::new2().unwrap();
        thread::spawn(move || {
            thread::sleep(Duration::from_secs(2));
            canceller.cancel().unwrap();
        });
        let r = timer.sleep(Duration::from_secs(10));
        assert_eq!(r.unwrap_err().kind(), io::ErrorKind::Interrupted);
    }
}