@@ -14,11 +14,11 @@ use crate::task::{Context, Poll};
1414#[ derive( Debug ) ]
1515pub struct Successors < F , Fut , T >
1616where
17- Fut : Future < Output = T > ,
17+ Fut : Future < Output = Option < T > > ,
1818{
1919 successor : F ,
2020 future : Option < Fut > ,
21- next : T ,
21+ next : Option < T > ,
2222 _marker : PhantomData < Fut > ,
2323}
2424
@@ -33,24 +33,35 @@ where
3333/// use async_std::prelude::*;
3434/// use async_std::stream;
3535///
36- /// let s = stream::successors(22 , |val| {
36+ /// let s = stream::successors(Some(22) , |val| {
3737/// async move {
38- /// val + 1
38+ /// Some( val + 1)
3939/// }
4040/// });
4141///
4242/// pin_utils::pin_mut!(s);
4343/// assert_eq!(s.next().await, Some(23));
4444/// assert_eq!(s.next().await, Some(24));
4545/// assert_eq!(s.next().await, Some(25));
46+ ///
47+ ///
48+ ///let never = stream::successors(None, |val: usize| {
49+ /// async move {
50+ /// Some(val + 1)
51+ /// }
52+ /// });
53+ ///
54+ /// pin_utils::pin_mut!(never);
55+ /// assert_eq!(never.next().await, None);
56+ /// assert_eq!(never.next().await, None);
4657/// #
4758/// # }) }
4859///
4960/// ```
50- pub fn successors < F , Fut , T > ( start : T , func : F ) -> Successors < F , Fut , T >
61+ pub fn successors < F , Fut , T > ( start : Option < T > , func : F ) -> Successors < F , Fut , T >
5162where
5263 F : FnMut ( T ) -> Fut ,
53- Fut : Future < Output = T > ,
64+ Fut : Future < Output = Option < T > > ,
5465 T : Copy ,
5566{
5667 Successors {
@@ -64,26 +75,30 @@ where
6475impl < F , Fut , T > Successors < F , Fut , T >
6576where
6677 F : FnMut ( T ) -> Fut ,
67- Fut : Future < Output = T > ,
78+ Fut : Future < Output = Option < T > > ,
6879 T : Copy ,
6980{
7081 pin_utils:: unsafe_unpinned!( successor: F ) ;
71- pin_utils:: unsafe_unpinned!( next: T ) ;
82+ pin_utils:: unsafe_unpinned!( next: Option < T > ) ;
7283 pin_utils:: unsafe_pinned!( future: Option <Fut >) ;
7384}
7485
7586impl < F , Fut , T > Stream for Successors < F , Fut , T >
7687where
77- Fut : Future < Output = T > ,
88+ Fut : Future < Output = Option < T > > ,
7889 F : FnMut ( T ) -> Fut ,
7990 T : Copy ,
8091{
8192 type Item = T ;
8293
8394 fn poll_next ( mut self : Pin < & mut Self > , cx : & mut Context < ' _ > ) -> Poll < Option < Self :: Item > > {
95+ if self . next . is_none ( ) {
96+ return Poll :: Ready ( None ) ;
97+ }
98+
8499 match & self . future {
85100 None => {
86- let x = self . next ;
101+ let x = self . next . unwrap ( ) ;
87102 let fut = ( self . as_mut ( ) . successor ( ) ) ( x) ;
88103 self . as_mut ( ) . future ( ) . set ( Some ( fut) ) ;
89104 }
93108 let next = futures_core:: ready!( self . as_mut( ) . future( ) . as_pin_mut( ) . unwrap( ) . poll( cx) ) ;
94109 * self . as_mut ( ) . next ( ) = next;
95110 self . as_mut ( ) . future ( ) . set ( None ) ;
96- Poll :: Ready ( Some ( next) )
111+ Poll :: Ready ( next)
97112 }
98113}
0 commit comments