reth_primitives_traits/
error.rs

1use alloc::boxed::Box;
2use core::{
3    fmt,
4    ops::{Deref, DerefMut},
5};
6
7/// A pair of values, one of which is expected and one of which is actual.
8#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
9pub struct GotExpected<T> {
10    /// The actual value.
11    pub got: T,
12    /// The expected value.
13    pub expected: T,
14}
15
16impl<T: fmt::Display> fmt::Display for GotExpected<T> {
17    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18        write!(f, "got {}, expected {}", self.got, self.expected)
19    }
20}
21
22impl<T: fmt::Debug + fmt::Display> core::error::Error for GotExpected<T> {}
23
24impl<T> From<(T, T)> for GotExpected<T> {
25    #[inline]
26    fn from((got, expected): (T, T)) -> Self {
27        Self::new(got, expected)
28    }
29}
30
31impl<T> GotExpected<T> {
32    /// Creates a new error from a pair of values.
33    #[inline]
34    pub const fn new(got: T, expected: T) -> Self {
35        Self { got, expected }
36    }
37}
38
39/// A pair of values, one of which is expected and one of which is actual.
40///
41/// Same as [`GotExpected`], but [`Box`]ed for smaller size.
42///
43/// Prefer instantiating using [`GotExpected`], and then using `.into()` to convert to this type.
44#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
45pub struct GotExpectedBoxed<T>(pub Box<GotExpected<T>>);
46
47impl<T: fmt::Debug> fmt::Debug for GotExpectedBoxed<T> {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        self.0.fmt(f)
50    }
51}
52
53impl<T: fmt::Display> fmt::Display for GotExpectedBoxed<T> {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        self.0.fmt(f)
56    }
57}
58
59impl<T: fmt::Debug + fmt::Display> core::error::Error for GotExpectedBoxed<T> {}
60
61impl<T> Deref for GotExpectedBoxed<T> {
62    type Target = GotExpected<T>;
63
64    #[inline(always)]
65    fn deref(&self) -> &Self::Target {
66        &self.0
67    }
68}
69
70impl<T> DerefMut for GotExpectedBoxed<T> {
71    #[inline(always)]
72    fn deref_mut(&mut self) -> &mut Self::Target {
73        &mut self.0
74    }
75}
76
77impl<T> From<(T, T)> for GotExpectedBoxed<T> {
78    #[inline]
79    fn from(value: (T, T)) -> Self {
80        Self(Box::new(GotExpected::from(value)))
81    }
82}
83
84impl<T> From<GotExpected<T>> for GotExpectedBoxed<T> {
85    #[inline]
86    fn from(value: GotExpected<T>) -> Self {
87        Self(Box::new(value))
88    }
89}