From d4b7c427c90e59aea46a8f914e0895249183afc5 Mon Sep 17 00:00:00 2001 From: whitequark Date: Sat, 13 Aug 2016 00:07:08 +0000 Subject: [PATCH] impl Iterator for Generator. --- src/generator.rs | 23 +++++++++++++++++++++++ tests/iterator.rs | 18 ++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 tests/iterator.rs diff --git a/src/generator.rs b/src/generator.rs index 4ddcbff..c181df0 100644 --- a/src/generator.rs +++ b/src/generator.rs @@ -42,6 +42,8 @@ pub enum State { /// the state is `State::Runnable` after creation and suspension, and `State::Unavailable` /// once the generator function returns or panics. /// +/// When the input type is `()`, a generator implements the Iterator trait. +/// /// # Example /// /// ``` @@ -58,6 +60,20 @@ pub enum State { /// println!("{:?}", add_one.resume(3)); // prints Some(4) /// println!("{:?}", add_one.resume(0)); // prints None /// ``` +/// +/// # Iterator example +/// +/// ``` +/// use fringe::{OsStack, Generator}; +/// +/// let stack = OsStack::new(0).unwrap(); +/// let mut nat = Generator::new(stack, move |yielder, ()| { +/// for i in 1.. { yielder.generate(i) } +/// }); +/// println!("{:?}", nat.next()); // prints Some(0) +/// println!("{:?}", nat.next()); // prints Some(1) +/// println!("{:?}", nat.next()); // prints Some(2) +/// ``` #[derive(Debug)] pub struct Generator { state: State, @@ -199,3 +215,10 @@ impl Yielder self.generate_bare(Some(item)) } } + +impl Iterator for Generator<(), Output, Stack> + where Output: Send, Stack: stack::Stack { + type Item = Output; + + fn next(&mut self) -> Option { self.resume(()) } +} diff --git a/tests/iterator.rs b/tests/iterator.rs new file mode 100644 index 0000000..53620d4 --- /dev/null +++ b/tests/iterator.rs @@ -0,0 +1,18 @@ +// This file is part of libfringe, a low-level green threading library. +// Copyright (c) whitequark +// See the LICENSE file included in this distribution. +extern crate fringe; + +use fringe::OsStack; +use fringe::generator::Generator; + +#[test] +fn producer() { + let stack = OsStack::new(0).unwrap(); + let mut gen = Generator::new(stack, move |yielder, ()| { + for i in 0.. { yielder.generate(i) } + }); + assert_eq!(gen.next(), Some(0)); + assert_eq!(gen.next(), Some(1)); + assert_eq!(gen.next(), Some(2)); +}