connpool/core/
timeouts.rs1#[derive(Debug, Clone, Copy, PartialEq)]
9pub enum Timeout {
10 Unset,
12 Infinite,
14 Of(f64),
16}
17
18impl Timeout {
19 pub fn from_option(seconds: Option<f64>) -> Self {
21 match seconds {
22 None => Timeout::Infinite,
23 Some(s) => Timeout::Of(s),
24 }
25 }
26
27 pub(crate) fn compute_deadline(self, default: Option<f64>, now: f64) -> Option<f64> {
30 match self {
31 Timeout::Unset => default.map(|d| now + d),
32 Timeout::Infinite => None,
33 Timeout::Of(s) => Some(now + s),
34 }
35 }
36}
37
38pub(crate) fn remaining(deadline: Option<f64>, now: f64) -> Option<f64> {
40 deadline.map(|d| d - now)
41}
42
43#[cfg(test)]
44mod tests {
45 use super::*;
46
47 #[test]
48 fn from_option_maps_none_to_infinite() {
49 assert_eq!(Timeout::from_option(None), Timeout::Infinite);
50 assert_eq!(Timeout::from_option(Some(3.0)), Timeout::Of(3.0));
51 }
52
53 #[test]
54 fn compute_deadline_covers_all_kinds() {
55 assert_eq!(Timeout::Unset.compute_deadline(Some(30.0), 100.0), Some(130.0));
57 assert_eq!(Timeout::Unset.compute_deadline(None, 100.0), None);
58 assert_eq!(Timeout::Infinite.compute_deadline(Some(30.0), 100.0), None);
60 assert_eq!(Timeout::Of(5.0).compute_deadline(None, 100.0), Some(105.0));
62 assert_eq!(Timeout::Of(0.0).compute_deadline(Some(30.0), 100.0), Some(100.0));
63 }
64
65 #[test]
66 fn remaining_math() {
67 assert_eq!(remaining(None, 100.0), None);
68 assert_eq!(remaining(Some(130.0), 100.0), Some(30.0));
69 assert_eq!(remaining(Some(100.0), 130.0), Some(-30.0));
70 let t = Timeout::Of(1.0);
72 assert_eq!(t, t.clone());
73 assert!(format!("{t:?}").contains("Of"));
74 }
75}