use std::io;
use std::time::{Duration, Instant};
use futures::{Future, Poll, Async};
use reactor::{Remote, Handle};
use reactor::timeout_token::TimeoutToken;
#[must_use = "futures do nothing unless polled"]
#[derive(Debug)]
pub struct Timeout {
token: TimeoutToken,
when: Instant,
handle: Remote,
}
impl Timeout {
pub fn new(dur: Duration, handle: &Handle) -> io::Result<Timeout> {
Timeout::new_at(Instant::now() + dur, handle)
}
pub fn new_at(at: Instant, handle: &Handle) -> io::Result<Timeout> {
Ok(Timeout {
token: try!(TimeoutToken::new(at, &handle)),
when: at,
handle: handle.remote().clone(),
})
}
pub fn reset(&mut self, at: Instant) {
self.when = at;
self.token.reset_timeout(self.when, &self.handle);
}
fn poll_at(&mut self, now: Instant) -> Poll<(), io::Error> {
if self.when <= now {
Ok(Async::Ready(()))
} else {
self.token.update_timeout(&self.handle);
Ok(Async::NotReady)
}
}
}
impl Future for Timeout {
type Item = ();
type Error = io::Error;
fn poll(&mut self) -> Poll<(), io::Error> {
self.poll_at(Instant::now())
}
}
impl Drop for Timeout {
fn drop(&mut self) {
self.token.cancel_timeout(&self.handle);
}
}