1use std::collections::HashMap;
4
5use crate::server::connection::ConnectionId;
6
7#[derive(Debug)]
9pub struct StateMachine<S: Clone> {
10 states: HashMap<ConnectionId, S>,
12 default_state: S,
14}
15
16impl<S: Clone> StateMachine<S> {
17 pub fn new(default_state: S) -> Self {
19 Self {
20 states: HashMap::new(),
21 default_state,
22 }
23 }
24
25 pub fn get_state(&self, connection_id: ConnectionId) -> S {
27 self.states
28 .get(&connection_id)
29 .cloned()
30 .unwrap_or_else(|| self.default_state.clone())
31 }
32
33 pub fn set_state(&mut self, connection_id: ConnectionId, state: S) {
35 self.states.insert(connection_id, state);
36 }
37
38 pub fn remove_state(&mut self, connection_id: ConnectionId) {
40 self.states.remove(&connection_id);
41 }
42
43 pub fn reset_state(&mut self, connection_id: ConnectionId) {
45 self.states
46 .insert(connection_id, self.default_state.clone());
47 }
48
49 pub fn len(&self) -> usize {
51 self.states.len()
52 }
53
54 pub fn is_empty(&self) -> bool {
56 self.states.is_empty()
57 }
58}