1 | use super::assert_stream; |
2 | use core::pin::Pin; |
3 | use futures_core::stream::{FusedStream, Stream}; |
4 | use futures_core::task::{Context, Poll}; |
5 | |
6 | /// Stream for the [`repeat`] function. |
7 | #[derive(Debug, Clone)] |
8 | #[must_use = "streams do nothing unless polled" ] |
9 | pub struct Repeat<T> { |
10 | item: T, |
11 | } |
12 | |
13 | /// Create a stream which produces the same item repeatedly. |
14 | /// |
15 | /// The stream never terminates. Note that you likely want to avoid |
16 | /// usage of `collect` or such on the returned stream as it will exhaust |
17 | /// available memory as it tries to just fill up all RAM. |
18 | /// |
19 | /// ``` |
20 | /// # futures::executor::block_on(async { |
21 | /// use futures::stream::{self, StreamExt}; |
22 | /// |
23 | /// let stream = stream::repeat(9); |
24 | /// assert_eq!(vec![9, 9, 9], stream.take(3).collect::<Vec<i32>>().await); |
25 | /// # }); |
26 | /// ``` |
27 | pub fn repeat<T>(item: T) -> Repeat<T> |
28 | where |
29 | T: Clone, |
30 | { |
31 | assert_stream::<T, _>(Repeat { item }) |
32 | } |
33 | |
34 | impl<T> Unpin for Repeat<T> {} |
35 | |
36 | impl<T> Stream for Repeat<T> |
37 | where |
38 | T: Clone, |
39 | { |
40 | type Item = T; |
41 | |
42 | fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> { |
43 | Poll::Ready(Some(self.item.clone())) |
44 | } |
45 | |
46 | fn size_hint(&self) -> (usize, Option<usize>) { |
47 | (usize::max_value(), None) |
48 | } |
49 | } |
50 | |
51 | impl<T> FusedStream for Repeat<T> |
52 | where |
53 | T: Clone, |
54 | { |
55 | fn is_terminated(&self) -> bool { |
56 | false |
57 | } |
58 | } |
59 | |