| 1 | use super::Layer; |
| 2 | use std::fmt; |
| 3 | |
| 4 | /// Two middlewares chained together. |
| 5 | #[derive (Clone)] |
| 6 | pub struct Stack<Inner, Outer> { |
| 7 | inner: Inner, |
| 8 | outer: Outer, |
| 9 | } |
| 10 | |
| 11 | impl<Inner, Outer> Stack<Inner, Outer> { |
| 12 | /// Create a new `Stack`. |
| 13 | pub const fn new(inner: Inner, outer: Outer) -> Self { |
| 14 | Stack { inner, outer } |
| 15 | } |
| 16 | } |
| 17 | |
| 18 | impl<S, Inner, Outer> Layer<S> for Stack<Inner, Outer> |
| 19 | where |
| 20 | Inner: Layer<S>, |
| 21 | Outer: Layer<Inner::Service>, |
| 22 | { |
| 23 | type Service = Outer::Service; |
| 24 | |
| 25 | fn layer(&self, service: S) -> Self::Service { |
| 26 | let inner: >::Service = self.inner.layer(inner:service); |
| 27 | |
| 28 | self.outer.layer(inner) |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | impl<Inner, Outer> fmt::Debug for Stack<Inner, Outer> |
| 33 | where |
| 34 | Inner: fmt::Debug, |
| 35 | Outer: fmt::Debug, |
| 36 | { |
| 37 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 38 | // The generated output of nested `Stack`s is very noisy and makes |
| 39 | // it harder to understand what is in a `ServiceBuilder`. |
| 40 | // |
| 41 | // Instead, this output is designed assuming that a `Stack` is |
| 42 | // usually quite nested, and inside a `ServiceBuilder`. Therefore, |
| 43 | // this skips using `f.debug_struct()`, since each one would force |
| 44 | // a new layer of indentation. |
| 45 | // |
| 46 | // - In compact mode, a nested stack ends up just looking like a flat |
| 47 | // list of layers. |
| 48 | // |
| 49 | // - In pretty mode, while a newline is inserted between each layer, |
| 50 | // the `DebugStruct` used in the `ServiceBuilder` will inject padding |
| 51 | // to that each line is at the same indentation level. |
| 52 | // |
| 53 | // Also, the order of [outer, inner] is important, since it reflects |
| 54 | // the order that the layers were added to the stack. |
| 55 | if f.alternate() { |
| 56 | // pretty |
| 57 | write!(f, " {:#?}, \n{:#?}" , self.outer, self.inner) |
| 58 | } else { |
| 59 | write!(f, " {:?}, {:?}" , self.outer, self.inner) |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | |