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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
//! Stream and handle types for the [`with_state`](crate::stream::StreamExt::with_state) method.

use crate::common::*;
use tokio::sync::oneshot;

/// Stream for the [`with_state`](super::StreamExt::with_state) method.
///
/// The stream produces a single [handle](Handle) to value `T` and
/// pauses indefinitely until [`handle.send()`](Handle::send) or
/// [`handle.close()`](Handle::close). Calling [`handle.send()`](Handle::send)
/// returns the value to the stream, so that the stream can produce the handle again.
/// [`handle.close()`](Handle::close) drops the handle and the close the stream.
#[pin_project]
pub struct StateStream<T> {
    #[pin]
    receiver: Option<oneshot::Receiver<T>>,
    value: Option<T>,
}

impl<T> StateStream<T> {
    /// Creates the stream with initial value `init`.
    pub fn new(init: T) -> Self {
        Self {
            value: Some(init),
            receiver: None,
        }
    }
}

impl<T> Stream for StateStream<T> {
    type Item = Handle<T>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
        let mut this = self.project();

        Ready(loop {
            if let Some(value) = this.value.take() {
                let (tx, rx) = oneshot::channel();
                this.receiver.set(Some(rx));
                break Some(Handle {
                    inner: Some(Inner { value, sender: tx }),
                });
            } else if let Some(receiver) = this.receiver.as_mut().as_pin_mut() {
                match ready!(receiver.poll(cx)) {
                    Ok(value) => {
                        *this.value = Some(value);
                        this.receiver.set(None);
                    }
                    Err(_) => {
                        this.receiver.set(None);
                        break None;
                    }
                }
            } else {
                break None;
            }
        })
    }
}

/// The handle maintains an unique reference to the state value for [StateStream].
pub struct Handle<T> {
    inner: Option<Inner<T>>,
}

struct Inner<T> {
    value: T,
    sender: oneshot::Sender<T>,
}

impl<T> Handle<T> {
    fn inner(&self) -> &Inner<T> {
        self.inner.as_ref().unwrap()
    }

    /// Returns the value to the associated stream.
    pub fn send(mut self) -> Result<(), T> {
        let Inner { value, sender } = self.inner.take().unwrap();
        sender.send(value)
    }

    /// Takes the ownership of value and closes the associated stream.
    pub fn take(mut self) -> T {
        self.inner.take().unwrap().value
    }

    /// Discards the value and closes the associated stream.
    pub fn close(mut self) {
        let _ = self.inner.take();
    }
}

impl<T> Drop for Handle<T> {
    fn drop(&mut self) {
        if let Some(Inner { value, sender }) = self.inner.take() {
            let _ = sender.send(value);
        }
    }
}

impl<T> Debug for Handle<T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        self.inner().value.fmt(f)
    }
}

impl<T> Display for Handle<T>
where
    T: Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        self.inner().value.fmt(f)
    }
}

impl<T> PartialEq<T> for Handle<T>
where
    T: PartialEq,
{
    fn eq(&self, other: &T) -> bool {
        self.inner().value.eq(other)
    }
}

impl<T> PartialOrd<T> for Handle<T>
where
    T: PartialOrd,
{
    fn partial_cmp(&self, other: &T) -> Option<cmp::Ordering> {
        self.inner().value.partial_cmp(other)
    }
}

impl<T> Hash for Handle<T>
where
    T: Hash,
{
    fn hash<H>(&self, state: &mut H)
    where
        H: Hasher,
    {
        self.inner().value.hash(state);
    }
}

impl<T> Deref for Handle<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.inner().value
    }
}

impl<T> DerefMut for Handle<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner.as_mut().unwrap().value
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{stream::StreamExt as _, utils::async_test};

    async_test! {
        async fn state_stream_test() {
            let quota = 100;

            let count: usize = stream::repeat(())
                .with_state(0)
                .filter_map(|((), mut cost)| async move {
                    if *cost < quota {
                        *cost += 1;
                        cost.send().unwrap();
                        Some(())
                    } else {
                        cost.close();
                        None
                    }
                })
                .count()
                .await;

            assert_eq!(count, quota);
        }

        async fn state_stream_simple_test() {
            {
                let mut state_stream = StateStream::new(0);

                let handle = state_stream.next().await.unwrap();
                handle.send().unwrap();

                let handle = state_stream.next().await.unwrap();
                drop(handle);

                let handle = state_stream.next().await.unwrap();
                handle.take();

                assert!(state_stream.next().await.is_none());
            }

            {
                let mut state_stream = StateStream::new(0);
                let handle = state_stream.next().await.unwrap();
                drop(state_stream);
                assert!(handle.send().is_err());
            }

            {
                let mut state_stream = StateStream::new(0);
                let handle = state_stream.next().await.unwrap();
                handle.close();
                assert!(state_stream.next().await.is_none());
            }
        }
    }
}