rust/tests/run-pass/generator.rs

81 lines
1.9 KiB
Rust
Raw Normal View History

2017-08-30 04:13:01 -05:00
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(generators, generator_trait)]
use std::ops::{GeneratorState, Generator};
2019-01-30 04:51:06 -06:00
use std::pin::Pin;
2017-08-30 04:13:01 -05:00
fn finish<T>(mut amt: usize, mut t: T) -> T::Return
2018-11-20 05:51:55 -06:00
where T: Generator<Yield = usize>
2017-08-30 04:13:01 -05:00
{
2019-01-30 04:51:06 -06:00
// We are not moving the `t` around until it gets dropped, so this is okay.
let mut t = unsafe { Pin::new_unchecked(&mut t) };
2017-08-30 04:13:01 -05:00
loop {
2019-01-30 04:51:06 -06:00
match t.as_mut().resume() {
2018-11-20 05:51:55 -06:00
GeneratorState::Yielded(y) => amt -= y,
2017-08-30 04:13:01 -05:00
GeneratorState::Complete(ret) => {
assert_eq!(amt, 0);
return ret
}
}
}
}
fn main() {
2018-11-20 05:51:55 -06:00
finish(1, || yield 1);
2017-08-30 04:13:01 -05:00
finish(3, || {
let mut x = 0;
2018-11-20 05:51:55 -06:00
yield 1;
2017-08-30 04:13:01 -05:00
x += 1;
2018-11-20 05:51:55 -06:00
yield 1;
2017-08-30 04:13:01 -05:00
x += 1;
2018-11-20 05:51:55 -06:00
yield 1;
2017-08-30 04:13:01 -05:00
assert_eq!(x, 2);
});
2018-11-20 05:51:55 -06:00
finish(7*8/2, || {
for i in 0..8 {
yield i;
2017-08-30 04:13:01 -05:00
}
});
finish(1, || {
if true {
2018-11-20 05:51:55 -06:00
yield 1;
2017-08-30 04:13:01 -05:00
} else {
}
});
finish(1, || {
if false {
} else {
2018-11-20 05:51:55 -06:00
yield 1;
2017-08-30 04:13:01 -05:00
}
});
finish(2, || {
2018-11-20 05:51:55 -06:00
if { yield 1; false } {
yield 1;
2017-08-30 04:13:01 -05:00
panic!()
}
2018-11-20 05:51:55 -06:00
yield 1;
2017-08-30 04:13:01 -05:00
});
2018-11-20 05:51:55 -06:00
// also test a self-referential generator
assert_eq!(
finish(5, || {
let mut x = Box::new(5);
let y = &mut *x;
*y = 5;
yield *y;
*y = 10;
*x
}),
10
);
2017-08-30 04:13:01 -05:00
}