futures_core/future/
result.rs

1use {Future, IntoFuture, Poll, Async};
2use task;
3
4/// A future representing a value that is immediately ready.
5///
6/// Created by the [`result`](::future::result), [`ok`](::future::ok) or
7/// [`err`](::future::err) functions.
8#[derive(Debug, Clone)]
9#[must_use = "futures do nothing unless polled"]
10pub struct FutureResult<T, E> {
11    inner: Option<Result<T, E>>,
12}
13
14impl<T, E> IntoFuture for Result<T, E> {
15    type Future = FutureResult<T, E>;
16    type Item = T;
17    type Error = E;
18
19    fn into_future(self) -> Self::Future {
20        result(self)
21    }
22}
23
24/// Creates a new future that will immediate resolve with the given result.
25///
26/// # Examples
27///
28/// ```
29/// use futures_core::future::*;
30///
31/// let future_of_1 = result::<u32, u32>(Ok(1));
32/// let future_of_err_2 = result::<u32, u32>(Err(2));
33/// ```
34pub fn result<T, E>(r: Result<T, E>) -> FutureResult<T, E> {
35    FutureResult { inner: Some(r) }
36}
37
38/// Creates a new future that will immediately resolve successfully to the given value.
39///
40/// # Examples
41///
42/// ```
43/// use futures_core::future::*;
44///
45/// let future_of_1 = ok::<u32, u32>(1);
46/// ```
47pub fn ok<T, E>(t: T) -> FutureResult<T, E> {
48    result(Ok(t))
49}
50
51/// Creates a new future that will immediately fail with the given error.
52///
53/// # Examples
54///
55/// ```
56/// use futures_core::future::*;
57///
58/// let future_of_err_1 = err::<u32, u32>(1);
59/// ```
60pub fn err<T, E>(e: E) -> FutureResult<T, E> {
61    result(Err(e))
62}
63
64impl<T, E> Future for FutureResult<T, E> {
65    type Item = T;
66    type Error = E;
67
68    fn poll(&mut self, _: &mut task::Context) -> Poll<T, E> {
69        self.inner.take().expect("cannot poll Result twice").map(Async::Ready)
70    }
71}
72
73impl<T, E> From<Result<T, E>> for FutureResult<T, E> {
74    fn from(r: Result<T, E>) -> Self {
75        result(r)
76    }
77}