futures_util/stream/
unfold.rs1use super::assert_stream;
2use crate::unfold_state::UnfoldState;
3use core::fmt;
4use core::pin::Pin;
5use futures_core::future::Future;
6use futures_core::ready;
7use futures_core::stream::{FusedStream, Stream};
8use futures_core::task::{Context, Poll};
9use pin_project_lite::pin_project;
10
11pub fn unfold<T, F, Fut, Item>(init: T, f: F) -> Unfold<T, F, Fut>
51where
52 F: FnMut(T) -> Fut,
53 Fut: Future<Output = Option<(Item, T)>>,
54{
55 assert_stream::<Item, _>(Unfold { f, state: UnfoldState::Value { value: init } })
56}
57
58pin_project! {
59 #[must_use = "streams do nothing unless polled"]
61 pub struct Unfold<T, F, Fut> {
62 f: F,
63 #[pin]
64 state: UnfoldState<T, Fut>,
65 }
66}
67
68impl<T, F, Fut> fmt::Debug for Unfold<T, F, Fut>
69where
70 T: fmt::Debug,
71 Fut: fmt::Debug,
72{
73 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74 f.debug_struct("Unfold").field("state", &self.state).finish()
75 }
76}
77
78impl<T, F, Fut, Item> FusedStream for Unfold<T, F, Fut>
79where
80 F: FnMut(T) -> Fut,
81 Fut: Future<Output = Option<(Item, T)>>,
82{
83 fn is_terminated(&self) -> bool {
84 if let UnfoldState::Empty = self.state {
85 true
86 } else {
87 false
88 }
89 }
90}
91
92impl<T, F, Fut, Item> Stream for Unfold<T, F, Fut>
93where
94 F: FnMut(T) -> Fut,
95 Fut: Future<Output = Option<(Item, T)>>,
96{
97 type Item = Item;
98
99 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
100 let mut this = self.project();
101
102 if let Some(state) = this.state.as_mut().take_value() {
103 this.state.set(UnfoldState::Future { future: (this.f)(state) });
104 }
105
106 let step = match this.state.as_mut().project_future() {
107 Some(fut) => ready!(fut.poll(cx)),
108 None => panic!("Unfold must not be polled after it returned `Poll::Ready(None)`"),
109 };
110
111 if let Some((item, next_state)) = step {
112 this.state.set(UnfoldState::Value { value: next_state });
113 Poll::Ready(Some(item))
114 } else {
115 this.state.set(UnfoldState::Empty);
116 Poll::Ready(None)
117 }
118 }
119}