| 1 | //! Definitions used in derived implementations of [`core::ops::Add`]-like traits. |
| 2 | |
| 3 | use core::fmt; |
| 4 | |
| 5 | use 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)] |
| 10 | pub struct WrongVariantError { |
| 11 | operation_name: &'static str, |
| 12 | } |
| 13 | |
| 14 | impl 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 | |
| 23 | impl 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" )] |
| 34 | impl 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)] |
| 39 | pub 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 | |
| 47 | impl fmt::Display for BinaryError { |
| 48 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 49 | match self { |
| 50 | Self::Mismatch(e: &WrongVariantError) => write!(f, " {e}" ), |
| 51 | Self::Unit(e: &UnitError) => write!(f, " {e}" ), |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | #[cfg (feature = "std" )] |
| 57 | impl std::error::Error for BinaryError { |
| 58 | fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { |
| 59 | match self { |
| 60 | Self::Mismatch(e: &WrongVariantError) => e.source(), |
| 61 | Self::Unit(e: &UnitError) => e.source(), |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | |