1use crate::{EResult, Error};
2use std::time::Duration;
3use std::time::Instant;
4
5pub struct Op {
6 t: Instant,
7 timeout: Duration,
8}
9
10impl Op {
11 #[inline]
12 pub fn new(timeout: Duration) -> Self {
13 Self {
14 t: Instant::now(),
15 timeout,
16 }
17 }
18 #[inline]
19 pub fn for_instant(t: Instant, timeout: Duration) -> Self {
20 Self { t, timeout }
21 }
22 pub fn is_timed_out(&self) -> bool {
23 let el = self.t.elapsed();
24 el > self.timeout
25 }
26 pub fn timeout(&self) -> EResult<Duration> {
27 let el = self.t.elapsed();
28 if el > self.timeout {
29 Err(Error::timeout())
30 } else {
31 Ok(self.timeout - el)
32 }
33 }
34 #[inline]
35 pub fn is_enough(&self, expected: Duration) -> bool {
36 self.t.elapsed() + expected < self.timeout
37 }
38 #[inline]
39 pub fn enough(&self, expected: Duration) -> EResult<()> {
40 if self.is_enough(expected) {
41 Ok(())
42 } else {
43 Err(Error::timeout())
44 }
45 }
46 #[inline]
47 pub fn remaining(&self, timeout: Duration) -> EResult<Duration> {
48 let el = self.t.elapsed();
49 if el > timeout {
50 Err(Error::timeout())
51 } else {
52 Ok(timeout - el)
53 }
54 }
55}