-
Notifications
You must be signed in to change notification settings - Fork 1
/
async_in_rust_34_fsm.rs
85 lines (75 loc) · 1.79 KB
/
async_in_rust_34_fsm.rs
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#![feature(generators, generator_trait)]
use std::pin::Pin;
use std::ops::{Generator, GeneratorState};
/*
fn main() {
let mut gen = || {
yield 1;
yield 2;
()
};
loop {
match Pin::new(&mut gen).resume(()) {
GeneratorState::Yielded(y) => println!("Yielded: {}", y),
GeneratorState::Complete(c) => {
println!("Complete: {:?}", c);
break;
}
}
}
}
*/
fn main() {
let mut gen = Gen::new();
loop {
match Pin::new(&mut gen).resume(()) {
GeneratorState::Yielded(y) => println!("Yielded: {}", y),
GeneratorState::Complete(c) => {
println!("Complete: {:?}", c);
break;
}
}
}
}
enum Gen {
Enter,
State1(State1),
State2(State2),
Exit
}
struct State1 {
_x: i32
}
struct State2 {
_x: i32
}
impl<R> Generator<R> for Gen {
type Yield = i32;
type Return = ();
fn resume(self: Pin<&mut Self>, _arg: R) -> GeneratorState<Self::Yield, Self::Return> {
let mut_gen = self.get_mut();
match std::mem::replace(mut_gen, Gen::Exit) {
Gen::Enter => {
// do works
*mut_gen = Gen::State1(State1 { _x: 1 });
GeneratorState::Yielded(1)
}
Gen::State1(_) => {
// do works
*mut_gen = Gen::State2(State2 { _x: 2 });
GeneratorState::Yielded(2)
}
Gen::State2(_) => {
// do works
*mut_gen = Gen::Exit;
GeneratorState::Complete(())
}
Gen::Exit => panic!("Generator has been completed.")
}
}
}
impl Gen {
fn new() -> Self {
Self::Enter
}
}