Skip to main content

netget/state/
machine.rs

1//! Protocol state machine management
2
3use std::collections::HashMap;
4
5use crate::server::connection::ConnectionId;
6
7/// Generic state machine for protocol handling
8#[derive(Debug)]
9pub struct StateMachine<S: Clone> {
10    /// Per-connection state
11    states: HashMap<ConnectionId, S>,
12    /// Default/initial state
13    default_state: S,
14}
15
16impl<S: Clone> StateMachine<S> {
17    /// Create a new state machine with a default state
18    pub fn new(default_state: S) -> Self {
19        Self {
20            states: HashMap::new(),
21            default_state,
22        }
23    }
24
25    /// Get the state for a connection
26    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    /// Set the state for a connection
34    pub fn set_state(&mut self, connection_id: ConnectionId, state: S) {
35        self.states.insert(connection_id, state);
36    }
37
38    /// Remove state for a connection (when disconnected)
39    pub fn remove_state(&mut self, connection_id: ConnectionId) {
40        self.states.remove(&connection_id);
41    }
42
43    /// Reset a connection to the default state
44    pub fn reset_state(&mut self, connection_id: ConnectionId) {
45        self.states
46            .insert(connection_id, self.default_state.clone());
47    }
48
49    /// Get the number of active states
50    pub fn len(&self) -> usize {
51        self.states.len()
52    }
53
54    /// Check if there are any active states
55    pub fn is_empty(&self) -> bool {
56        self.states.is_empty()
57    }
58}