derive_more/
add.rs

1//! Definitions used in derived implementations of [`core::ops::Add`]-like traits.
2
3use core::fmt;
4
5use crate::UnitError;
6
7/// Error returned by the derived implementations when an arithmetic or logic
8/// operation is invoked on mismatched enum variants.
9#[derive(Clone, Copy, Debug)]
10pub struct WrongVariantError {
11    operation_name: &'static str,
12}
13
14impl WrongVariantError {
15    #[doc(hidden)]
16    #[must_use]
17    #[inline]
18    pub const fn new(operation_name: &'static str) -> Self {
19        Self { operation_name }
20    }
21}
22
23impl fmt::Display for WrongVariantError {
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        write!(
26            f,
27            "Trying to {}() mismatched enum variants",
28            self.operation_name,
29        )
30    }
31}
32
33#[cfg(feature = "std")]
34impl std::error::Error for WrongVariantError {}
35
36/// Possible errors returned by the derived implementations of binary
37/// arithmetic or logic operations.
38#[derive(Clone, Copy, Debug)]
39pub enum BinaryError {
40    /// Operation is attempted between mismatched enum variants.
41    Mismatch(WrongVariantError),
42
43    /// Operation is attempted on unit-like enum variants.
44    Unit(UnitError),
45}
46
47impl fmt::Display for BinaryError {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        match self {
50            Self::Mismatch(e) => write!(f, "{e}"),
51            Self::Unit(e) => write!(f, "{e}"),
52        }
53    }
54}
55
56#[cfg(feature = "std")]
57impl std::error::Error for BinaryError {
58    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
59        match self {
60            Self::Mismatch(e) => e.source(),
61            Self::Unit(e) => e.source(),
62        }
63    }
64}