Skip to content

Add stream successors #359

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/stream/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub use repeat_with::{repeat_with, RepeatWith};
pub use stream::{
Chain, Filter, Fuse, Inspect, Scan, Skip, SkipWhile, StepBy, Stream, Take, TakeWhile, Zip,
};
pub use successors::{successors, Successors};

pub(crate) mod stream;

Expand All @@ -39,6 +40,7 @@ mod from_fn;
mod once;
mod repeat;
mod repeat_with;
mod successors;

cfg_if! {
if #[cfg(any(feature = "unstable", feature = "docs"))] {
Expand Down
61 changes: 61 additions & 0 deletions src/stream/successors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
use std::pin::Pin;

use crate::stream::Stream;
use crate::task::{Context, Poll};

/// Creates a new stream where each successive item is computed based on the preceding one.
/// The stream starts with the given first item (if any) and calls the given FnMut(&T) -> Option<T> closure to compute each item’s successor.
///
/// # Examples
///
/// ```
/// # async_std::task::block_on(async {
/// #
/// use async_std::prelude::*;
/// use async_std::stream;
///
/// let powers_of_10 = stream::successors(Some(1_u16), |n| n.checked_mul(10));
/// assert_eq!(powers_of_10.collect::<Vec<_>>().await, &[1, 10, 100, 1_000, 10_000]);
///
/// #
/// # })
/// ```
pub fn successors<T, F>(first: Option<T>, succ: F) -> Successors<T, F>
where
F: FnMut(&T) -> Option<T>,
{
Successors { next: first, succ }
}

/// An new stream where each successive item is computed based on the preceding one.
///
/// This `struct` is created by the [`successors`] function.
/// See its documentation for more.
///
/// [`successors`]: fn.successors.html
#[derive(Clone, Debug)]
pub struct Successors<T, F> {
next: Option<T>,
succ: F,
}

impl<T, F> Successors<T, F> {
pin_utils::unsafe_unpinned!(next: Option<T>);
pin_utils::unsafe_unpinned!(succ: F);
}

impl<T, F> Stream for Successors<T, F>
where
F: FnMut(&T) -> Option<T>,
{
type Item = T;

fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let item = self.as_mut().next().take().map(|item| {
*self.as_mut().next() = (self.as_mut().succ())(&item);
item
});

Poll::Ready(item)
}
}