Skip to main content

derive_more/
add.rs

1//! Definitions used in derived implementations of [`core::ops::Add`]-like traits.
2
3use core::{error::Error, 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
33impl Error for WrongVariantError {}
34
35/// Possible errors returned by the derived implementations of binary
36/// arithmetic or logic operations.
37#[derive(Clone, Copy, Debug)]
38pub enum BinaryError {
39    /// Operation is attempted between mismatched enum variants.
40    Mismatch(WrongVariantError),
41
42    /// Operation is attempted on unit-like enum variants.
43    Unit(UnitError),
44}
45
46impl fmt::Display for BinaryError {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        match self {
49            Self::Mismatch(e) => write!(f, "{e}"),
50            Self::Unit(e) => write!(f, "{e}"),
51        }
52    }
53}
54
55impl Error for BinaryError {
56    fn source(&self) -> Option<&(dyn Error + 'static)> {
57        match self {
58            Self::Mismatch(e) => e.source(),
59            Self::Unit(e) => e.source(),
60        }
61    }
62}