tower/util/
ready.rs

1use std::{fmt, marker::PhantomData};
2
3use std::{
4    future::Future,
5    pin::Pin,
6    task::{ready, Context, Poll},
7};
8use tower_service::Service;
9
10/// A [`Future`] that yields the service when it is ready to accept a request.
11///
12/// [`ReadyOneshot`] values are produced by [`ServiceExt::ready_oneshot`].
13///
14/// [`ServiceExt::ready_oneshot`]: crate::util::ServiceExt::ready_oneshot
15pub struct ReadyOneshot<T, Request> {
16    inner: Option<T>,
17    _p: PhantomData<fn() -> Request>,
18}
19
20// Safety: This is safe because `Services`'s are always `Unpin`.
21impl<T, Request> Unpin for ReadyOneshot<T, Request> {}
22
23impl<T, Request> ReadyOneshot<T, Request>
24where
25    T: Service<Request>,
26{
27    #[allow(missing_docs)]
28    pub const fn new(service: T) -> Self {
29        Self {
30            inner: Some(service),
31            _p: PhantomData,
32        }
33    }
34}
35
36impl<T, Request> Future for ReadyOneshot<T, Request>
37where
38    T: Service<Request>,
39{
40    type Output = Result<T, T::Error>;
41
42    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
43        ready!(self
44            .inner
45            .as_mut()
46            .expect("poll after Poll::Ready")
47            .poll_ready(cx))?;
48
49        Poll::Ready(Ok(self.inner.take().expect("poll after Poll::Ready")))
50    }
51}
52
53impl<T, Request> fmt::Debug for ReadyOneshot<T, Request>
54where
55    T: fmt::Debug,
56{
57    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
58        f.debug_struct("ReadyOneshot")
59            .field("inner", &self.inner)
60            .finish()
61    }
62}
63
64/// A future that yields a mutable reference to the service when it is ready to accept a request.
65///
66/// [`Ready`] values are produced by [`ServiceExt::ready`].
67///
68/// [`ServiceExt::ready`]: crate::util::ServiceExt::ready
69pub struct Ready<'a, T, Request>(ReadyOneshot<&'a mut T, Request>);
70
71// Safety: This is safe for the same reason that the impl for ReadyOneshot is safe.
72impl<T, Request> Unpin for Ready<'_, T, Request> {}
73
74impl<'a, T, Request> Ready<'a, T, Request>
75where
76    T: Service<Request>,
77{
78    #[allow(missing_docs)]
79    pub fn new(service: &'a mut T) -> Self {
80        Self(ReadyOneshot::new(service))
81    }
82}
83
84impl<'a, T, Request> Future for Ready<'a, T, Request>
85where
86    T: Service<Request>,
87{
88    type Output = Result<&'a mut T, T::Error>;
89
90    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
91        Pin::new(&mut self.0).poll(cx)
92    }
93}
94
95impl<T, Request> fmt::Debug for Ready<'_, T, Request>
96where
97    T: fmt::Debug,
98{
99    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
100        f.debug_tuple("Ready").field(&self.0).finish()
101    }
102}