Skip to main content

async_pub_sub/utils/
middleware.rs

1/// A trait for creating middleware layers.
2/// This trait enables the creation of middleware that can wrap
3/// and extend the functionality of other components.
4///
5/// # Type Parameters
6/// * `Inner` - The type being wrapped
7pub trait Layer<Inner> {
8    /// The type that this layer produces
9    type LayerType;
10
11    /// Wraps an inner type with this layer
12    ///
13    /// # Arguments
14    /// * `inner` - The inner component to wrap
15    ///
16    /// # Returns
17    /// A new instance wrapped with this layer's functionality
18    fn layer(&self, inner: Inner) -> Self::LayerType;
19}
20
21/// Layer that does not alter the pipeline.
22/// This is used as the base case for layer composition.
23#[derive(Clone, Copy, Debug, Default)]
24pub struct IdentityLayer;
25
26impl IdentityLayer {
27    /// Creates a new identity layer.
28    pub fn new() -> Self {
29        Self
30    }
31}
32
33impl<T> Layer<T> for IdentityLayer {
34    type LayerType = T;
35
36    fn layer(&self, inner: T) -> Self::LayerType {
37        inner
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    #[test]
46    fn identity_layer_passes_through() {
47        let value = 42;
48        let layered = Layer::layer(&IdentityLayer::new(), value);
49        assert_eq!(layered, value);
50    }
51}