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
extern crate rand;
pub use std::time::{Duration, Instant};
pub struct Timeout {
created_at: Instant,
expires_after: Duration,
}
impl Timeout {
pub fn new(t: Duration) -> Self {
Timeout {
created_at: Instant::now(),
expires_after: t,
}
}
pub fn new_rand(min: Duration, max: Duration) -> Self {
use rand::distributions::{IndependentSample, Range};
let mut rng = rand::thread_rng();
let secs = Range::new(min.as_secs(), max.as_secs()).ind_sample(&mut rng);
let subsecs = Range::new(min.subsec_nanos(), max.subsec_nanos()).ind_sample(&mut rng);
Timeout {
created_at: Instant::now(),
expires_after: Duration::new(secs, subsecs),
}
}
pub fn refresh(&mut self) {
self.created_at = Instant::now();
}
pub fn expired(&self) -> bool {
self.created_at.duration_since(Instant::now()) > self.expires_after
}
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {}
}