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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
//! Lightweight async stream wrapper.
//!
//! # Usage
//! ```
//! use transform_stream::AsyncTryStream;
//! use futures::StreamExt;
//! use std::io;
//!
//! let stream: AsyncTryStream<Vec<u8>, io::Error, _> = AsyncTryStream::new(|mut y| async move {
//!     y.yield_ok(vec![b'1', b'2']).await;
//!     y.yield_ok(vec![b'3', b'4']).await;
//!     Ok(())
//! });
//!
//! futures::executor::block_on(async {
//!     futures::pin_mut!(stream);
//!     assert_eq!(stream.next().await.unwrap().unwrap(), vec![b'1', b'2']);
//!     assert_eq!(stream.next().await.unwrap().unwrap(), vec![b'3', b'4']);
//!     assert!(stream.next().await.is_none());
//! });
//! ```

#![forbid(unsafe_code)]
#![deny(
    missing_debug_implementations,
    missing_docs,
    clippy::all,
    clippy::cargo
)]

use std::collections::VecDeque;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use atomic_refcell::AtomicRefCell;
use futures_core::future::BoxFuture;
use futures_core::stream::{FusedStream, Stream};
use pin_project_lite::pin_project;

type Channel<T> = Arc<AtomicRefCell<VecDeque<T>>>;

/// A handle for sending items into the related stream.
#[derive(Debug)]
pub struct Yielder<T> {
    tx: Channel<T>,
}

impl<T> Yielder<T> {
    /// Send a item into the related stream.
    pub async fn yield_item(&mut self, value: T) {
        self.tx.borrow_mut().push_back(value);
    }

    /// Send items into the related stream.
    pub async fn yield_iter<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = T>,
    {
        self.tx.borrow_mut().extend(iter.into_iter());
    }
}

impl<T, E> Yielder<Result<T, E>> {
    /// Send `Ok(value)` into the related stream.
    pub async fn yield_ok(&mut self, value: T) {
        self.tx.borrow_mut().push_back(Ok(value));
    }

    /// Send ok values into the related stream.
    pub async fn yield_ok_iter<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = T>,
    {
        self.tx.borrow_mut().extend(iter.into_iter().map(Ok));
    }
}

pin_project! {
    /// Asynchronous stream of items
    pub struct AsyncStream<T, G = BoxFuture<'static, ()>> {
        chan: Channel<T>,
        done: bool,
        #[pin]
        gen: G,
    }
}

impl<T, G> AsyncStream<T, G>
where
    G: Future<Output = ()>,
{
    /// Constructs an `AsyncStream` by a factory function which returns a future.
    pub fn new<F>(f: F) -> Self
    where
        F: FnOnce(Yielder<T>) -> G,
    {
        let chan = Arc::new(AtomicRefCell::new(VecDeque::new()));
        let tx = Arc::clone(&chan);
        let yielder = Yielder { tx };
        let gen = f(yielder);
        Self {
            chan,
            gen,
            done: false,
        }
    }
}

impl<'a, T> AsyncStream<T, BoxFuture<'a, ()>> {
    /// Constructs an `AsyncStream` by a factory function which returns a future.
    ///
    /// The `G` is wrapped as an owned dynamically typed `Future` which allows you to write the type.
    pub fn new_boxed<F, G>(f: F) -> Self
    where
        F: FnOnce(Yielder<T>) -> G,
        G: Future<Output = ()> + Send + 'a,
    {
        let chan = Arc::new(AtomicRefCell::new(VecDeque::new()));
        let tx = Arc::clone(&chan);
        let yielder = Yielder { tx };
        let gen = Box::pin(f(yielder));
        Self {
            chan,
            gen,
            done: false,
        }
    }
}

impl<T, G> Stream for AsyncStream<T, G>
where
    G: Future<Output = ()>,
{
    type Item = T;

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

        loop {
            if let Some(item) = this.chan.borrow_mut().pop_front() {
                return Poll::Ready(Some(item));
            }

            if *this.done {
                return Poll::Ready(None);
            }

            match this.gen.as_mut().poll(cx) {
                Poll::Pending => return Poll::Pending,
                Poll::Ready(()) => *this.done = true,
            }
        }
    }
}

impl<T, G> FusedStream for AsyncStream<T, G>
where
    G: Future<Output = ()>,
{
    fn is_terminated(&self) -> bool {
        self.done && self.chan.borrow().is_empty()
    }
}

pin_project! {
    /// Asynchronous stream of results
    pub struct AsyncTryStream<T, E, G = BoxFuture<'static, Result<(), E>>> {
        #[pin]
        inner: AsyncStream<Result<T,E>,G>
    }
}

