use serde::{Deserialize, Serialize};
use std::str::FromStr;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BoothStateState {
Available,
Unavailable,
}
impl Default for BoothStateState {
fn default() -> Self {
Self::Available
}
}
impl std::fmt::Display for BoothStateState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Available => write!(f, "available"),
Self::Unavailable => write!(f, "unavailable"),
}
}
}
impl FromStr for BoothStateState {
type Err = StateMachineError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"available" => Ok(Self::Available),
"unavailable" => Ok(Self::Unavailable),
_ => Err(StateMachineError::InvalidState(s.to_string())),
}
}
}
impl BoothStateState {
pub fn is_initial(&self) -> bool {
matches!(self, Self::Available)
}
pub fn is_final(&self) -> bool {
matches!(self, Self::Unavailable)
}
pub fn all() -> Vec<Self> {
vec![
Self::Available,
Self::Unavailable,
]
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BoothStateTransition {
Confirm,
Release,
}
impl std::fmt::Display for BoothStateTransition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Confirm => write!(f, "confirm"),
Self::Release => write!(f, "release"),
}
}
}
impl FromStr for BoothStateTransition {
type Err = StateMachineError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"confirm" => Ok(Self::Confirm),
"release" => Ok(Self::Release),
_ => Err(StateMachineError::InvalidTransition(s.to_string())),
}
}
}
impl BoothStateTransition {
pub fn target_state(&self) -> BoothStateState {
match self {
Self::Confirm => BoothStateState::Unavailable,
Self::Release => BoothStateState::Available,
}
}
pub fn all() -> Vec<Self> {
vec![
Self::Confirm,
Self::Release,
]
}
pub fn allowed_roles(&self) -> &'static [&'static str] {
match self {
Self::Confirm => &[],
Self::Release => &[],
}
}
}
use super::StateMachineError;
#[derive(Debug, Clone)]
pub struct BoothStateStateMachine {
current_state: BoothStateState,
}
impl BoothStateStateMachine {
pub fn new() -> Self {
Self {
current_state: BoothStateState::default(),
}
}
pub fn from_state(state: BoothStateState) -> Self {
Self { current_state: state }
}
pub fn current_state(&self) -> BoothStateState {
self.current_state
}
pub fn can_transition(&self, transition: BoothStateTransition) -> bool {
if matches!(self.current_state, BoothStateState::Unavailable) {
return false;
}
match (self.current_state, transition) {
(_, BoothStateTransition::Confirm) => true,
(_, BoothStateTransition::Release) => true,
}
}
pub fn can_transition_with_role(&self, transition: BoothStateTransition, role: &str) -> bool {
if !self.can_transition(transition) {
return false;
}
let allowed_roles = transition.allowed_roles();
if allowed_roles.is_empty() {
return true; }
allowed_roles.iter().any(|r| *r == role || *r == "*")
}
pub fn transition(&mut self, transition: BoothStateTransition) -> Result<BoothStateState, StateMachineError> {
if !self.can_transition(transition) {
return Err(StateMachineError::TransitionNotAllowed {
transition: transition.to_string(),
from: self.current_state.to_string(),
});
}
self.current_state = transition.target_state();
Ok(self.current_state)
}
pub fn transition_with_role(&mut self, transition: BoothStateTransition, role: &str) -> Result<BoothStateState, StateMachineError> {
if !self.can_transition(transition) {
return Err(StateMachineError::TransitionNotAllowed {
transition: transition.to_string(),
from: self.current_state.to_string(),
});
}
if !self.can_transition_with_role(transition, role) {
return Err(StateMachineError::RoleNotAuthorized {
role: role.to_string(),
transition: transition.to_string(),
});
}
self.current_state = transition.target_state();
Ok(self.current_state)
}
pub fn available_transitions(&self) -> Vec<BoothStateTransition> {
BoothStateTransition::all()
.into_iter()
.filter(|t| self.can_transition(*t))
.collect()
}
pub fn available_transitions_for_role(&self, role: &str) -> Vec<BoothStateTransition> {
BoothStateTransition::all()
.into_iter()
.filter(|t| self.can_transition_with_role(*t, role))
.collect()
}
pub fn transition_to_state(&mut self, target: BoothStateState) -> Result<BoothStateState, StateMachineError> {
let valid = BoothStateTransition::all().into_iter()
.filter(|t| self.can_transition(*t))
.find(|t| t.target_state() == target);
match valid {
Some(t) => self.transition(t),
None => Err(StateMachineError::TransitionNotAllowed {
transition: target.to_string(),
from: self.current_state.to_string(),
}),
}
}
}
impl Default for BoothStateStateMachine {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_initial_state() {
let sm = BoothStateStateMachine::new();
assert_eq!(sm.current_state(), BoothStateState::Available);
assert!(sm.current_state().is_initial());
}
#[test]
fn test_valid_transition() {
let mut sm = BoothStateStateMachine::new();
assert!(sm.can_transition(BoothStateTransition::Confirm));
let result = sm.transition(BoothStateTransition::Confirm);
assert!(result.is_ok());
assert_eq!(sm.current_state(), BoothStateState::Unavailable);
}
#[test]
fn test_invalid_transition() {
assert!(true);
}
#[test]
fn test_state_parsing() {
let state: BoothStateState = "available".parse().unwrap();
assert_eq!(state, BoothStateState::Available);
}
#[test]
fn test_available_transitions() {
let sm = BoothStateStateMachine::new();
let available = sm.available_transitions();
assert!(!available.is_empty() || sm.current_state().is_final());
}
}