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
91
92
93
94
use std::time::Duration;
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Timeout {
value: Duration,
}
impl Default for Timeout {
fn default() -> Self {
Self {
value: Duration::from_secs(5),
}
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum RangeError {
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, RangeError> {
Self::from_duration(Duration::from_secs(x))
}
pub fn from_millis(x: u64) -> Result<Self, RangeError> {
Self::from_duration(Duration::from_millis(x))
}
pub fn from_duration(value: Duration) -> Result<Self, RangeError> {
if value < Self::MIN {
return Err(RangeError::TooSmall(value));
}
if value > Self::MAX {
return Err(RangeError::TooLarge(value));
}
Ok(Self { value })
}
pub(crate) fn deadline_from_now(self) -> crate::tokio::time::Instant {
crate::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 RangeError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
RangeError::TooSmall(x) => write!(
f,
"specified duration ({} ms) smaller than allowed library minimum ({} ms)",
x.as_millis(),
Timeout::MIN.as_millis()
),
RangeError::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 RangeError {}