Created
February 19, 2019 10:03
-
-
Save sunwayforever/335c9e6d0c4f456e0343d2970d91a51b to your computer and use it in GitHub Desktop.
generator to iterator
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
#![feature(generators, generator_trait)] | |
use std::ops::GeneratorState; | |
use std::pin::Pin; | |
fn generator_to_iterator<G>(g: G) -> impl Iterator<Item = G::Yield> | |
where | |
G: std::marker::Unpin + std::ops::Generator, | |
{ | |
struct GeneratorIter<G>(G); | |
impl<G> Iterator for GeneratorIter<G> | |
where | |
G: std::marker::Unpin + std::ops::Generator, | |
{ | |
type Item = G::Yield; | |
fn next(&mut self) -> Option<Self::Item> { | |
match Pin::new(&mut self.0).resume() { | |
GeneratorState::Yielded(x) => return Some(x), | |
_ => None, | |
} | |
} | |
} | |
GeneratorIter(g) | |
} | |
fn main() { | |
let iter = generator_to_iterator(|| { | |
for i in 0..10 { | |
yield i*i; | |
} | |
}); | |
for i in iter { | |
println!("{:?}", i); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment