Skip to main content

use_stoichiometry/
coefficient.rs

1use std::fmt;
2
3use crate::StoichiometryValidationError;
4
5/// A nonzero stoichiometric coefficient.
6#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
7pub struct StoichiometricCoefficient(u32);
8
9impl StoichiometricCoefficient {
10    /// Creates a stoichiometric coefficient.
11    ///
12    /// # Errors
13    ///
14    /// Returns [`StoichiometryValidationError::ZeroCoefficient`] when `value` is zero.
15    pub const fn new(value: u32) -> Result<Self, StoichiometryValidationError> {
16        if value == 0 {
17            Err(StoichiometryValidationError::ZeroCoefficient)
18        } else {
19            Ok(Self(value))
20        }
21    }
22
23    /// Returns the coefficient value.
24    #[must_use]
25    pub const fn value(self) -> u32 {
26        self.0
27    }
28
29    /// Returns `true` when the coefficient is one.
30    #[must_use]
31    pub const fn is_one(self) -> bool {
32        self.0 == 1
33    }
34}
35
36impl TryFrom<u32> for StoichiometricCoefficient {
37    type Error = StoichiometryValidationError;
38
39    fn try_from(value: u32) -> Result<Self, Self::Error> {
40        Self::new(value)
41    }
42}
43
44impl fmt::Display for StoichiometricCoefficient {
45    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
46        write!(formatter, "{}", self.0)
47    }
48}