2016-07-17 11:11:33 +08:00
|
|
|
// This file is part of libfringe, a low-level green threading library.
|
|
|
|
// Copyright (c) whitequark <whitequark@whitequark.org>
|
|
|
|
// See the LICENSE file included in this distribution.
|
|
|
|
extern crate fringe;
|
|
|
|
|
|
|
|
use fringe::OsStack;
|
|
|
|
use fringe::generator::Generator;
|
|
|
|
|
2016-08-12 05:04:40 +08:00
|
|
|
fn new_add_one() -> Generator<i32, i32, OsStack> {
|
2016-07-17 11:11:33 +08:00
|
|
|
let stack = OsStack::new(0).unwrap();
|
2016-08-12 05:04:40 +08:00
|
|
|
Generator::new(stack, move |yielder, mut input| {
|
|
|
|
loop {
|
|
|
|
if input == 0 { break }
|
|
|
|
input = yielder.generate(input + 1)
|
2016-07-17 11:11:33 +08:00
|
|
|
}
|
2016-08-12 05:04:40 +08:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn generator() {
|
|
|
|
let mut add_one = new_add_one();
|
|
|
|
assert_eq!(add_one.resume(1), Some(2));
|
|
|
|
assert_eq!(add_one.resume(2), Some(3));
|
|
|
|
assert_eq!(add_one.resume(0), None);
|
2016-07-17 11:11:33 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn move_after_new() {
|
2016-08-12 05:04:40 +08:00
|
|
|
let mut add_one = new_add_one();
|
|
|
|
assert_eq!(add_one.resume(1), Some(2));
|
2016-07-17 11:11:33 +08:00
|
|
|
|
|
|
|
#[inline(never)]
|
2016-08-12 05:04:40 +08:00
|
|
|
fn run_moved(mut add_one: Generator<i32, i32, OsStack>) {
|
|
|
|
assert_eq!(add_one.resume(2), Some(3));
|
|
|
|
assert_eq!(add_one.resume(3), Some(4));
|
|
|
|
assert_eq!(add_one.resume(0), None);
|
2016-07-17 11:11:33 +08:00
|
|
|
}
|
2016-08-12 05:04:40 +08:00
|
|
|
run_moved(add_one);
|
2016-07-17 11:11:33 +08:00
|
|
|
}
|
2016-08-11 10:16:13 +08:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
#[should_panic]
|
|
|
|
fn panic_safety() {
|
|
|
|
struct Wrapper {
|
2016-08-12 05:04:40 +08:00
|
|
|
gen: Generator<(), (), OsStack>
|
2016-08-11 10:16:13 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Drop for Wrapper {
|
|
|
|
fn drop(&mut self) {
|
2016-08-12 05:04:40 +08:00
|
|
|
self.gen.resume(());
|
2016-08-11 10:16:13 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let stack = OsStack::new(4 << 20).unwrap();
|
2016-08-12 05:04:40 +08:00
|
|
|
let gen = Generator::new(stack, move |_yielder, ()| {
|
2016-08-11 10:16:13 +08:00
|
|
|
panic!("foo")
|
|
|
|
});
|
|
|
|
|
|
|
|
let mut wrapper = Wrapper { gen: gen };
|
2016-08-12 05:04:40 +08:00
|
|
|
wrapper.gen.resume(());
|
2016-08-11 10:16:13 +08:00
|
|
|
}
|