Skip to content

Instantly share code, notes, and snippets.

@badboy
Forked from rust-play/playground.rs
Created December 12, 2018 19:13
Show Gist options
  • Save badboy/b5ed1765c61077a202c407cfc7ebb698 to your computer and use it in GitHub Desktop.
Save badboy/b5ed1765c61077a202c407cfc7ebb698 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
trait StateSet {
fn next(self) -> (u32, Self);
}
trait State {
type S: StateSet;
fn next(self) -> (u32, Self::S);
}
macro_rules! delegate {
($fn:ident => enum $name:ident { $($variant:tt,)*}) => {
#[derive(Debug)]
enum $name {
$($variant($variant),)+
}
impl StateSet for $name {
fn next(self) -> (u32, Self) {
match self {
$(
$name::$variant(e) => e.$fn(),
)+
}
}
}
}
}
#[derive(Debug)]
struct First(u32);
#[derive(Debug)]
struct Second;
#[derive(Debug)]
struct Third;
impl State for First {
type S = SMTP;
fn next(self) -> (u32, Self::S) {
(self.0 + 1, SMTP::Second(Second))
}
}
impl State for Second {
type S = SMTP;
fn next(self) -> (u32, Self::S) {
(2, SMTP::Third(Third))
}
}
impl State for Third {
type S = SMTP;
fn next(self) -> (u32, Self::S) {
(3, SMTP::First(First(4)))
}
}
delegate!{next =>
enum SMTP {
First,
Second,
Third,
}
}
fn main() {
let machine = SMTP::First(First(0));
let (n, machine) = machine.next();
println!("{:?}", (n, &machine));
let (n, machine) = machine.next();
println!("{:?}", (n, &machine));
let (n, machine) = machine.next();
println!("{:?}", (n, &machine));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment