rama_core/layer/
map_state.rs1use crate::{Context, Layer, Service};
2use rama_utils::macros::define_inner_service_accessors;
3
4pub struct MapState<S, F> {
7 inner: S,
8 f: F,
9}
10
11impl<S: std::fmt::Debug, F> std::fmt::Debug for MapState<S, F> {
12 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
13 f.debug_struct("MapState")
14 .field("inner", &self.inner)
15 .field("f", &format_args!("{}", std::any::type_name::<F>()))
16 .finish()
17 }
18}
19
20impl<S, F> Clone for MapState<S, F>
21where
22 S: Clone,
23 F: Clone,
24{
25 fn clone(&self) -> Self {
26 Self {
27 inner: self.inner.clone(),
28 f: self.f.clone(),
29 }
30 }
31}
32
33impl<S, F> MapState<S, F> {
34 pub const fn new(inner: S, f: F) -> Self {
36 Self { inner, f }
37 }
38
39 define_inner_service_accessors!();
40}
41
42impl<S, F, W, State, Request> Service<State, Request> for MapState<S, F>
43where
44 S: Service<W, Request>,
45 State: Clone + Send + Sync + 'static,
46 W: Send + Sync + 'static,
47 F: FnOnce(State) -> W + Clone + Send + Sync + 'static,
48 Request: Send + 'static,
49{
50 type Response = S::Response;
51 type Error = S::Error;
52
53 #[inline]
54 fn serve(
55 &self,
56 ctx: Context<State>,
57 req: Request,
58 ) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send + '_ {
59 let ctx = ctx.map_state(self.f.clone());
60 self.inner.serve(ctx, req)
61 }
62}
63
64pub struct MapStateLayer<F> {
67 f: F,
68}
69
70impl<F> std::fmt::Debug for MapStateLayer<F> {
71 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72 f.debug_struct("MapStateLayer")
73 .field("f", &format_args!("{}", std::any::type_name::<F>()))
74 .finish()
75 }
76}
77
78impl<F: Clone> Clone for MapStateLayer<F> {
79 fn clone(&self) -> Self {
80 Self { f: self.f.clone() }
81 }
82}
83
84impl<F> MapStateLayer<F> {
85 pub const fn new(f: F) -> Self {
87 Self { f }
88 }
89}
90
91impl<S, F: Clone> Layer<S> for MapStateLayer<F> {
92 type Service = MapState<S, F>;
93
94 fn layer(&self, inner: S) -> Self::Service {
95 MapState::new(inner, self.f.clone())
96 }
97
98 fn into_layer(self, inner: S) -> Self::Service {
99 MapState::new(inner, self.f)
100 }
101}