vector/sinks/util/service/
map.rs

1use std::{
2    fmt,
3    sync::Arc,
4    task::{Context, Poll},
5};
6
7use tower::{Layer, Service};
8
9pub struct MapLayer<R1, R2> {
10    f: Arc<dyn Fn(R1) -> R2 + Send + Sync + 'static>,
11}
12
13impl<R1, R2> MapLayer<R1, R2> {
14    pub(crate) fn new(f: Arc<dyn Fn(R1) -> R2 + Send + Sync + 'static>) -> Self {
15        Self { f }
16    }
17}
18
19impl<S, R1, R2> Layer<S> for MapLayer<R1, R2>
20where
21    S: Service<R2>,
22{
23    type Service = Map<S, R1, R2>;
24
25    fn layer(&self, inner: S) -> Self::Service {
26        Map {
27            f: Arc::clone(&self.f),
28            inner,
29        }
30    }
31}
32
33pub struct Map<S, R1, R2> {
34    f: Arc<dyn Fn(R1) -> R2 + Send + Sync + 'static>,
35    pub(crate) inner: S,
36}
37
38impl<S, R1, R2> Service<R1> for Map<S, R1, R2>
39where
40    S: Service<R2>,
41{
42    type Response = S::Response;
43    type Error = S::Error;
44    type Future = S::Future;
45
46    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
47        self.inner.poll_ready(cx)
48    }
49
50    fn call(&mut self, req: R1) -> Self::Future {
51        let req = (self.f)(req);
52        self.inner.call(req)
53    }
54}
55
56impl<S, R1, R2> Clone for Map<S, R1, R2>
57where
58    S: Clone,
59{
60    fn clone(&self) -> Self {
61        Self {
62            f: Arc::clone(&self.f),
63            inner: self.inner.clone(),
64        }
65    }
66}
67
68impl<S, R1, R2> fmt::Debug for Map<S, R1, R2>
69where
70    S: fmt::Debug,
71{
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        f.debug_struct("Map").field("inner", &self.inner).finish()
74    }
75}