impl<T, E, G> AsyncTryStream<T, E, G>
where
    G: Future<Output = Result<(), E>>,
{
    /// Constructs an `AsyncTryStream` by a factory function which returns a future.
    pub fn new<F>(f: F) -> Self
    where
        F: FnOnce(Yielder<Result<T, E>>) -> G,
    {
        let chan = Arc::new(AtomicRefCell::new(VecDeque::new()));
        let tx = Arc::clone(&chan);
        let yielder = Yielder { tx };
        let gen = f(yielder);
        Self {
            inner: AsyncStream {
                chan,
                gen,
                done: false,
            },
        }
    }
}

impl<'a, T, E> AsyncTryStream<T, E, BoxFuture<'a, Result<(), E>>> {
    /// Constructs an `AsyncTryStream` by a factory function which returns a future.
    ///
    /// The `G` is wrapped as an owned dynamically typed `Future` which allows you to write the type.
    pub fn new_boxed<F, G>(f: F) -> Self
    where
        F: FnOnce(Yielder<Result<T, E>>) -> G,
        G: Future<Output = Result<(), E>> + Send + 'a,
        E: 'a,
    {
        let chan = Arc::new(AtomicRefCell::new(VecDeque::new()));
        let tx = Arc::clone(&chan);
        let yielder = Yielder { tx };
        let gen = Box::pin(f(yielder));
        Self {
            inner: AsyncStream {
                chan,
                gen,
                done: false,
            },
        }
    }
}

impl<T, E, G> Stream for AsyncTryStream<T, E, G>
where
    G: Future<Output = Result<(), E>>,
{
    type Item = Result<T, E>;

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

        loop {
            if let Some(item) = this.chan.borrow_mut().pop_front() {
                return Poll::Ready(Some(item));
            }

            if *this.done {
                return Poll::Ready(None);
            }

            match this.gen.as_mut().poll(cx) {
                Poll::Pending => return Poll::Pending,
                Poll::Ready(ret) => {
                    *this.done = true;
                    if let Err(e) = ret {
                        this.chan.borrow_mut().push_back(Err(e));
                    }
                }
            }
        }
    }
}

impl<T, E, G> FusedStream for AsyncTryStream<T, E, G>
where
    G: Future<Output = Result<(), E>>,
{
    fn is_terminated(&self) -> bool {
        self.inner.done && self.inner.chan.borrow().is_empty()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn line_stream() {
        use futures::{pin_mut, StreamExt};
        use memchr::memchr;
        use std::io;
        use std::mem;

        let bytes: &[&[u8]] = &[b"12", b"34", b"5\n", b"67", b"89", b"10\n", b"11"];
        let io_bytes: Vec<io::Result<Vec<u8>>> = bytes.iter().map(|&b| Ok(Vec::from(b))).collect();

        let source_stream = futures::stream::iter(io_bytes);

        let line_stream: AsyncTryStream<Vec<u8>, io::Error> =
            AsyncTryStream::new_boxed(|mut y| async move {
                pin_mut!(source_stream);

                let mut buf: Vec<u8> = Vec::new();
                loop {
                    match source_stream.next().await {
                        None => break,
                        Some(Err(e)) => return Err(e),
                        Some(Ok(bytes)) => {
                            if let Some(idx) = memchr(b'\n', &bytes) {
                                let pos = idx + 1 + buf.len();
                                buf.extend(bytes);
                                let remaining = buf.split_off(pos);
                                let line = mem::replace(&mut buf, remaining);
                                y.yield_ok(line).await;
                            }
                        }
                    }
                }

                if !buf.is_empty() {
                    y.yield_ok(buf).await;
                }

                Ok(())
            });

        futures::executor::block_on(async {
            pin_mut!(line_stream);

            while let Some(bytes) = line_stream.next().await {
                let bytes = bytes.unwrap();
                let line = std::str::from_utf8(&bytes).unwrap();
                dbg!(line);
            }
        });
    }

    macro_rules! require_by_ref {
        ($value:expr, $($bound:tt)+) => {{
            fn __require<T: $($bound)+>(_: &T) {}
            __require(&$value);
        }};
    }

    #[test]
    fn markers() {
        use futures::future;
        use std::io;

        let stream = AsyncTryStream::new(|mut y| async move {
            y.yield_ok(1_usize).await;
            io::Result::Ok(())
        });

        require_by_ref!(stream, Send + Sync + 'static);

        let stream_boxed: AsyncTryStream<usize, io::Error> =
            AsyncTryStream::new_boxed(|mut y| async move {
                y.yield_ok(1_usize).await;
                io::Result::Ok(())
            });

        require_by_ref!(stream_boxed, Send + Unpin + 'static);

        type FullMarkerBoxFuture<'a, T> = Box<dyn Future<Output = T> + Send + Sync + Unpin + 'a>;

        let stream_full: AsyncTryStream<
            usize,
            io::Error,
            FullMarkerBoxFuture<'static, io::Result<()>>,
        > = AsyncTryStream::new(|_| -> FullMarkerBoxFuture<'static, io::Result<()>> {
            Box::new(future::ready(io::Result::Ok(())))
        });

        require_by_ref!(stream_full, Send + Sync + Unpin + 'static)
    }
}