port_plumber/
connections_counter.rs1use std::time::SystemTime;
2
3enum CounterState {
4    HasConnections { count: usize },
5    NoConnections { since: SystemTime },
6}
7
8pub struct ConnectionCounter {
9    state: CounterState,
10}
11
12impl ConnectionCounter {
13    pub fn new() -> Self {
14        Self {
15            state: CounterState::NoConnections { since: SystemTime::now() },
16        }
17    }
18
19    pub fn add_connection(&mut self) {
20        self.state = match self.state {
21            CounterState::HasConnections { count } => CounterState::HasConnections { count: count + 1 },
22            CounterState::NoConnections { .. } => CounterState::HasConnections { count: 1 },
23        }
24    }
25
26    pub fn rem_connection(&mut self) {
27        self.state = match self.state {
28            CounterState::HasConnections { count } if count > 1 => CounterState::HasConnections { count: count - 1 },
29            CounterState::HasConnections { .. } => CounterState::NoConnections { since: SystemTime::now() },
30            CounterState::NoConnections { .. } => panic!("Trying to remove connections but no one was found"),
31        }
32    }
33
34    pub fn no_connections_since(&self) -> Option<SystemTime> {
35        match &self.state {
36            CounterState::HasConnections { .. } => None,
37            CounterState::NoConnections { since } => Some(*since),
38        }
39    }
40}
41