timeout/
lib.rs

1// Copyright (c) 2017 Jeremy Rubin
2// This Source Code Form is subject to the terms of the Mozilla Public
3// License, v. 2.0. If a copy of the MPL was not distributed with this
4// file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
6extern crate rand;
7
8pub use std::time::{Duration, Instant};
9pub struct Timeout {
10    created_at: Instant,
11    expires_after: Duration,
12}
13impl Timeout {
14    pub fn new(t: Duration) -> Self {
15        Timeout {
16            created_at: Instant::now(),
17            expires_after: t,
18        }
19    }
20    pub fn new_rand(min: Duration, max: Duration) -> Self {
21        use rand::distributions::{IndependentSample, Range};
22        let mut rng = rand::thread_rng();
23        let secs = Range::new(min.as_secs(), max.as_secs()).ind_sample(&mut rng);
24        let subsecs = Range::new(min.subsec_nanos(), max.subsec_nanos()).ind_sample(&mut rng);
25        Timeout {
26            created_at: Instant::now(),
27            expires_after: Duration::new(secs, subsecs),
28        }
29
30
31    }
32    pub fn refresh(&mut self) {
33        self.created_at = Instant::now();
34    }
35    pub fn expired(&self) -> bool {
36        self.created_at.duration_since(Instant::now()) > self.expires_after
37    }
38}
39#[cfg(test)]
40mod tests {
41    #[test]
42    fn it_works() {}
43}