Skip to content

Instantly share code, notes, and snippets.

@scorbeil
Created June 9, 2017 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scorbeil/7081a597e7453e632a59ccf9db78d023 to your computer and use it in GitHub Desktop.
Save scorbeil/7081a597e7453e632a59ccf9db78d023 to your computer and use it in GitHub Desktop.
The trait defines a state machine and the FSM enum is a reference implementation. This does not compile.
use ::state;
pub trait Machine {
type C;
type O;
fn run(&mut self, &mut Self::C) -> Option<Self::O>;
}
pub enum FSM<C, S, O> where S: state::State<C=C, R=(Option<S>, Option<O>)> {
State(S),
Output(O),
Both(S, O),
Nothing,
}
impl<C, S, O> Machine for FSM<C, S, O> where S: state::State<C=C, R=(Option<S>, Option<O>)> {
type C = C;
type O = O;
fn run(&mut self, c: &mut Self::C) -> Option<Self::O> {
loop {
match *self {
FSM::State(ref mut s) => {
let (os, oo) = s.step(c);
match os {
Some(s) => self = &mut FSM::State(s),
None => self = &mut FSM::Nothing,
}
if let Some(o) = oo {
return Some(o);
}
}
FSM::Output(ref mut o) => {
self = &mut FSM::Nothing;
return Some(*o);
}
FSM::Both(ref mut s, ref mut o) => {
self = &mut FSM::State(*s);
return Some(*o);
}
FSM::Nothing => return None,
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment