Skip to main content

use_chemical_formula/
element_count.rs

1use std::fmt;
2
3use crate::FormulaValidationError;
4
5/// A positive element count.
6#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
7pub struct ElementCount(u32);
8
9impl ElementCount {
10    /// The implicit count for a term with no numeric suffix.
11    pub const ONE: Self = Self(1);
12
13    /// Creates a positive element count.
14    ///
15    /// # Errors
16    ///
17    /// Returns [`FormulaValidationError::ZeroCount`] when `value` is zero.
18    pub fn new(value: u32) -> Result<Self, FormulaValidationError> {
19        if value == 0 {
20            Err(FormulaValidationError::ZeroCount)
21        } else {
22            Ok(Self(value))
23        }
24    }
25
26    /// Returns the numeric count.
27    #[must_use]
28    pub const fn get(self) -> u32 {
29        self.0
30    }
31
32    /// Returns `true` when the count is one.
33    #[must_use]
34    pub const fn is_one(self) -> bool {
35        self.0 == 1
36    }
37}
38
39impl Default for ElementCount {
40    fn default() -> Self {
41        Self::ONE
42    }
43}
44
45impl fmt::Display for ElementCount {
46    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
47        write!(formatter, "{}", self.0)
48    }
49}
50
51/// A positive group or hydrate multiplier.
52#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
53pub struct FormulaMultiplier(u32);
54
55impl FormulaMultiplier {
56    /// The implicit multiplier for a group or hydrate with no numeric suffix.
57    pub const ONE: Self = Self(1);
58
59    /// Creates a positive formula multiplier.
60    ///
61    /// # Errors
62    ///
63    /// Returns [`FormulaValidationError::ZeroMultiplier`] when `value` is zero.
64    pub fn new(value: u32) -> Result<Self, FormulaValidationError> {
65        if value == 0 {
66            Err(FormulaValidationError::ZeroMultiplier)
67        } else {
68            Ok(Self(value))
69        }
70    }
71
72    /// Returns the numeric multiplier.
73    #[must_use]
74    pub const fn get(self) -> u32 {
75        self.0
76    }
77
78    /// Returns `true` when the multiplier is one.
79    #[must_use]
80    pub const fn is_one(self) -> bool {
81        self.0 == 1
82    }
83}
84
85impl Default for FormulaMultiplier {
86    fn default() -> Self {
87        Self::ONE
88    }
89}
90
91impl fmt::Display for FormulaMultiplier {
92    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
93        write!(formatter, "{}", self.0)
94    }
95}