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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
|
use genawaiter::rc::{Co, Gen};
use std::cell::RefCell;
use std::future::Future;
use std::pin::Pin;
use std::rc::Rc;
#[derive(Debug)]
enum ValueRepr {
Int(i64),
Thunk((i64, i64)),
}
#[derive(Clone, Debug)]
struct Value(Rc<RefCell<ValueRepr>>);
impl Value {
fn force(&self) {
let mut inner = self.0.borrow_mut();
match *inner {
ValueRepr::Int(_) => return,
ValueRepr::Thunk((a, b)) => {
*inner = ValueRepr::Int(a + b);
}
}
}
fn is_forced(&self) -> bool {
matches!(*self.0.borrow(), ValueRepr::Int(_))
}
fn int(&self) -> i64 {
match *self.0.borrow() {
ValueRepr::Int(i) => i,
ValueRepr::Thunk(_) => panic!("unforced thunk!"),
}
}
}
impl From<i64> for Value {
fn from(value: i64) -> Self {
Value(Rc::new(RefCell::new(ValueRepr::Int(value))))
}
}
impl From<(i64, i64)> for Value {
fn from(value: (i64, i64)) -> Self {
Value(Rc::new(RefCell::new(ValueRepr::Thunk(value))))
}
}
async fn list_maker(values: Vec<Value>, co: Co<Value>) -> Vec<i64> {
let mut output: Vec<i64> = vec![];
for value in values {
if !value.is_forced() {
co.yield_(value.clone()).await;
}
output.push(value.int());
}
output
}
async fn list_reverser(values: Vec<Value>, co: Co<Value>) -> Vec<i64> {
let mut output = list_maker(values, co).await;
output.reverse();
output
}
struct Frame {
gen: Gen<Value, (), Pin<Box<dyn Future<Output = Vec<i64>>>>>,
}
fn pin_future(
f: impl Future<Output = Vec<i64>> + 'static,
) -> Pin<Box<dyn Future<Output = Vec<i64>>>> {
Box::pin(f)
}
fn main() {
let mut frames: Vec<Frame> = vec![];
let values: Vec<Value> = vec![
42.into(),
(12, 54).into(),
4.into(),
(40, 2).into(),
2.into(),
];
let second = values.clone();
frames.push(Frame {
gen: Gen::new(|co| pin_future(list_maker(values, co))),
});
frames.push(Frame {
gen: Gen::new(|co| pin_future(list_reverser(second, co))),
});
for (idx, mut frame) in frames.into_iter().enumerate() {
loop {
match frame.gen.resume() {
genawaiter::GeneratorState::Yielded(val) => {
println!("yielded {:?} in frame {}", val, idx);
val.force();
}
genawaiter::GeneratorState::Complete(list) => {
println!("result {}: {:?}", idx, list);
break;
}
}
}
}
}
|