hyper_util/service/
glue.rs

1use pin_project_lite::pin_project;
2use std::{
3    future::Future,
4    pin::Pin,
5    task::{Context, Poll},
6};
7
8use super::Oneshot;
9
10/// A tower service converted into a hyper service.
11#[derive(Debug, Copy, Clone)]
12pub struct TowerToHyperService<S> {
13    service: S,
14}
15
16impl<S> TowerToHyperService<S> {
17    /// Create a new `TowerToHyperService` from a tower service.
18    pub fn new(tower_service: S) -> Self {
19        Self {
20            service: tower_service,
21        }
22    }
23}
24
25impl<S, R> hyper::service::Service<R> for TowerToHyperService<S>
26where
27    S: tower_service::Service<R> + Clone,
28{
29    type Response = S::Response;
30    type Error = S::Error;
31    type Future = TowerToHyperServiceFuture<S, R>;
32
33    fn call(&self, req: R) -> Self::Future {
34        TowerToHyperServiceFuture {
35            future: Oneshot::new(self.service.clone(), req),
36        }
37    }
38}
39
40pin_project! {
41    /// Response future for [`TowerToHyperService`].
42    pub struct TowerToHyperServiceFuture<S, R>
43    where
44        S: tower_service::Service<R>,
45    {
46        #[pin]
47        future: Oneshot<S, R>,
48    }
49}
50
51impl<S, R> Future for TowerToHyperServiceFuture<S, R>
52where
53    S: tower_service::Service<R>,
54{
55    type Output = Result<S::Response, S::Error>;
56
57    #[inline]
58    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
59        self.project().future.poll(cx)
60    }
61}