@@ -29,8 +29,10 @@ mod find_map;
2929mod min_by;
3030mod next;
3131mod nth;
32+ mod scan;
3233mod take;
3334
35+ pub use scan:: Scan ;
3436pub use take:: Take ;
3537
3638use all:: AllFuture ;
@@ -501,6 +503,49 @@ pub trait Stream {
501503 f,
502504 }
503505 }
506+
507+ /// A stream adaptor similar to [`fold`] that holds internal state and produces a new stream.
508+ ///
509+ /// [`fold`]: #method.fold
510+ ///
511+ /// `scan()` takes two arguments: an initial value which seeds the internal state, and a
512+ /// closure with two arguments, the first being a mutable reference to the internal state and
513+ /// the second a stream element. The closure can assign to the internal state to share state
514+ /// between iterations.
515+ ///
516+ /// On iteration, the closure will be applied to each element of the stream and the return
517+ /// value from the closure, an `Option`, is yielded by the stream.
518+ ///
519+ /// ## Examples
520+ ///
521+ /// ```
522+ /// # fn main() { async_std::task::block_on(async {
523+ /// #
524+ /// use std::collections::VecDeque;
525+ /// use async_std::stream::Stream;
526+ ///
527+ /// let s: VecDeque<isize> = vec![1, 2, 3].into_iter().collect();
528+ /// let mut s = s.scan(1, |state, x| {
529+ /// *state = *state * x;
530+ /// Some(-*state)
531+ /// });
532+ ///
533+ /// assert_eq!(s.next().await, Some(-1));
534+ /// assert_eq!(s.next().await, Some(-2));
535+ /// assert_eq!(s.next().await, Some(-6));
536+ /// assert_eq!(s.next().await, None);
537+ /// #
538+ /// # }) }
539+ /// ```
540+ #[ inline]
541+ fn scan < St , B , F > ( self , initial_state : St , f : F ) -> Scan < Self , St , F >
542+ where
543+ Self : Sized ,
544+ St : Unpin ,
545+ F : Unpin + FnMut ( & mut St , Self :: Item ) -> Option < B > ,
546+ {
547+ Scan :: new ( self , initial_state, f)
548+ }
504549}
505550
506551impl < T : futures_core:: stream:: Stream + Unpin + ?Sized > Stream for T {
0 commit comments