spacegate_kernel/helper_layers/
map_future.rs

1use hyper::service::Service;
2use std::{fmt, future::Future};
3use tower_layer::Layer;
4
5/// [`Service`] returned by the [`map_future`] combinator.
6#[derive(Clone)]
7pub struct MapFuture<S, F> {
8    inner: S,
9    f: F,
10}
11
12impl<S, F> MapFuture<S, F> {
13    /// Creates a new [`MapFuture`] service.
14    pub fn new(inner: S, f: F) -> Self {
15        Self { inner, f }
16    }
17
18    /// Returns a new [`Layer`] that produces [`MapFuture`] services.
19    ///
20    /// This is a convenience function that simply calls [`MapFutureLayer::new`].
21    ///
22    /// [`Layer`]: tower_layer::Layer
23    pub fn layer(f: F) -> MapFutureLayer<F> {
24        MapFutureLayer::new(f)
25    }
26
27    /// Get a reference to the inner service
28    pub fn get_ref(&self) -> &S {
29        &self.inner
30    }
31
32    /// Get a mutable reference to the inner service
33    pub fn get_mut(&mut self) -> &mut S {
34        &mut self.inner
35    }
36
37    /// Consume `self`, returning the inner service
38    pub fn into_inner(self) -> S {
39        self.inner
40    }
41}
42
43impl<R, S, F, T, E, Fut> Service<R> for MapFuture<S, F>
44where
45    S: Service<R>,
46    F: Fn(S::Future) -> Fut,
47    E: From<S::Error>,
48    Fut: Future<Output = Result<T, E>>,
49{
50    type Response = T;
51    type Error = E;
52    type Future = Fut;
53
54    fn call(&self, req: R) -> Self::Future {
55        let fut = self.inner.call(req);
56        (self.f)(fut)
57    }
58}
59
60impl<S, F> fmt::Debug for MapFuture<S, F>
61where
62    S: fmt::Debug,
63{
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        f.debug_struct("MapFuture").field("inner", &self.inner).field("f", &format_args!("{}", std::any::type_name::<F>())).finish()
66    }
67}
68
69/// A [`Layer`] that produces a [`MapFuture`] service.
70///
71/// [`Layer`]: tower_layer::Layer
72#[derive(Clone)]
73pub struct MapFutureLayer<F> {
74    f: F,
75}
76
77impl<F> MapFutureLayer<F> {
78    /// Creates a new [`MapFutureLayer`] layer.
79    pub fn new(f: F) -> Self {
80        Self { f }
81    }
82}
83
84impl<S, F> Layer<S> for MapFutureLayer<F>
85where
86    F: Clone,
87{
88    type Service = MapFuture<S, F>;
89
90    fn layer(&self, inner: S) -> Self::Service {
91        MapFuture::new(inner, self.f.clone())
92    }
93}
94
95impl<F> fmt::Debug for MapFutureLayer<F> {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        f.debug_struct("MapFutureLayer").field("f", &format_args!("{}", std::any::type_name::<F>())).finish()
98    }
99}