1use std::time::Duration;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum KeepAlive {
6 Timeout(Duration),
10
11 Os,
15
16 Disabled,
20}
21
22impl KeepAlive {
23 pub(crate) fn enabled(&self) -> bool {
24 !matches!(self, Self::Disabled)
25 }
26
27 #[allow(unused)] pub(crate) fn duration(&self) -> Option<Duration> {
29 match self {
30 KeepAlive::Timeout(dur) => Some(*dur),
31 _ => None,
32 }
33 }
34
35 pub(crate) fn normalize(self) -> KeepAlive {
37 match self {
38 KeepAlive::Timeout(Duration::ZERO) => KeepAlive::Disabled,
39 ka => ka,
40 }
41 }
42}
43
44impl Default for KeepAlive {
45 fn default() -> Self {
46 Self::Timeout(Duration::from_secs(5))
47 }
48}
49
50impl From<Duration> for KeepAlive {
51 fn from(dur: Duration) -> Self {
52 KeepAlive::Timeout(dur).normalize()
53 }
54}
55
56impl From<Option<Duration>> for KeepAlive {
57 fn from(ka_dur: Option<Duration>) -> Self {
58 match ka_dur {
59 Some(dur) => KeepAlive::from(dur),
60 None => KeepAlive::Disabled,
61 }
62 .normalize()
63 }
64}
65
66#[cfg(test)]
67mod tests {
68 use super::*;
69
70 #[test]
71 fn from_impls() {
72 let test: KeepAlive = Duration::from_secs(1).into();
73 assert_eq!(test, KeepAlive::Timeout(Duration::from_secs(1)));
74
75 let test: KeepAlive = Duration::from_secs(0).into();
76 assert_eq!(test, KeepAlive::Disabled);
77
78 let test: KeepAlive = Some(Duration::from_secs(0)).into();
79 assert_eq!(test, KeepAlive::Disabled);
80
81 let test: KeepAlive = None.into();
82 assert_eq!(test, KeepAlive::Disabled);
83 }
84}