• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use super::assert_stream;
2 use core::pin::Pin;
3 use futures_core::stream::{Stream, FusedStream};
4 use futures_core::task::{Context, Poll};
5 
6 /// An stream that repeats elements of type `A` endlessly by
7 /// applying the provided closure `F: FnMut() -> A`.
8 ///
9 /// This `struct` is created by the [`repeat_with()`] function.
10 /// See its documentation for more.
11 #[derive(Debug, Clone)]
12 #[must_use = "streams do nothing unless polled"]
13 pub struct RepeatWith<F> {
14     repeater: F,
15 }
16 
17 impl<A, F: FnMut() -> A> Unpin for RepeatWith<F> {}
18 
19 impl<A, F: FnMut() -> A> Stream for RepeatWith<F> {
20     type Item = A;
21 
poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>>22     fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
23         Poll::Ready(Some((&mut self.repeater)()))
24     }
25 
size_hint(&self) -> (usize, Option<usize>)26     fn size_hint(&self) -> (usize, Option<usize>) {
27         (usize::max_value(), None)
28     }
29 }
30 
31 impl<A, F: FnMut() -> A> FusedStream for RepeatWith<F>
32 {
is_terminated(&self) -> bool33     fn is_terminated(&self) -> bool {
34         false
35     }
36 }
37 
38 /// Creates a new stream that repeats elements of type `A` endlessly by
39 /// applying the provided closure, the repeater, `F: FnMut() -> A`.
40 ///
41 /// The `repeat_with()` function calls the repeater over and over again.
42 ///
43 /// Infinite stream like `repeat_with()` are often used with adapters like
44 /// [`stream.take()`], in order to make them finite.
45 ///
46 /// If the element type of the stream you need implements [`Clone`], and
47 /// it is OK to keep the source element in memory, you should instead use
48 /// the [`stream.repeat()`] function.
49 ///
50 /// # Examples
51 ///
52 /// Basic usage:
53 ///
54 /// ```
55 /// # futures::executor::block_on(async {
56 /// use futures::stream::{self, StreamExt};
57 ///
58 /// // let's assume we have some value of a type that is not `Clone`
59 /// // or which don't want to have in memory just yet because it is expensive:
60 /// #[derive(PartialEq, Debug)]
61 /// struct Expensive;
62 ///
63 /// // a particular value forever:
64 /// let mut things = stream::repeat_with(|| Expensive);
65 ///
66 /// assert_eq!(Some(Expensive), things.next().await);
67 /// assert_eq!(Some(Expensive), things.next().await);
68 /// assert_eq!(Some(Expensive), things.next().await);
69 /// # });
70 /// ```
71 ///
72 /// Using mutation and going finite:
73 ///
74 /// ```rust
75 /// # futures::executor::block_on(async {
76 /// use futures::stream::{self, StreamExt};
77 ///
78 /// // From the zeroth to the third power of two:
79 /// let mut curr = 1;
80 /// let mut pow2 = stream::repeat_with(|| { let tmp = curr; curr *= 2; tmp })
81 ///                     .take(4);
82 ///
83 /// assert_eq!(Some(1), pow2.next().await);
84 /// assert_eq!(Some(2), pow2.next().await);
85 /// assert_eq!(Some(4), pow2.next().await);
86 /// assert_eq!(Some(8), pow2.next().await);
87 ///
88 /// // ... and now we're done
89 /// assert_eq!(None, pow2.next().await);
90 /// # });
91 /// ```
repeat_with<A, F: FnMut() -> A>(repeater: F) -> RepeatWith<F>92 pub fn repeat_with<A, F: FnMut() -> A>(repeater: F) -> RepeatWith<F> {
93     assert_stream::<A, _>(RepeatWith { repeater })
94 }
95