Skip to content

Commit 074fdbd

Browse files
committed
Improve readability for stream::map with named struct
1 parent f4ad1d2 commit 074fdbd

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

src/stream.rs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,17 @@ pub fn map<St, U, F>(stream: St, f: F) -> impl Stream<Item = U>
3030
where St: Stream,
3131
F: FnMut(St::Item) -> U,
3232
{
33+
// stream::unfold accepts the initial state and a closure accepting the state
34+
// the closure returns Future(None) as a terminate value
35+
// to produce a value for the stream the closure returns Future( Some(value, state) )
36+
37+
// So State is a named struct to be destructured in the closure arg to improve readability
38+
struct State<St, F> { stream: Pin<Box<St>>, f: F }
39+
3340
let stream = Box::pin(stream);
34-
futures::stream::unfold((stream, f), async move | (mut stream, mut f)| {
35-
let item = await!(next(&mut stream));
36-
item.map(|item| (f(item), (stream, f)))
41+
futures::stream::unfold(State { stream, f }, async move |State { mut stream, mut f }| {
42+
let item : Option<St::Item> = await!(next(&mut stream));
43+
item.map(|item| (f(item), State { stream, f }))
3744
})
3845
}
3946

0 commit comments

Comments
 (0)