use std::time::Duration;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Timeout {
pub(crate) value: Duration,
}
impl Default for Timeout {
fn default() -> Self {
Self {
value: Duration::from_secs(5),
}
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum TimeoutRangeError {
TooSmall(Duration),
TooLarge(Duration),
}
impl Timeout {
pub const MIN: Duration = Duration::from_millis(1);
pub const MAX: Duration = Duration::from_secs(60 * 60);
pub fn from_secs(x: u64) -> Result<Self, TimeoutRangeError> {
Self::from_duration(Duration::from_secs(x))
}
pub fn from_millis(x: u64) -> Result<Self, TimeoutRangeError> {
Self::from_duration(Duration::from_millis(x))
}
pub fn from_duration(value: Duration) -> Result<Self, TimeoutRangeError> {
if value < Self::MIN {
return Err(TimeoutRangeError::TooSmall(value));
}
if value > Self::MAX {
return Err(TimeoutRangeError::TooLarge(value));
}
Ok(Self { value })
}
pub(crate) fn deadline_from_now(self) -> tokio::time::Instant {
tokio::time::Instant::now() + self.value
}
}
impl std::fmt::Display for Timeout {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{} ms", self.value.as_millis())
}
}
impl std::fmt::Display for TimeoutRangeError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
TimeoutRangeError::TooSmall(x) => write!(
f,
"specified duration ({} ms) smaller than allowed library minimum ({} ms)",
x.as_millis(),
Timeout::MIN.as_millis()
),
TimeoutRangeError::TooLarge(x) => write!(
f,
"specified duration ({} ms) larger than allowed library maximum ({} ms)",
x.as_millis(),
Timeout::MAX.as_millis()
),
}
}
}
impl std::error::Error for TimeoutRangeError {}