1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#![feature(generator_trait)]

use std::collections::LinkedList;
use std::{
    ops::{Generator, GeneratorState},
    pin::Pin,
};

#[cfg(feature = "rayon")]
use rayon::prelude::*;

/// A wrapper struct around Generators,
/// providing a safe implementation of the [`Iterator`] trait.
pub struct YieldIter<G>(G);

impl<G> Unpin for YieldIter<G> {}

impl<G: Generator + Unpin> YieldIter<G> {
    /// Creates a new `GenIter` instance from a generator.
    /// The returned instance can be iterated over,
    /// consuming the generator.
    #[inline]
    pub fn new(generator: G) -> Self {
        Self(generator)
    }
}

impl<G: Generator + Unpin> Iterator for YieldIter<G> {
    type Item = G::Yield;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        Pin::new(self).next()
    }
}

impl<G: Generator + Unpin> YieldIter<G> {
    /// Creates a new `GenIter` instance from a generator.
    ///
    /// The returned instance can be iterated over,
    /// consuming the generator.
    ///
    /// # Safety
    /// This function is marked unsafe,
    /// because the caller must ensure the generator is in a valid state.
    /// A valid state means that the generator has not been moved ever since it's creation.
    #[inline]
    pub unsafe fn new_unchecked(generator: G) -> Self {
        Self(generator)
    }
}

impl<G: Generator> Iterator for Pin<&mut YieldIter<G>> {
    type Item = G::Yield;

    fn next(&mut self) -> Option<Self::Item> {
        let this: Pin<&mut YieldIter<G>> = self.as_mut();

        // This should be safe.
        // this Iterator implementation is on a Pin<&mut GenIter<G>> where G: Generator.
        // In order to acquire such a Pin<&mut YieldIter<G>> if G does *NOT* implement Unpin,
        // the unsafe `new_unchecked` function from the Pin type must be used anyway.
        //
        // Note that if G: Unpin, the Iterator implementation of YieldIter<G> itself is used,
        // which just creates a Pin safely, and then delegates to this implementation.
        let gen = unsafe { this.map_unchecked_mut(|gen| &mut gen.0) };

        match gen.resume(()) {
            GeneratorState::Yielded(y) => Some(y),
            GeneratorState::Complete(_) => None,
        }
    }
}

#[cfg(feature = "rayon")]
impl<G> IntoParallelIterator for YieldIter<G>
where
    G: Generator + Unpin,
    G::Yield: Sync + Send,
{
    type Iter = rayon::vec::IntoIter<Self::Item>;
    type Item = G::Yield;

    fn into_par_iter(self) -> Self::Iter {
        Vec::from_iter(self).into_par_iter()
    }
}

/// Create `YieldIter` with the provided generator body
/// # Examples
/// ```
/// #![feature(generators, generator_trait)]
///
/// use yield_iter::generator;
///
/// let x = 10;
/// let iter = generator! {
///     let r = &x;
///
///     for i in 0..5u32 {
///         yield i * *r
///     }
/// };
/// ```
#[macro_export]
macro_rules! generator {
    ($($x:tt)*) => {
        // SAFETY: Generator is directly passed into new_unchecked,
        // so it has not been moved
        unsafe {
            $crate::YieldIter::new_unchecked(|| {
                $($x)*
            })
        }//.fuse()
    };
}