Last active
May 23, 2017 14:54
-
-
Save Lisoph/5a9d992b1ba0a4e8ff7b18f4233bdf6d to your computer and use it in GitHub Desktop.
This file contains 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
/* | |
#[yields] | |
fn foo(multi: i32) -> i32 { | |
let mut counter = 0i32; | |
yield 100; | |
println!("After yield 100!"); | |
counter += 1; | |
yield 200; | |
let aeiou = "Hello!"; | |
println!("{} We're done - {}", aeiou, counter); | |
yield counter * 4 * multi; | |
} | |
*/ | |
struct FooStack { | |
multi: i32, | |
counter: i32, | |
aeiou: &'static str, | |
} | |
struct YieldsFnFoo { | |
cur_state: Option<usize>, | |
stack: FooStack, | |
} | |
impl Iterator for YieldsFnFoo { | |
type Item = i32; | |
fn next(&mut self) -> Option<Self::Item> { | |
if let Some(cur_state) = self.cur_state { | |
let (next_state, res) = match cur_state { | |
0 => (Some(1), Some(100)), | |
1 => { | |
println!("After yield 100!"); | |
self.stack.counter += 1; | |
(Some(2), Some(200)) | |
}, | |
2 => { | |
self.stack.aeiou = "Hello!"; | |
println!("{} We're done - {}", self.stack.aeiou, self.stack.counter); | |
(None, Some(self.stack.counter * 4 * self.stack.multi)) | |
}, | |
_ => (None, None) | |
}; | |
self.cur_state = next_state; | |
res | |
} else { | |
None | |
} | |
} | |
} | |
fn foo(multi: i32) -> YieldsFnFoo { | |
YieldsFnFoo { | |
cur_state: Some(0), | |
stack: FooStack { | |
multi: multi, | |
counter: 0, | |
aeiou: unsafe { std::mem::uninitialized() }, | |
}, | |
} | |
} | |
fn main() { | |
for n in foo(1) { | |
println!("{}", n); | |
} | |
println!(); | |
for n in foo(10) { | |
println!("{}", n); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment