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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
use pin_project::pin_project;

use super::{ConcurrentStream, Consumer};
use core::num::NonZeroUsize;
use core::{
    future::Future,
    marker::PhantomData,
    pin::Pin,
    task::{ready, Context, Poll},
};

/// Convert items from one type into another
#[derive(Debug)]
pub struct Map<CS, F, FutT, T, FutB, B>
where
    CS: ConcurrentStream<Item = T, Future = FutT>,
    F: Fn(T) -> FutB,
    F: Clone,
    FutT: Future<Output = T>,
    FutB: Future<Output = B>,
{
    inner: CS,
    f: F,
    _phantom: PhantomData<(FutT, T, FutB, B)>,
}

impl<CS, F, FutT, T, FutB, B> Map<CS, F, FutT, T, FutB, B>
where
    CS: ConcurrentStream<Item = T, Future = FutT>,
    F: Fn(T) -> FutB,
    F: Clone,
    FutT: Future<Output = T>,
    FutB: Future<Output = B>,
{
    pub(crate) fn new(inner: CS, f: F) -> Self {
        Self {
            inner,
            f,
            _phantom: PhantomData,
        }
    }
}

impl<CS, F, FutT, T, FutB, B> ConcurrentStream for Map<CS, F, FutT, T, FutB, B>
where
    CS: ConcurrentStream<Item = T, Future = FutT>,
    F: Fn(T) -> FutB,
    F: Clone,
    FutT: Future<Output = T>,
    FutB: Future<Output = B>,
{
    type Future = MapFuture<F, FutT, T, FutB, B>;
    type Item = B;

    async fn drive<C>(self, consumer: C) -> C::Output
    where
        C: Consumer<Self::Item, Self::Future>,
    {
        let consumer = MapConsumer {
            inner: consumer,
            f: self.f,
            _phantom: PhantomData,
        };
        self.inner.drive(consumer).await
    }

    fn concurrency_limit(&self) -> Option<NonZeroUsize> {
        self.inner.concurrency_limit()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

#[pin_project]
pub struct MapConsumer<C, F, FutT, T, FutB, B>
where
    FutT: Future<Output = T>,
    C: Consumer<B, MapFuture<F, FutT, T, FutB, B>>,
    F: Fn(T) -> FutB,
    F: Clone,
    FutB: Future<Output = B>,
{
    #[pin]
    inner: C,
    f: F,
    _phantom: PhantomData<(FutT, T, FutB, B)>,
}

impl<C, F, FutT, T, FutB, B> Consumer<T, FutT> for MapConsumer<C, F, FutT, T, FutB, B>
where
    FutT: Future<Output = T>,
    C: Consumer<B, MapFuture<F, FutT, T, FutB, B>>,
    F: Fn(T) -> FutB,
    F: Clone,
    FutB: Future<Output = B>,
{
    type Output = C::Output;

    async fn progress(self: Pin<&mut Self>) -> super::ConsumerState {
        let this = self.project();
        this.inner.progress().await
    }

    async fn send(self: Pin<&mut Self>, future: FutT) -> super::ConsumerState {
        let this = self.project();
        let fut = MapFuture::new(this.f.clone(), future);
        this.inner.send(fut).await
    }

    async fn flush(self: Pin<&mut Self>) -> Self::Output {
        let this = self.project();
        this.inner.flush().await
    }
}

/// Takes a future and maps it to another future via a closure
#[derive(Debug)]
pub struct MapFuture<F, FutT, T, FutB, B>
where
    FutT: Future<Output = T>,
    F: Fn(T) -> FutB,
    FutB: Future<Output = B>,
{
    done: bool,
    f: F,
    fut_t: Option<FutT>,
    fut_b: Option<FutB>,
}

impl<F, FutT, T, FutB, B> MapFuture<F, FutT, T, FutB, B>
where
    FutT: Future<Output = T>,
    F: Fn(T) -> FutB,
    FutB: Future<Output = B>,
{
    fn new(f: F, fut_t: FutT) -> Self {
        Self {
            done: false,
            f,
            fut_t: Some(fut_t),
            fut_b: None,
        }
    }
}

impl<F, FutT, T, FutB, B> Future for MapFuture<F, FutT, T, FutB, B>
where
    FutT: Future<Output = T>,
    F: Fn(T) -> FutB,
    FutB: Future<Output = B>,
{
    type Output = B;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        // SAFETY: we need to access the inner future's fields to project them
        let this = unsafe { self.get_unchecked_mut() };
        if this.done {
            panic!("future has already been polled to completion once");
        }

        // Poll forward the future containing the value of `T`
        if let Some(fut) = this.fut_t.as_mut() {
            // SAFETY: we're pin projecting here
            let t = ready!(unsafe { Pin::new_unchecked(fut) }.poll(cx));
            let fut_b = (this.f)(t);
            this.fut_t = None;
            this.fut_b = Some(fut_b);
        }

        // Poll forward the future returned by the closure
        if let Some(fut) = this.fut_b.as_mut() {
            // SAFETY: we're pin projecting here
            let t = ready!(unsafe { Pin::new_unchecked(fut) }.poll(cx));
            this.done = true;
            return Poll::Ready(t);
        }

        unreachable!("neither future `a` nor future `b` were ready");
    }
}