mycelium_pci/
error.rs

1use core::fmt;
2
3pub(crate) fn unexpected<T>(value: T) -> UnexpectedValue<T>
4where
5    T: fmt::LowerHex + fmt::Debug,
6{
7    UnexpectedValue { value, name: None }
8}
9
10#[derive(Clone, Debug, Eq, PartialEq)]
11pub struct UnexpectedValue<T> {
12    value: T,
13    name: Option<&'static str>,
14}
15
16impl<T> UnexpectedValue<T> {
17    pub(crate) fn named(self, name: &'static str) -> Self {
18        Self {
19            name: Some(name),
20            ..self
21        }
22    }
23}
24
25impl<T> fmt::Display for UnexpectedValue<T>
26where
27    T: fmt::LowerHex + fmt::Debug,
28{
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        let ty = core::any::type_name::<T>();
31        match self {
32            Self {
33                value,
34                name: Some(name),
35            } => write!(f, "unexpected {ty} value for {name}: {value:#x}",),
36            Self { value, name: None } => write!(f, "unexpected {ty} value: {value:#x}",),
37        }
38    }
39}
40
41impl<T> core::error::Error for UnexpectedValue<T> where T: fmt::LowerHex + fmt::Debug {}