Skip to content

Commit 3df1c4c

Browse files
committed
Improve readability for stream::map with named struct
1 parent 44ba8e9 commit 3df1c4c

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
@@ -27,10 +27,17 @@ pub fn map<St, U, F>(stream: St, f: F) -> impl Stream<Item = U>
2727
where F: FnMut(St::Item) -> U,
2828
St: Stream,
2929
{
30+
// stream::unfold accepts the initial state and a closure accepting the state
31+
// the closure returns Future(None) as a terminate value
32+
// to produce a value for the stream the closure returns Future( Some(value, state) )
33+
34+
// So State is a named struct to be destructured in the closure arg to improve readability
35+
struct State<St, F> { stream: Pin<Box<St>>, f: F }
36+
3037
let stream = Box::pin(stream);
31-
futures::stream::unfold((stream, f), async move | (mut stream, mut f)| {
32-
let item = await!(next(&mut stream));
33-
item.map(|item| (f(item), (stream, f)))
38+
futures::stream::unfold(State { stream, f }, async move |State { mut stream, mut f }| {
39+
let item : Option<St::Item> = await!(next(&mut stream));
40+
item.map(|item| (f(item), State { stream, f }))
3441
})
3542
}
3643

0 commit comments

Comments
 (0)