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
43
44
45
46
47
48
49
50
51
/// Error returned when a state transition is not allowed
#[derive(Debug, Clone)]
pub struct TranstionNotAllowed;

/// Trait that must be implemented by state enumerations
pub trait State {
    fn transition_allowed(self, new_state: &Self) -> bool;
}

pub trait Feature<T: State> {
    fn allowed(self, state: &T) -> bool;
}

/// State machine
/// 
/// For an example look at the traffic lights test
#[derive(Clone, Copy)]
pub struct StateMachine<T> {
    state: T
}

impl<T: State + Copy> StateMachine<T> {
  /// Create a new state machine
  /// 
  /// # Arguments
  /// 
  /// * `state` - initial state
  pub fn new(state: T) -> StateMachine<T> {
    StateMachine {
      state: state
    }
  }

  pub fn feature_allowed<U: Feature<T> + Copy>(self, feature: &U) -> bool {
    feature.allowed(&self.state)
  }

  /// Starts a state transition
  /// 
  /// # Arguments
  /// 
  /// * `new_state` - try transtion to this state
  pub fn set(&mut self, new_state: &T) -> Result<(), TranstionNotAllowed> {
      if self.state.transition_allowed(&new_state) {
          self.state = *new_state;
          Ok(())
      } else {
          Err(TranstionNotAllowed {})
      }
  }
}