futures_core/future/
option.rs

1//! Definition of the `Option` (optional step) combinator
2
3use {Future, IntoFuture, Poll, Async};
4use task;
5
6/// A future representing a value which may or may not be present.
7///
8/// Created by the `IntoFuture` implementation for `std::option::Option`.
9#[derive(Debug, Clone)]
10#[must_use = "futures do nothing unless polled"]
11pub struct FutureOption<T> {
12    inner: Option<T>,
13}
14
15impl<T> IntoFuture for Option<T> where T: IntoFuture {
16    type Future = FutureOption<T::Future>;
17    type Item = Option<T::Item>;
18    type Error = T::Error;
19
20    fn into_future(self) -> FutureOption<T::Future> {
21        FutureOption { inner: self.map(IntoFuture::into_future) }
22    }
23}
24
25impl<F, T, E> Future for FutureOption<F> where F: Future<Item=T, Error=E> {
26    type Item = Option<T>;
27    type Error = E;
28
29    fn poll(&mut self, cx: &mut task::Context) -> Poll<Option<T>, E> {
30        match self.inner {
31            None => Ok(Async::Ready(None)),
32            Some(ref mut x) => x.poll(cx).map(|x| x.map(Some)),
33        }
34    }
35}
36
37impl<T> From<Option<T>> for FutureOption<T> {
38    fn from(o: Option<T>) -> Self {
39        FutureOption { inner: o }
40    }
41}