requiem_service/
map_config.rs

1use std::marker::PhantomData;
2
3use super::{IntoServiceFactory, ServiceFactory};
4
5/// Adapt external config argument to a config for provided service factory
6///
7/// Note that this function consumes the receiving service factory and returns
8/// a wrapped version of it.
9pub fn map_config<T, U, F, C>(factory: U, f: F) -> MapConfig<T, F, C>
10where
11    T: ServiceFactory,
12    U: IntoServiceFactory<T>,
13    F: Fn(C) -> T::Config,
14{
15    MapConfig::new(factory.into_factory(), f)
16}
17
18/// Replace config with unit
19pub fn unit_config<T, U, C>(factory: U) -> UnitConfig<T, C>
20where
21    T: ServiceFactory<Config = ()>,
22    U: IntoServiceFactory<T>,
23{
24    UnitConfig::new(factory.into_factory())
25}
26
27/// `map_config()` adapter service factory
28pub struct MapConfig<A, F, C> {
29    a: A,
30    f: F,
31    e: PhantomData<C>,
32}
33
34impl<A, F, C> MapConfig<A, F, C> {
35    /// Create new `MapConfig` combinator
36    pub(crate) fn new(a: A, f: F) -> Self
37    where
38        A: ServiceFactory,
39        F: Fn(C) -> A::Config,
40    {
41        Self {
42            a,
43            f,
44            e: PhantomData,
45        }
46    }
47}
48
49impl<A, F, C> Clone for MapConfig<A, F, C>
50where
51    A: Clone,
52    F: Clone,
53{
54    fn clone(&self) -> Self {
55        Self {
56            a: self.a.clone(),
57            f: self.f.clone(),
58            e: PhantomData,
59        }
60    }
61}
62
63impl<A, F, C> ServiceFactory for MapConfig<A, F, C>
64where
65    A: ServiceFactory,
66    F: Fn(C) -> A::Config,
67{
68    type Request = A::Request;
69    type Response = A::Response;
70    type Error = A::Error;
71
72    type Config = C;
73    type Service = A::Service;
74    type InitError = A::InitError;
75    type Future = A::Future;
76
77    fn new_service(&self, cfg: C) -> Self::Future {
78        self.a.new_service((self.f)(cfg))
79    }
80}
81
82/// `unit_config()` config combinator
83pub struct UnitConfig<A, C> {
84    a: A,
85    e: PhantomData<C>,
86}
87
88impl<A, C> UnitConfig<A, C>
89where
90    A: ServiceFactory<Config = ()>,
91{
92    /// Create new `UnitConfig` combinator
93    pub(crate) fn new(a: A) -> Self {
94        Self { a, e: PhantomData }
95    }
96}
97
98impl<A, C> Clone for UnitConfig<A, C>
99where
100    A: Clone,
101{
102    fn clone(&self) -> Self {
103        Self {
104            a: self.a.clone(),
105            e: PhantomData,
106        }
107    }
108}
109
110impl<A, C> ServiceFactory for UnitConfig<A, C>
111where
112    A: ServiceFactory<Config = ()>,
113{
114    type Request = A::Request;
115    type Response = A::Response;
116    type Error = A::Error;
117
118    type Config = C;
119    type Service = A::Service;
120    type InitError = A::InitError;
121    type Future = A::Future;
122
123    fn new_service(&self, _: C) -> Self::Future {
124        self.a.new_service(())
125    }
126}