actix/fut/future/
result.rs

1//! Definition of the [`Ready`] (immediately finished) combinator
2
3use std::{
4    future::Future,
5    pin::Pin,
6    task::{self, Poll},
7};
8
9// TODO: remove re-export and encourage direct usage of std and/or futures crate types.
10pub use futures_util::future::{ready, Ready};
11
12use crate::{actor::Actor, fut::ActorFuture};
13
14/// Creates a new "leaf future" which will resolve with the given result.
15///
16/// The returned future represents a computation which is finished immediately.
17/// This can be useful with the `finished` and `failed` base future types to
18/// convert an immediate value to a future to interoperate elsewhere.
19///
20/// # Examples
21///
22/// ```
23/// use actix::{fut, Actor, Context};
24///
25/// struct MyActor;
26/// impl Actor for MyActor {
27///     type Context = Context<Self>;
28/// }
29///
30/// let future_of_1 = fut::result::<u32, u32>(Ok(1));
31/// let future_of_err_2 = fut::result::<u32, u32>(Err(2));
32/// ```
33pub fn result<T, E>(r: Result<T, E>) -> Ready<Result<T, E>> {
34    ready(r)
35}
36
37/// Creates a "leaf future" from an immediate value of a finished and
38/// successful computation.
39///
40/// The returned future is similar to `result` where it will immediately run a
41/// scheduled callback with the provided value.
42///
43/// # Examples
44///
45/// ```
46/// use actix::fut::*;
47/// use actix::{Actor, Context};
48///
49/// struct MyActor;
50/// impl Actor for MyActor {
51///     type Context = Context<Self>;
52/// }
53///
54/// let future_of_1 = ok::<u32, u32>(1);
55/// ```
56pub fn ok<T, E>(t: T) -> Ready<Result<T, E>> {
57    ready(Ok(t))
58}
59
60/// Creates a "leaf future" from an immediate value of a failed computation.
61///
62/// The returned future is similar to `result` where it will immediately run a
63/// scheduled callback with the provided value.
64///
65/// # Examples
66///
67/// ```
68/// use actix::{fut, Actor, Context};
69///
70/// struct MyActor;
71/// impl Actor for MyActor {
72///     type Context = Context<Self>;
73/// }
74///
75/// let future_of_err_1 = fut::err::<u32, u32>(1);
76/// ```
77pub fn err<T, E>(e: E) -> Ready<Result<T, E>> {
78    ready(Err(e))
79}
80
81impl<T, A> ActorFuture<A> for Ready<T>
82where
83    A: Actor,
84{
85    type Output = T;
86
87    #[inline]
88    fn poll(
89        self: Pin<&mut Self>,
90        _: &mut A,
91        _: &mut A::Context,
92        cx: &mut task::Context<'_>,
93    ) -> Poll<Self::Output> {
94        Future::poll(self, cx)
95    }
96}