-
Notifications
You must be signed in to change notification settings - Fork 341
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
192: Add Stream::scan r=stjepang a=tirr-c Ref #129. The mapper function `f` is synchronous and returns bare `Option<B>`. Asynchronous `f` seems tricky to implement right. It requires the wrapper to be self-referential, as a reference to internal state may be captured by the returned future. Co-authored-by: Wonwoo Choi <[email protected]>
- Loading branch information
Showing
3 changed files
with
88 additions
and
1 deletion.
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
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
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,42 @@ | ||
use crate::task::{Context, Poll}; | ||
|
||
use std::pin::Pin; | ||
|
||
/// A stream to maintain state while polling another stream. | ||
#[derive(Debug)] | ||
pub struct Scan<S, St, F> { | ||
stream: S, | ||
state_f: (St, F), | ||
} | ||
|
||
impl<S, St, F> Scan<S, St, F> { | ||
pub(crate) fn new(stream: S, initial_state: St, f: F) -> Self { | ||
Self { | ||
stream, | ||
state_f: (initial_state, f), | ||
} | ||
} | ||
|
||
pin_utils::unsafe_pinned!(stream: S); | ||
pin_utils::unsafe_unpinned!(state_f: (St, F)); | ||
} | ||
|
||
impl<S: Unpin, St, F> Unpin for Scan<S, St, F> {} | ||
|
||
impl<S, St, F, B> futures_core::stream::Stream for Scan<S, St, F> | ||
where | ||
S: futures_core::stream::Stream, | ||
F: FnMut(&mut St, S::Item) -> Option<B>, | ||
{ | ||
type Item = B; | ||
|
||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<B>> { | ||
let poll_result = self.as_mut().stream().poll_next(cx); | ||
poll_result.map(|item| { | ||
item.and_then(|item| { | ||
let (state, f) = self.as_mut().state_f(); | ||
f(state, item) | ||
}) | ||
}) | ||
} | ||
} |