tokio_stream/stream_ext/
map_while.rs1use crate::Stream;
2
3use core::fmt;
4use core::pin::Pin;
5use core::task::{Context, Poll};
6use futures_core::FusedStream;
7use pin_project_lite::pin_project;
8
9pin_project! {
10 #[must_use = "streams do nothing unless polled"]
12 pub struct MapWhile<St, F> {
13 #[pin]
14 stream: St,
15 f: F,
16 done: bool,
17 }
18}
19
20impl<St, F> fmt::Debug for MapWhile<St, F>
21where
22 St: fmt::Debug,
23{
24 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25 f.debug_struct("MapWhile")
26 .field("stream", &self.stream)
27 .field("done", &self.done)
28 .finish()
29 }
30}
31
32impl<St, F> MapWhile<St, F> {
33 pub(super) fn new(stream: St, f: F) -> Self {
34 MapWhile {
35 stream,
36 f,
37 done: false,
38 }
39 }
40}
41
42impl<St, F, T> Stream for MapWhile<St, F>
43where
44 St: Stream,
45 F: FnMut(St::Item) -> Option<T>,
46{
47 type Item = T;
48
49 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<T>> {
50 let me = self.project();
51 if *me.done {
52 return Poll::Ready(None);
53 }
54
55 let f = me.f;
56 let done = me.done;
57 me.stream.poll_next(cx).map(|opt| {
58 let mapped = opt.and_then(f);
59 if mapped.is_none() {
60 *done = true;
61 }
62 mapped
63 })
64 }
65
66 fn size_hint(&self) -> (usize, Option<usize>) {
67 if self.done {
68 return (0, Some(0));
69 }
70
71 let (_, upper) = self.stream.size_hint();
72 (0, upper)
73 }
74}
75
76impl<St, F> FusedStream for MapWhile<St, F>
77where
78 Self: Stream,
79{
80 fn is_terminated(&self) -> bool {
81 self.done
82 }
83}