ntex_service/
map_state.rs1use crate::{Ctx, IntoService, IntoServiceFactory, Service, ServiceFactory};
2
3pub fn map_state<S, St, Req>(st: St, s: impl IntoService<S, St, Req>) -> MapState<S, St>
9where
10 S: Service<St, Req>,
11{
12 MapState {
13 st,
14 s: s.into_service(),
15 }
16}
17
18pub fn map_state_factory<Sf, St, Req>(
22 st: St,
23 sf: impl IntoServiceFactory<Sf, St, Req>,
24) -> MapStateFactory<Sf, St>
25where
26 Sf: ServiceFactory<St, Req>,
27 St: Clone,
28{
29 MapStateFactory {
30 st,
31 sf: sf.into_factory(),
32 }
33}
34
35#[derive(Clone, Debug)]
36pub struct MapState<S, St> {
42 s: S,
43 st: St,
44}
45
46impl<OtSt, S, St, Req> Service<OtSt, Req> for MapState<S, St>
47where
48 S: Service<St, Req>,
49{
50 type Res = S::Res;
51 type Error = S::Error;
52
53 fn bind(&self, ctx: crate::BindCtx<'_>) {
54 ctx.bind(&self.s);
55 }
56
57 #[inline]
58 #[allow(clippy::manual_async_fn)]
59 fn call(
60 &self,
61 req: Req,
62 ctx: Ctx<'_, Self, OtSt>,
63 ) -> impl Future<Output = Result<S::Res, S::Error>> {
64 async move { self.s.call(req, ctx.map_state(&self.st).cast()).await }
66 }
67
68 #[inline]
69 #[allow(clippy::manual_async_fn)]
70 fn ready(&self, ctx: Ctx<'_, Self, OtSt>) -> impl Future<Output = Result<(), S::Error>> {
71 async move { self.s.ready(ctx.map_state(&self.st).cast()).await }
74 }
75
76 #[inline]
77 #[allow(clippy::manual_async_fn)]
78 fn shutdown(&self, ctx: Ctx<'_, Self, OtSt>) -> impl Future<Output = ()> {
79 async move { self.s.shutdown(ctx.map_state(&self.st).cast()).await }
81 }
82}
83
84#[derive(Clone, Debug)]
85pub struct MapStateFactory<Sf, St> {
87 sf: Sf,
88 st: St,
89}
90
91impl<OtSt, Sf, St, Req> ServiceFactory<OtSt, Req> for MapStateFactory<Sf, St>
92where
93 Sf: ServiceFactory<St, Req>,
94 St: Clone,
95{
96 type Res = Sf::Res;
97 type Error = Sf::Error;
98
99 type Service = MapState<Sf::Service, St>;
100 type InitError = Sf::InitError;
101
102 #[inline]
103 async fn create(&self, _: &OtSt) -> Result<Self::Service, Self::InitError> {
104 Ok(MapState {
105 s: self.sf.create(&self.st).await?,
106 st: self.st.clone(),
107 })
108 }
109}
110
111#[cfg(test)]
112#[path = "../tests/unit/map_state.rs"]
113mod tests;