Last active
October 12, 2021 04:33
-
-
Save dcoles/479e257643b946e9009ab116fda1fa44 to your computer and use it in GitHub Desktop.
Dynamic Finite-State-Machine in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::fmt::Debug; | |
pub trait State: Debug { | |
fn execute(&self) -> Transition; | |
} | |
pub trait TransitionTo<S: State + 'static>: State { | |
fn transition_to(&self, to: &'static S) -> Transition { | |
Transition { to } | |
} | |
} | |
pub struct Transition { | |
to: &'static dyn State, | |
} | |
impl Transition { | |
pub fn to(&self) -> &'static dyn State { | |
self.to | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mod fsm; | |
use std::time::Duration; | |
use crate::fsm::{State, TransitionTo, Transition}; | |
#[derive(Debug)] | |
struct StateA; | |
#[derive(Debug)] | |
struct StateB; | |
impl State for StateA { | |
fn execute(&self) -> Transition { | |
self.transition_to(&StateB) | |
} | |
} | |
impl TransitionTo<StateB> for StateA {} | |
impl State for StateB { | |
fn execute(&self) -> Transition { | |
self.transition_to(&StateA) | |
} | |
} | |
impl TransitionTo<StateA> for StateB {} | |
fn main() { | |
let mut state: &dyn State = &StateA; | |
loop { | |
println!("{:?}", state); | |
std::thread::sleep(Duration::from_secs(1)); | |
let transition = state.execute(); | |
state = transition.to(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment