async_std/stream/
repeat_with.rs

1use core::pin::Pin;
2
3use crate::stream::Stream;
4use crate::task::{Context, Poll};
5
6/// A stream that repeats elements of type `T` endlessly by applying a provided closure.
7///
8/// This stream is created by the [`repeat_with`] function. See its
9/// documentation for more.
10///
11/// [`repeat_with`]: fn.repeat_with.html
12#[derive(Clone, Debug)]
13pub struct RepeatWith<F> {
14    f: F,
15}
16
17impl<F> Unpin for RepeatWith<F> {}
18
19/// Creates a new stream that repeats elements of type `A` endlessly by applying the provided closure.
20///
21/// # Examples
22///
23/// Basic usage:
24///
25/// ```
26/// # async_std::task::block_on(async {
27/// #
28/// use async_std::prelude::*;
29/// use async_std::stream;
30///
31/// let s = stream::repeat_with(|| 1);
32///
33/// pin_utils::pin_mut!(s);
34///
35/// assert_eq!(s.next().await, Some(1));
36/// assert_eq!(s.next().await, Some(1));
37/// assert_eq!(s.next().await, Some(1));
38/// assert_eq!(s.next().await, Some(1));
39/// # })
40/// ```
41///
42/// Going finite:
43///
44/// ```
45/// # async_std::task::block_on(async {
46/// #
47/// use async_std::prelude::*;
48/// use async_std::stream;
49///
50/// let mut n = 1;
51/// let s = stream::repeat_with(|| {
52///     let item = n;
53///     n *= 2;
54///     item
55/// })
56/// .take(4);
57///
58/// pin_utils::pin_mut!(s);
59///
60/// assert_eq!(s.next().await, Some(1));
61/// assert_eq!(s.next().await, Some(2));
62/// assert_eq!(s.next().await, Some(4));
63/// assert_eq!(s.next().await, Some(8));
64/// assert_eq!(s.next().await, None);
65/// # })
66/// ```
67pub fn repeat_with<T, F>(repeater: F) -> RepeatWith<F>
68where
69    F: FnMut() -> T,
70{
71    RepeatWith { f: repeater }
72}
73
74impl<T, F> Stream for RepeatWith<F>
75where
76    F: FnMut() -> T,
77{
78    type Item = T;
79
80    fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
81        let item = (&mut self.f)();
82        Poll::Ready(Some(item))
83    }
84}