Skip to content

Improve readability for stream::map with named struct #1

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 1 commit into from
Closed
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
13 changes: 10 additions & 3 deletions src/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,17 @@ pub fn map<St, U, F>(stream: St, f: F) -> impl Stream<Item = U>
where St: Stream,
F: FnMut(St::Item) -> U,
{
// stream::unfold accepts the initial state and a closure accepting the state
// the closure returns Future(None) as a terminate value
// to produce a value for the stream the closure returns Future( Some(value, state) )

// So State is a named struct to be destructured in the closure arg to improve readability
struct State<St, F> { stream: Pin<Box<St>>, f: F }

let stream = Box::pin(stream);
futures::stream::unfold((stream, f), async move | (mut stream, mut f)| {
let item = await!(next(&mut stream));
item.map(|item| (f(item), (stream, f)))
futures::stream::unfold(State { stream, f }, async move |State { mut stream, mut f }| {
let item : Option<St::Item> = await!(next(&mut stream));
item.map(|item| (f(item), State { stream, f }))
})
}

Expand Down