Created
July 28, 2017 22:07
-
-
Save cameronp98/2d8c70cfba457996c016978f22fd98d1 to your computer and use it in GitHub Desktop.
Example worker FSM in rust
This file contains hidden or 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 worker; | |
| use worker::Worker; | |
| fn main() { | |
| let worker = Worker::new() | |
| .initialize() | |
| .do_work() | |
| .reset(); | |
| println!("{:?}", worker); | |
| } |
This file contains hidden or 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
| #[derive(Debug)] | |
| pub struct Worker<S> { | |
| progress: Option<bool>, | |
| state: S, | |
| } | |
| #[derive(Debug)] | |
| struct Waiting; | |
| impl Worker<Waiting> { | |
| pub fn new() -> Self { | |
| Worker { | |
| progress: None, | |
| state: Waiting, | |
| } | |
| } | |
| pub fn initialize(self) -> Worker<Working> { | |
| println!("{:?} - Initializing", self); | |
| Worker { | |
| progress: Some(false), | |
| state: Working, | |
| } | |
| } | |
| } | |
| #[derive(Debug)] | |
| struct Working; | |
| impl Worker<Working> { | |
| pub fn do_work(self) -> Worker<Finished> { | |
| println!("{:?} - Doing work", self); | |
| Worker { | |
| progress: Some(true), | |
| state: Finished, | |
| } | |
| } | |
| } | |
| #[derive(Debug)] | |
| struct Finished; | |
| impl Worker<Finished> { | |
| pub fn reset(self) -> Worker<Waiting> { | |
| println!("{:?} - Resetting", self); | |
| Worker { | |
| progress: None, | |
| state: Waiting, | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment