use std::io;
use std::time::{Duration, Instant};
use futures::{Future, Poll, Async};
use reactor::{Remote, Handle};
use reactor::timeout_token::TimeoutToken;
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(),
})
}
}
impl Future for Timeout {
type Item = ();
type Error = io::Error;
fn poll(&mut self) -> Poll<(), io::Error> {
let now = Instant::now();
if self.when <= now {
Ok(Async::Ready(()))
} else {
self.token.update_timeout(&self.handle);
Ok(Async::NotReady)
}
}
}
impl Drop for Timeout {
fn drop(&mut self) {
self.token.cancel_timeout(&self.handle);
}
}