Debian Codegraph @

third_party/rust/derive_more/src/ops.rs

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