-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstate_machine.ov
More file actions
42 lines (37 loc) · 1.53 KB
/
Copy pathstate_machine.ov
File metadata and controls
42 lines (37 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
module tcp_state_machine
// A simplified TCP-like connection state machine.
// Demonstrates: enum with bare variants, exhaustive match on tuple patterns.
enum ConnectionState {
Closed,
Listen,
SynSent,
SynReceived,
Established,
FinWait,
}
enum Event {
ActiveOpen,
PassiveOpen,
SynAckReceived,
AckReceived,
Close,
}
@derive(Debug, Display)
enum TransitionError {
InvalidTransition { from: ConnectionState, event: Event },
}
// Pure function — no effect marker.
// Exhaustive pattern matching: the compiler checks every (state, event)
// pair is handled, or that a wildcard arm covers the rest.
fn transition(state: ConnectionState, event: Event) -> Result<ConnectionState, TransitionError> {
match (state, event) {
(ConnectionState.Closed, Event.ActiveOpen) => Ok(ConnectionState.SynSent),
(ConnectionState.Closed, Event.PassiveOpen) => Ok(ConnectionState.Listen),
(ConnectionState.Listen, Event.SynAckReceived) => Ok(ConnectionState.SynReceived),
(ConnectionState.SynSent, Event.SynAckReceived) => Ok(ConnectionState.Established),
(ConnectionState.SynReceived, Event.AckReceived) => Ok(ConnectionState.Established),
(ConnectionState.Established, Event.Close) => Ok(ConnectionState.FinWait),
(ConnectionState.FinWait, Event.AckReceived) => Ok(ConnectionState.Closed),
_ => Err(TransitionError.InvalidTransition { from = state, event = event }),
}
}