Skip to main content

mynd_math/
error.rs

1use core::fmt;
2
3/// The checked operation that could not be represented by its output type.
4#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
5#[non_exhaustive]
6pub enum ArithmeticOperation {
7    /// Checked integer addition.
8    Add,
9    /// Checked integer multiplication.
10    Multiply,
11    /// Rounding a value upward to an alignment multiple.
12    AlignUp,
13}
14
15/// A failure from a checked Mynd arithmetic primitive.
16#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
17#[non_exhaustive]
18pub enum MathError {
19    /// The source integer is not representable by the destination type.
20    ConversionOutOfRange,
21    /// The named arithmetic operation overflowed its output type.
22    Overflow {
23        /// The operation that overflowed.
24        operation: ArithmeticOperation,
25    },
26    /// Alignment zero is invalid.
27    ZeroAlignment,
28    /// The computed half-open range exceeds its exclusive upper bound.
29    RangeOutOfBounds,
30}
31
32impl fmt::Display for MathError {
33    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match self {
35            Self::ConversionOutOfRange => formatter.write_str("integer conversion is out of range"),
36            Self::Overflow { operation } => {
37                write!(formatter, "{operation} overflow")
38            }
39            Self::ZeroAlignment => formatter.write_str("alignment must be nonzero"),
40            Self::RangeOutOfBounds => {
41                formatter.write_str("range exceeds its exclusive upper bound")
42            }
43        }
44    }
45}
46
47impl fmt::Display for ArithmeticOperation {
48    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
49        match self {
50            Self::Add => formatter.write_str("addition"),
51            Self::Multiply => formatter.write_str("multiplication"),
52            Self::AlignUp => formatter.write_str("alignment"),
53        }
54    }
55}
56
57impl core::error::Error for MathError {}
58
59/// The result type returned by checked Mynd arithmetic primitives.
60pub type MathResult<T> = Result<T, MathError>;