ntex_util/future/
ready.rs

1//! Definition of the `Ready` (immediately finished) future
2use std::{future::Future, pin::Pin, task::Context, task::Poll};
3
4/// A future representing a value that is immediately ready.
5///
6/// Created by the `result` function.
7#[derive(Debug, Clone)]
8#[must_use = "futures do nothing unless polled"]
9pub enum Ready<T, E> {
10    Ok(T),
11    Err(E),
12    Done(Sealed),
13}
14
15#[derive(Debug, Clone)]
16pub struct Sealed;
17
18impl<T, E> Unpin for Ready<T, E> {}
19
20impl<T, E> Future for Ready<T, E> {
21    type Output = Result<T, E>;
22
23    #[inline]
24    fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
25        let result = std::mem::replace(self.get_mut(), Ready::Done(Sealed));
26        match result {
27            Ready::Ok(ok) => Poll::Ready(Ok(ok)),
28            Ready::Err(err) => Poll::Ready(Err(err)),
29            Ready::Done(_) => panic!("cannot poll completed Ready future"),
30        }
31    }
32}
33
34impl<T, E> From<Result<T, E>> for Ready<T, E> {
35    fn from(r: Result<T, E>) -> Self {
36        match r {
37            Ok(v) => Ready::Ok(v),
38            Err(e) => Ready::Err(e),
39        }
40    }
41}
42
43#[cfg(test)]
44mod test {
45    use std::future::poll_fn;
46
47    use super::*;
48
49    #[ntex_macros::rt_test2]
50    async fn ready() {
51        let ok = Ok::<_, ()>("ok");
52        let mut f = Ready::from(ok);
53        let res = poll_fn(|cx| Pin::new(&mut f).poll(cx)).await;
54        assert_eq!(res.unwrap(), "ok");
55        let err = Err::<(), _>("err");
56        let mut f = Ready::from(err);
57        let res = poll_fn(|cx| Pin::new(&mut f).poll(cx)).await;
58        assert_eq!(res.unwrap_err(), "err");
59    }
60}