tokio_stream/stream_ext/
map.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 Map<St, F> {
13 #[pin]
14 stream: St,
15 f: F,
16 }
17}
18
19impl<St, F> fmt::Debug for Map<St, F>
20where
21 St: fmt::Debug,
22{
23 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24 f.debug_struct("Map").field("stream", &self.stream).finish()
25 }
26}
27
28impl<St, F> Map<St, F> {
29 pub(super) fn new(stream: St, f: F) -> Self {
30 Map { stream, f }
31 }
32}
33
34impl<St, F, T> Stream for Map<St, F>
35where
36 St: Stream,
37 F: FnMut(St::Item) -> T,
38{
39 type Item = T;
40
41 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<T>> {
42 self.as_mut()
43 .project()
44 .stream
45 .poll_next(cx)
46 .map(|opt| opt.map(|x| (self.as_mut().project().f)(x)))
47 }
48
49 fn size_hint(&self) -> (usize, Option<usize>) {
50 self.stream.size_hint()
51 }
52}
53
54impl<St, F, T> FusedStream for Map<St, F>
55where
56 St: FusedStream,
57 F: FnMut(St::Item) -> T,
58{
59 fn is_terminated(&self) -> bool {
60 self.stream.is_terminated()
61 }
62}