rama_core/layer/
into_error.rs

1//! Utility error trait for Layers.
2//!
3//! See [`MakeLayerError`] for more details.
4
5use std::fmt;
6
7/// Utility error trait to allow Rama layers
8/// to return a default error as well as a user-defined one,
9/// being it a [`Clone`]-able type or a [`Fn`] returning an error type.
10pub trait MakeLayerError: sealed::Sealed + Send + Sync + 'static {
11    /// The error type returned by the layer.
12    ///
13    /// It does not need to be an actual error type,
14    /// but it must be [`Send`] and of `'static` lifetime.
15    type Error;
16
17    /// Create a new error value that can
18    /// be turned into the inner [`Service`]'s error type.
19    ///
20    /// [`Service`]: crate
21    fn make_layer_error(&self) -> Self::Error;
22}
23
24/// A [`MakeLayerError`] implementation that
25/// returns a new error value every time.
26pub struct LayerErrorFn<F>(F);
27
28impl<F, E> LayerErrorFn<F>
29where
30    F: FnOnce() -> E + Clone + Send + Sync + 'static,
31    E: Send + 'static,
32{
33    pub(crate) const fn new(f: F) -> Self {
34        Self(f)
35    }
36}
37
38impl<F> fmt::Debug for LayerErrorFn<F>
39where
40    F: fmt::Debug,
41{
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        f.debug_tuple("LayerErrorFn").field(&self.0).finish()
44    }
45}
46
47impl<F> Clone for LayerErrorFn<F>
48where
49    F: Clone,
50{
51    fn clone(&self) -> Self {
52        Self(self.0.clone())
53    }
54}
55
56impl<F, E> MakeLayerError for LayerErrorFn<F>
57where
58    F: FnOnce() -> E + Clone + Send + Sync + 'static,
59    E: Send + 'static,
60{
61    type Error = E;
62
63    fn make_layer_error(&self) -> Self::Error {
64        self.0.clone()()
65    }
66}
67
68/// A [`MakeLayerError`] implementation that
69/// always returns clone of the same error value.
70pub struct LayerErrorStatic<E>(E);
71
72impl<E> fmt::Debug for LayerErrorStatic<E>
73where
74    E: fmt::Debug,
75{
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        f.debug_tuple("LayerErrorStatic").field(&self.0).finish()
78    }
79}
80
81impl<E> Clone for LayerErrorStatic<E>
82where
83    E: Clone,
84{
85    fn clone(&self) -> Self {
86        Self(self.0.clone())
87    }
88}
89
90impl<E> LayerErrorStatic<E>
91where
92    E: Clone + Send + Sync + 'static,
93{
94    pub(crate) const fn new(e: E) -> Self {
95        Self(e)
96    }
97}
98
99impl<E> MakeLayerError for LayerErrorStatic<E>
100where
101    E: Clone + Send + Sync + 'static,
102{
103    type Error = E;
104
105    fn make_layer_error(&self) -> Self::Error {
106        self.0.clone()
107    }
108}
109
110mod sealed {
111    pub trait Sealed {}
112
113    impl<F> Sealed for super::LayerErrorFn<F> {}
114    impl<E> Sealed for super::LayerErrorStatic<E> {}
115}