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
183
184
185
186
187
188
189
190
191
192
193
194
use std::{
    marker::PhantomData,
    pin::Pin,
    sync::{Arc, Mutex},
    task::{Poll, Waker},
};

use futures::{future::Either, Stream};
use pin_project_lite::pin_project;

pin_project! {
    pub(crate) struct SplitByMap<I, L, R, S, P> {
        buf_left: Option<L>,
        buf_right: Option<R>,
        waker_left: Option<Waker>,
        waker_right: Option<Waker>,
        #[pin]
        stream: S,
        predicate: P,
        item: PhantomData<I>
    }
}

impl<I, L, R, S, P> SplitByMap<I, L, R, S, P>
where
    S: Stream<Item = I>,
    P: Fn(I) -> Either<L, R>,
{
    pub(crate) fn new(stream: S, predicate: P) -> Arc<Mutex<Self>> {
        Arc::new(Mutex::new(Self {
            buf_right: None,
            buf_left: None,
            waker_right: None,
            waker_left: None,
            stream,
            predicate,
            item: PhantomData,
        }))
    }

    fn poll_next_left(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<L>> {
        let this = self.project();
        // There should only ever be one waker calling the function
        if this.waker_left.is_none() {
            *this.waker_left = Some(cx.waker().clone());
        }
        if let Some(item) = this.buf_left.take() {
            // There was already a value in the buffer. Return that value
            return Poll::Ready(Some(item));
        }
        if this.buf_right.is_some() {
            // There is a value available for the other stream. Wake that
            // stream if possible and return pending since we can't store
            // multiple values for a stream
            if let Some(waker) = this.waker_right {
                waker.wake_by_ref();
            }
            return Poll::Pending;
        }
        match this.stream.poll_next(cx) {
            Poll::Ready(Some(item)) => {
                match (this.predicate)(item) {
                    Either::Left(left_item) => Poll::Ready(Some(left_item)),
                    Either::Right(right_item) => {
                        // This value is not what we wanted. Store it and notify other partition task if it exists
                        let _ = this.buf_right.replace(right_item);
                        if let Some(waker) = this.waker_right {
                            waker.wake_by_ref();
                        }
                        Poll::Pending
                    }
                }
            }
            Poll::Ready(None) => Poll::Ready(None),
            Poll::Pending => Poll::Pending,
        }
    }

    fn poll_next_right(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<R>> {
        let this = self.project();
        // I think there should only ever be one waker calling the function
        if this.waker_right.is_none() {
            *this.waker_right = Some(cx.waker().clone());
        }
        if let Some(item) = this.buf_right.take() {
            // There was already a value in the buffer. Return that value
            return Poll::Ready(Some(item));
        }
        if this.buf_left.is_some() {
            // There is a value available for the other stream. Wake that
            // stream if possible and return pending since we can't store
            // multiple values for a stream
            if let Some(waker) = this.waker_left {
                waker.wake_by_ref();
            }
            return Poll::Pending;
        }
        match this.stream.poll_next(cx) {
            Poll::Ready(Some(item)) => {
                match (this.predicate)(item) {
                    Either::Left(left_item) => {
                        // This value is not what we wanted. Store it and notify other partition task if it exists
                        let _ = this.buf_left.replace(left_item);
                        if let Some(waker) = this.waker_left {
                            waker.wake_by_ref();
                        }
                        Poll::Pending
                    }
                    Either::Right(right_item) => Poll::Ready(Some(right_item)),
                }
            }
            Poll::Ready(None) => Poll::Ready(None),
            Poll::Pending => Poll::Pending,
        }
    }
}

pin_project! {
    /// A struct that implements `Stream` which returns the inner values
    /// where the predicate returns `Either::Left(..)` when using `split_by_map`
    pub struct LeftSplitByMap<I, L, R, S, P> {
        #[pin]
        stream: Arc<Mutex<SplitByMap<I, L, R, S, P>>>,
    }
}

impl<I, L, R, S, P> LeftSplitByMap<I, L, R, S, P> {
    pub(crate) fn new(stream: Arc<Mutex<SplitByMap<I, L, R, S, P>>>) -> Self {
        Self { stream }
    }
}

impl<I, L, R, S, P> Stream for LeftSplitByMap<I, L, R, S, P>
where
    S: Stream<Item = I> + Unpin,
    P: Fn(I) -> Either<L, R>,
{
    type Item = L;
    fn poll_next(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        let this = self.project();
        let response = if let Ok(mut guard) = this.stream.try_lock() {
            SplitByMap::poll_next_left(Pin::new(&mut guard), cx)
        } else {
            cx.waker().wake_by_ref();
            Poll::Pending
        };
        response
    }
}

pin_project! {
    /// A struct that implements `Stream` which returns the inner values
    /// where the predicate returns `Either::Right(..)` when using `split_by_map`
    pub struct RightSplitByMap<I, L, R, S, P> {
        #[pin]
        stream: Arc<Mutex<SplitByMap<I, L, R , S, P>>>,
    }
}

impl<I, L, R, S, P> RightSplitByMap<I, L, R, S, P> {
    pub(crate) fn new(stream: Arc<Mutex<SplitByMap<I, L, R, S, P>>>) -> Self {
        Self { stream }
    }
}

impl<I, L, R, S, P> Stream for RightSplitByMap<I, L, R, S, P>
where
    S: Stream<Item = I> + Unpin,
    P: Fn(I) -> Either<L, R>,
{
    type Item = R;
    fn poll_next(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        let this = self.project();
        let response = if let Ok(mut guard) = this.stream.try_lock() {
            SplitByMap::poll_next_right(Pin::new(&mut guard), cx)
        } else {
            cx.waker().wake_by_ref();
            Poll::Pending
        };
        response
    }
}