Skip to content
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

add stream::from_fn #130

Closed
wants to merge 5 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
104 changes: 104 additions & 0 deletions src/stream/from_fn.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
use futures::stream::Stream;
use pin_utils::{unsafe_pinned, unsafe_unpinned};

use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

/// Creates a new stream where each iteration calls the provided closure.
///
/// This allows creating a custom stream with any behavior
/// without using the more verbose syntax of creating a dedicated type
/// and implementing the `Stream` trait for it.
///
/// Note that the `FromFn` stream doesn’t make assumptions about the behavior of the closure,
/// and therefore conservatively does not implement [`FusedStream`](futures_core::stream::FusedStream).
///
/// The closure can use captures and its environment to track state across iterations. Depending on
/// how the stream is used, this may require specifying the `move` keyword on the closure.
///
/// # Examples
///
/// ```
/// # futures::executor::block_on(async {
/// use async_std::{future, stream};
/// use std::sync::atomic::{AtomicUsize, Ordering};
///
/// static COUNT: AtomicUsize = AtomicUsize::new(0);
/// let stream = stream::from_fn(|| {
/// // Increment our count. This is why we started at zero.
///
/// let count = COUNT.fetch_add(1, Ordering::SeqCst);
///
/// // Check to see if we've finished counting or not.
/// if count < 6 {
/// future::ready(Some(count))
/// } else {
/// future::ready(None)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should make this an async closure (closure of async block) instead

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately, probably the equivalent of this cannot be written by async/await at this time. (see rust-lang/futures-rs#1842 (comment))

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(This is one of the unuseful features I mentioned in #129 (comment).)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My understanding is that it can't close over futures, but it can access statics, which may make it more useful?

/// }
/// });
/// assert_eq!(stream.collect::<Vec<_>>().await, &[1, 2, 3, 4, 5]);
/// # });
/// ```
pub fn from_fn<F, Fut, Item>(f: F) -> FromFn<F, Fut>
where
F: FnMut() -> Fut,
Fut: Future<Output = Option<Item>>,
{
FromFn { f, fut: None }
}

/// A stream where each iteration calls the provided closure.
///
/// This `struct` is created by the [`stream::from_fn`] function.
/// See its documentation for more.
///
/// [`stream::from_fn`]: fn.from_fn.html
#[must_use = "streams do nothing unless polled"]
pub struct FromFn<F, Fut> {
f: F,
fut: Option<Fut>,
}

impl<F, Fut: Unpin> Unpin for FromFn<F, Fut> {}

impl<F, Fut> fmt::Debug for FromFn<F, Fut>
where
Fut: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FromFn").finish()
}
}

impl<F, Fut> FromFn<F, Fut> {
unsafe_unpinned!(f: F);
unsafe_pinned!(fut: Option<Fut>);
}

impl<F, Fut, Item> Stream for FromFn<F, Fut>
where
F: FnMut() -> Fut,
Fut: Future<Output = Option<Item>>,
{
type Item = Item;

#[inline]
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
if self.fut.is_none() {
let fut = (self.as_mut().f())();
self.as_mut().fut().set(Some(fut));
}

self.as_mut()
.fut()
.as_pin_mut()
.unwrap()
.poll(cx)
.map(|item| {
self.as_mut().fut().set(None);
item
})
}
}
2 changes: 2 additions & 0 deletions src/stream/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,13 @@
//! ```

pub use empty::{empty, Empty};
pub use from_fn::{from_fn, FromFn};
pub use once::{once, Once};
pub use repeat::{repeat, Repeat};
pub use stream::{Stream, Take};

mod empty;
mod from_fn;
mod once;
mod repeat;
mod stream;