1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//! Definitions used in derived implementations of [`core::ops`] traits.

use core::fmt;

/// Error returned by the derived implementations when an arithmetic or logic
/// operation is invoked on a unit-like variant of an enum.
#[derive(Clone, Copy, Debug)]
pub struct UnitError {
    operation_name: &'static str,
}

impl UnitError {
    #[doc(hidden)]
    #[must_use]
    #[inline]
    pub const fn new(operation_name: &'static str) -> Self {
        Self { operation_name }
    }
}

impl fmt::Display for UnitError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Cannot {}() unit variants", self.operation_name)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for UnitError {}

#[cfg(feature = "add")]
/// Error returned by the derived implementations when an arithmetic or logic
/// operation is invoked on mismatched enum variants.
#[derive(Clone, Copy, Debug)]
pub struct WrongVariantError {
    operation_name: &'static str,
}

#[cfg(feature = "add")]
impl WrongVariantError {
    #[doc(hidden)]
    #[must_use]
    #[inline]
    pub const fn new(operation_name: &'static str) -> Self {
        Self { operation_name }
    }
}

#[cfg(feature = "add")]
impl fmt::Display for WrongVariantError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Trying to {}() mismatched enum variants",
            self.operation_name
        )
    }
}

#[cfg(all(feature = "add", feature = "std"))]
impl std::error::Error for WrongVariantError {}

#[cfg(feature = "add")]
/// Possible errors returned by the derived implementations of binary
/// arithmetic or logic operations.
#[derive(Clone, Copy, Debug)]
pub enum BinaryError {
    /// Operation is attempted between mismatched enum variants.
    Mismatch(WrongVariantError),

    /// Operation is attempted on unit-like enum variants.
    Unit(UnitError),
}

#[cfg(feature = "add")]
impl fmt::Display for BinaryError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Mismatch(e) => write!(f, "{e}"),
            Self::Unit(e) => write!(f, "{e}"),
        }
    }
}

#[cfg(all(feature = "add", feature = "std"))]
impl std::error::Error for BinaryError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Mismatch(e) => e.source(),
            Self::Unit(e) => e.source(),
        }
    }
}