use std::time::{Duration, Instant};
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub enum Timeout {
DontBlock,
BlockUntil(Instant),
BlockIndefinitely,
}
impl Timeout {
pub fn block_for(duration: Duration) -> Self {
Self::BlockUntil(Instant::now() + duration)
}
pub fn block_for_millis(millis: u64) -> Self {
Self::block_for(Duration::from_millis(millis))
}
}
pub type BlockResult<T> = Result<T, TimedOut>;
#[derive(Debug, Clone, Copy, Ord, PartialOrd, Hash, Eq, PartialEq)]
pub struct TimedOut;
#[cfg(test)]
mod test {
use std::time::{Duration, Instant};
use crate::Timeout;
#[test]
fn ordering_is_correct() {
let now = Instant::now();
let in_the_future = Timeout::BlockUntil(now + Duration::from_secs(1));
let in_the_past = Timeout::BlockUntil(now - Duration::from_secs(1));
let mut timeouts = vec![
Timeout::BlockIndefinitely,
in_the_future,
in_the_past,
Timeout::DontBlock,
];
timeouts.sort();
assert_eq!(
timeouts,
vec![
Timeout::DontBlock,
in_the_past,
in_the_future,
Timeout::BlockIndefinitely,
]
);
}
}