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
//! Timeout specifiers and error types.
//!
//! See [Timeout](Timeout).
use std::time::{Duration, Instant};
/// A timeout (or lack thereof) describing how blocking operations should behave.
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub enum Timeout {
/// Disallows blocking for a contended resource.
DontBlock,
/// Allows blocking for a contended resource until the given time has passed.
BlockUntil(Instant),
/// Allows blocking for a contended resource indefinitely.
BlockIndefinitely,
}
impl Timeout {
/// Creates a new timeout that lasts for the provided duration, starting now.
///
/// # Example
///
/// ```
/// # use read_write_store::timeout::Timeout;
/// # use std::time::{Instant, Duration};
/// let first_timeout = Timeout::BlockUntil(Instant::now());
/// let second_timeout = Timeout::block_for(Duration::from_secs(1));
/// assert!(first_timeout < second_timeout);
/// ```
pub fn block_for(duration: Duration) -> Self {
Self::BlockUntil(Instant::now() + duration)
}
/// Creates a new timeout that lasts for the provided number of milliseconds, starting now.
///
/// # Example
///
/// ```
/// # use read_write_store::timeout::Timeout;
/// # use std::time::Instant;
/// let first_timeout = Timeout::BlockUntil(Instant::now());
/// let second_timeout = Timeout::block_for_millis(1000);
/// assert!(first_timeout < second_timeout);
/// ```
pub fn block_for_millis(millis: u64) -> Self {
Self::block_for(Duration::from_millis(millis))
}
}
/// A result which either succeeded, or failed due to a timeout.
pub type BlockResult<T> = Result<T, TimedOut>;
/// The value of the error alternative of [BlockResult](crate::BlockResult) that indicates a
/// timeout.
#[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,
]
);
}
}