1use crate::fmt;
2use crate::ops::{Coroutine, CoroutineState};
3use crate::pin::Pin;
4
5/// Creates a new iterator where each iteration calls the provided coroutine.
6///
7/// Similar to [`iter::from_fn`].
8///
9/// [`iter::from_fn`]: crate::iter::from_fn
10///
11/// # Examples
12///
13/// ```
14/// #![feature(coroutines)]
15/// #![feature(iter_from_coroutine)]
16///
17/// let it = std::iter::from_coroutine(#[cfg_attr(not(bootstrap), coroutine)] || {
18/// yield 1;
19/// yield 2;
20/// yield 3;
21/// });
22/// let v: Vec<_> = it.collect();
23/// assert_eq!(v, [1, 2, 3]);
24/// ```
25#[inline]
26#[unstable(feature = "iter_from_coroutine", issue = "43122", reason = "coroutines are unstable")]
27pub fn from_coroutine<G: Coroutine<Return = ()> + Unpin>(coroutine: G) -> FromCoroutine<G> {
28 FromCoroutine(coroutine)
29}
30
31/// An iterator over the values yielded by an underlying coroutine.
32///
33/// This `struct` is created by the [`iter::from_coroutine()`] function. See its documentation for
34/// more.
35///
36/// [`iter::from_coroutine()`]: from_coroutine
37#[unstable(feature = "iter_from_coroutine", issue = "43122", reason = "coroutines are unstable")]
38#[derive(Clone)]
39pub struct FromCoroutine<G>(G);
40
41#[unstable(feature = "iter_from_coroutine", issue = "43122", reason = "coroutines are unstable")]
42impl<G: Coroutine<Return = ()> + Unpin> Iterator for FromCoroutine<G> {
43 type Item = G::Yield;
44
45 fn next(&mut self) -> Option<Self::Item> {
46 match Pin::new(&mut self.0).resume(()) {
47 CoroutineState::Yielded(n: >::Yield) => Some(n),
48 CoroutineState::Complete(()) => None,
49 }
50 }
51}
52
53#[unstable(feature = "iter_from_coroutine", issue = "43122", reason = "coroutines are unstable")]
54impl<G> fmt::Debug for FromCoroutine<G> {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 f.debug_struct(name:"FromCoroutine").finish()
57 }
58}
59