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
357
358
359
360
361
362
363
364
//! A version of [async-stream](https://github.com/tokio-rs/async-stream) without macros.
//! This crate provides generic implementations of [`Stream`] trait.
//! [`Stream`] is an asynchronous version of [`std::iter::Iterator`].
//!
//! Two functions are provided - [`fn_stream`] and [`try_fn_stream`].
//!
//! # Usage
//!
//! If you need to create a stream that may result in error, use [`try_fn_stream`], otherwise use [`fn_stream`].
//!
//! To create a stream:
//!
//! 1.  Invoke [`fn_stream`] or [`try_fn_stream`], passing a closure (anonymous function).
//! 2.  Closure will accept an `emitter`.
//!     To return value from the stream, call `.emit(value)` on `emitter` and `.await` on its result.
//!     Once stream consumer has processed the value and called `.next()` on stream, `.await` will return.
//! 3.  (for [`try_fn_stream`] only) Return errors from closure via `return Err(...)` or `?` (question mark) operator.
//!
//! # Examples
//!
//! Finite stream of numbers
//!
//! ```rust
//! use async_fn_stream::fn_stream;
//! use futures::Stream;
//!
//! fn build_stream() -> impl Stream<Item = i32> {
//!     fn_stream(|emitter| async move {
//!         for i in 0..3 {
//!             // yield elements from stream via `emitter`
//!             emitter.emit(i).await;
//!         }
//!     })
//! }
//! ```
//!
//! Read numbers from text file, with error handling
//!
//! ```rust
//! use anyhow::Context;
//! use async_fn_stream::try_fn_stream;
//! use futures::{pin_mut, Stream, StreamExt};
//! use tokio::{
//!     fs::File,
//!     io::{AsyncBufReadExt, BufReader},
//! };
//!
//! fn read_numbers(file_name: String) -> impl Stream<Item = Result<i32, anyhow::Error>> {
//!     try_fn_stream(|emitter| async move {
//!         // Return errors via `?` operator.
//!         let file = BufReader::new(File::open(file_name).await.context("Failed to open file")?);
//!         pin_mut!(file);
//!         let mut line = String::new();
//!         loop {
//!             line.clear();
//!             let byte_count = file
//!                 .read_line(&mut line)
//!                 .await
//!                 .context("Failed to read line")?;
//!             if byte_count == 0 {
//!                 break;
//!             }
//!
//!             for token in line.split_ascii_whitespace() {
//!                 let number: i32 = token
//!                     .parse()
//!                     .with_context(|| format!("Failed to conver string \"{token}\" to number"))?;
//!                 // Return errors via `?` operator.
//!                 emitter.emit(number).await;
//!             }
//!         }
//!
//!         Ok(())
//!     })
//! }
//! ```
//!
//! # Why not `async-stream`?
//!
//! [async-stream](https://github.com/tokio-rs/async-stream) is great!
//! It has a nice syntax, but it is based on macros which brings some flaws:
//! * proc-macros sometimes interacts badly with IDEs such as rust-analyzer or IntelliJ Rust.
//!   see e.g. <https://github.com/rust-lang/rust-analyzer/issues/11533>
//! * proc-macros may increase build times

use std::{
    pin::Pin,
    sync::{Arc, Mutex},
    task::{Poll, Waker},
};

use futures::{Future, FutureExt, Stream};
use pin_project_lite::pin_project;

/// An intemediary that transfers values from stream to its consumer
pub struct StreamEmitter<T: Send> {
    inner: Arc<Mutex<Inner<T>>>,
}

struct Inner<T: Send> {
    value: Option<T>,
    waker: Option<Waker>,
}

pin_project! {
    /// Implementation of [`Stream`] trait created by [`fn_stream`].
    pub struct FnStream<T: Send, Fut: Future<Output = ()>> {
        #[pin]
        fut: Fut,
        inner: Arc<Mutex<Inner<T>>>,
    }
}

/// Create a new infallible stream which is implemented by `func`.
///
/// Caller should pass an async function which will return successive stream elements via [`StreamEmitter::emit`].
///
/// # Example
///
/// ```rust
/// use async_fn_stream::fn_stream;
/// use futures::Stream;
///
/// fn build_stream() -> impl Stream<Item = i32> {
///     fn_stream(|emitter| async move {
///         for i in 0..3 {
///             // yield elements from stream via `emitter`
///             emitter.emit(i).await;
///         }
///     })
/// }
/// ```
pub fn fn_stream<T: Send, Fut: Future<Output = ()>>(
    func: impl FnOnce(StreamEmitter<T>) -> Fut,
) -> FnStream<T, Fut> {
    FnStream::new(func)
}

impl<T: Send, Fut: Future<Output = ()>> FnStream<T, Fut> {
    fn new<F: FnOnce(StreamEmitter<T>) -> Fut>(func: F) -> Self {
        let inner = Arc::new(Mutex::new(Inner {
            value: None,
            waker: None,
        }));
        let collector = StreamEmitter {
            inner: inner.clone(),
        };
        let fut = func(collector);
        Self { fut, inner }
    }
}

impl<T: Send, Fut: Future<Output = ()>> Stream for FnStream<T, Fut> {
    type Item = T;

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

        this.inner.lock().expect("Mutex was poisoned").waker = Some(cx.waker().clone());
        let r = this.fut.poll_unpin(cx);
        match r {
            std::task::Poll::Ready(()) => Poll::Ready(None),
            std::task::Poll::Pending => {
                let value = this.inner.lock().expect("Mutex was poisoned").value.take();
                match value {
                    None => Poll::Pending,
                    Some(value) => Poll::Ready(Some(value)),
                }
            }
        }
    }
}

