eva_common/
op.rs

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
use crate::{EResult, Error};
use std::time::Duration;
use std::time::Instant;

pub struct Op {
    t: Instant,
    timeout: Duration,
}

impl Op {
    #[inline]
    pub fn new(timeout: Duration) -> Self {
        Self {
            t: Instant::now(),
            timeout,
        }
    }
    #[inline]
    pub fn for_instant(t: Instant, timeout: Duration) -> Self {
        Self { t, timeout }
    }
    pub fn is_timed_out(&self) -> bool {
        let el = self.t.elapsed();
        el > self.timeout
    }
    pub fn timeout(&self) -> EResult<Duration> {
        let el = self.t.elapsed();
        if el > self.timeout {
            Err(Error::timeout())
        } else {
            Ok(self.timeout - el)
        }
    }
    #[inline]
    pub fn is_enough(&self, expected: Duration) -> bool {
        self.t.elapsed() + expected < self.timeout
    }
    #[inline]
    pub fn enough(&self, expected: Duration) -> EResult<()> {
        if self.is_enough(expected) {
            Ok(())
        } else {
            Err(Error::timeout())
        }
    }
    #[inline]
    pub fn remaining(&self, timeout: Duration) -> EResult<Duration> {
        let el = self.t.elapsed();
        if el > timeout {
            Err(Error::timeout())
        } else {
            Ok(timeout - el)
        }
    }
}