Skip to main content

use_oxidation_state/
oxidation_magnitude.rs

1use std::fmt;
2
3use crate::OxidationStateValidationError;
4
5/// A bounded oxidation-state magnitude.
6#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
7pub struct OxidationMagnitude(u8);
8
9impl OxidationMagnitude {
10    /// The maximum magnitude supported by this crate.
11    pub const MAX: u8 = 8;
12
13    /// Zero magnitude.
14    pub const ZERO: Self = Self(0);
15
16    /// Creates an oxidation-state magnitude.
17    ///
18    /// # Errors
19    ///
20    /// Returns [`OxidationStateValidationError::MagnitudeAboveMaximum`] when `magnitude`
21    /// is greater than [`Self::MAX`].
22    pub const fn new(magnitude: u8) -> Result<Self, OxidationStateValidationError> {
23        if magnitude > Self::MAX {
24            Err(OxidationStateValidationError::MagnitudeAboveMaximum {
25                magnitude,
26                maximum: Self::MAX,
27            })
28        } else {
29            Ok(Self(magnitude))
30        }
31    }
32
33    /// Returns the magnitude value.
34    #[must_use]
35    pub const fn get(self) -> u8 {
36        self.0
37    }
38
39    /// Returns `true` when the magnitude is zero.
40    #[must_use]
41    pub const fn is_zero(self) -> bool {
42        self.0 == 0
43    }
44}
45
46impl Default for OxidationMagnitude {
47    fn default() -> Self {
48        Self::ZERO
49    }
50}
51
52impl fmt::Display for OxidationMagnitude {
53    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
54        write!(formatter, "{}", self.0)
55    }
56}