futures_util/future/
map.rs

1use futures_core::{Future, Poll, Async};
2use futures_core::task;
3
4/// Future for the `map` combinator, changing the type of a future.
5///
6/// This is created by the `Future::map` method.
7#[derive(Debug)]
8#[must_use = "futures do nothing unless polled"]
9pub struct Map<A, F> where A: Future {
10    future: A,
11    f: Option<F>,
12}
13
14pub fn new<A, F>(future: A, f: F) -> Map<A, F>
15    where A: Future,
16{
17    Map {
18        future: future,
19        f: Some(f),
20    }
21}
22
23impl<U, A, F> Future for Map<A, F>
24    where A: Future,
25          F: FnOnce(A::Item) -> U,
26{
27    type Item = U;
28    type Error = A::Error;
29
30    fn poll(&mut self, cx: &mut task::Context) -> Poll<U, A::Error> {
31        let e = match self.future.poll(cx) {
32            Ok(Async::Pending) => return Ok(Async::Pending),
33            Ok(Async::Ready(e)) => Ok(e),
34            Err(e) => Err(e),
35        };
36        e.map(self.f.take().expect("cannot poll Map twice"))
37         .map(Async::Ready)
38    }
39}