/// Create a new fallible stream which is implemented by `func`.
///
/// Caller should pass an async function which will return successive stream elements via [`StreamEmitter::emit`] or returns errors as [`Result::Err`].
///
/// # Example
/// ```rust
/// use async_fn_stream::try_fn_stream;
/// use futures::Stream;
///
/// fn build_stream() -> impl Stream<Item = Result<i32, anyhow::Error>> {
///     try_fn_stream(|emitter| async move {
///         for i in 0..3 {
///             // yield elements from stream via `emitter`
///             emitter.emit(i).await;
///         }
///
///         // return errors as `Result::Err`
///         Err(anyhow::anyhow!("An error happened"))
///     })
/// }
/// ```
pub fn try_fn_stream<T: Send, E: Send, Fut: Future<Output = Result<(), E>>>(
    func: impl FnOnce(StreamEmitter<T>) -> Fut,
) -> TryFnStream<T, E, Fut> {
    TryFnStream::new(func)
}

pin_project! {
    /// Implementation of [`Stream`] trait created by [`try_fn_stream`].
    pub struct TryFnStream<T: Send, E: Send, Fut: Future<Output = Result<(), E>>> {
        is_err: bool,
        #[pin]
        fut: Fut,
        inner: Arc<Mutex<Inner<T>>>,
    }
}

impl<T: Send, E: Send, Fut: Future<Output = Result<(), E>>> TryFnStream<T, E, Fut> {
    fn new<F: FnOnce(StreamEmitter<T>) -> Fut>(func: F) -> Self {
        let inner = Arc::new(Mutex::new(Inner {
            value: None,
            waker: None,
        }));
        let collector = StreamEmitter {
            inner: inner.clone(),
        };
        let fut = func(collector);
        Self {
            is_err: false,
            fut,
            inner,
        }
    }
}

impl<T: Send, E: Send, Fut: Future<Output = Result<(), E>>> Stream for TryFnStream<T, E, Fut> {
    type Item = Result<T, E>;

    fn poll_next(
        self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<Option<Self::Item>> {
        if self.is_err {
            return Poll::Ready(None);
        }
        let mut this = self.project();
        this.inner.lock().expect("Mutex was poisoned").waker = Some(cx.waker().clone());
        let r = this.fut.poll_unpin(cx);
        match r {
            std::task::Poll::Ready(Ok(())) => Poll::Ready(None),
            std::task::Poll::Ready(Err(e)) => {
                *this.is_err = true;
                Poll::Ready(Some(Err(e)))
            }
            std::task::Poll::Pending => {
                let value = this.inner.lock().expect("Mutex was poisoned").value.take();
                match value {
                    None => Poll::Pending,
                    Some(value) => Poll::Ready(Some(Ok(value))),
                }
            }
        }
    }
}

impl<T: Send> StreamEmitter<T> {
    /// Emit value from a stream and wait until stream consumer calls [`futures::StreamExt::next`] again.
    ///
    /// # Panics
    /// Will panic if:
    /// * `collect` is called twice without awaiting result of first call
    /// * `collect` is called not in context of polling the stream
    #[must_use = "Ensure that collect() is awaited"]
    pub fn emit(&self, value: T) -> CollectFuture {
        let mut inner = self.inner.lock().expect("Mutex was poisoned");
        let inner = &mut *inner;
        if inner.value.is_some() {
            panic!(
                "Collector::collect() was called without `.await`'ing result of previous collect"
            )
        }
        inner.value = Some(value);
        inner
            .waker
            .take()
            .expect("Collector::collect() should only be called in context of Future::poll()")
            .wake();
        CollectFuture { polled: false }
    }
}

/// Future returned from [`StreamEmitter::emit`].
pub struct CollectFuture {
    polled: bool,
}

impl Future for CollectFuture {
    type Output = ();

    fn poll(self: Pin<&mut Self>, _cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
        if self.polled {
            Poll::Ready(())
        } else {
            self.get_mut().polled = true;
            Poll::Pending
        }
    }
}

#[cfg(test)]
mod tests {
    use std::io::ErrorKind;

    use futures::{executor, pin_mut, StreamExt};

    use super::*;

    #[test]
    fn infallible_works() {
        executor::block_on(async {
            let stream = fn_stream(|collector| async move {
                eprintln!("stream 1");
                collector.emit(1).await;
                eprintln!("stream 2");
                collector.emit(2).await;
                eprintln!("stream 3");
            });
            pin_mut!(stream);
            assert_eq!(Some(1), stream.next().await);
            assert_eq!(Some(2), stream.next().await);
            assert_eq!(None, stream.next().await);
        });
    }
    #[test]
    #[should_panic]
    fn infallible_panics_on_multiple_collects() {
        executor::block_on(async {
            #[allow(unused_must_use)]
            let stream = fn_stream(|collector| async move {
                eprintln!("stream 1");
                collector.emit(1);
                collector.emit(2);
                eprintln!("stream 3");
            });
            pin_mut!(stream);
            assert_eq!(Some(1), stream.next().await);
            assert_eq!(Some(2), stream.next().await);
            assert_eq!(None, stream.next().await);
        });
    }
    #[test]
    fn fallible_works() {
        executor::block_on(async {
            let stream = try_fn_stream(|collector| async move {
                eprintln!("try stream 1");
                collector.emit(1).await;
                eprintln!("try stream 2");
                collector.emit(2).await;
                eprintln!("try stream 3");
                Err(std::io::Error::from(ErrorKind::Other))
            });
            pin_mut!(stream);
            assert_eq!(1, stream.next().await.unwrap().unwrap());
            assert_eq!(2, stream.next().await.unwrap().unwrap());
            assert!(stream.next().await.unwrap().err().is_some());
        });
    }
}