-
Notifications
You must be signed in to change notification settings - Fork 341
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
Closed
add stream::from_fn #130
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
/// } | ||
/// }); | ||
/// 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 | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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))
There was a problem hiding this comment.
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).)
There was a problem hiding this comment.
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
static
s, which may make it more useful?