Skip to main content

use_stoichiometry/
formula_quantity.rs

1use std::fmt;
2
3use use_chemical_formula::ChemicalFormula;
4
5use crate::{StoichiometricCoefficient, StoichiometricTerm, StoichiometryValidationError};
6
7/// A formula with a stoichiometric quantity.
8#[derive(Clone, Debug, Eq, PartialEq)]
9pub struct FormulaQuantity {
10    term: StoichiometricTerm,
11}
12
13impl FormulaQuantity {
14    /// Creates a formula quantity.
15    ///
16    /// # Errors
17    ///
18    /// Returns [`StoichiometryValidationError::ZeroCoefficient`] if the coefficient is
19    /// structurally invalid.
20    pub fn new(
21        coefficient: StoichiometricCoefficient,
22        formula: ChemicalFormula,
23    ) -> Result<Self, StoichiometryValidationError> {
24        Ok(Self {
25            term: StoichiometricTerm::new(coefficient, formula)?,
26        })
27    }
28
29    /// Creates a formula quantity from a raw coefficient value.
30    ///
31    /// # Errors
32    ///
33    /// Returns [`StoichiometryValidationError::ZeroCoefficient`] when `coefficient` is zero.
34    pub fn from_value(
35        coefficient: u32,
36        formula: ChemicalFormula,
37    ) -> Result<Self, StoichiometryValidationError> {
38        Self::new(StoichiometricCoefficient::new(coefficient)?, formula)
39    }
40
41    /// Returns the coefficient.
42    #[must_use]
43    pub const fn coefficient(&self) -> StoichiometricCoefficient {
44        self.term.coefficient()
45    }
46
47    /// Returns the formula.
48    #[must_use]
49    pub const fn formula(&self) -> &ChemicalFormula {
50        self.term.formula()
51    }
52
53    /// Returns the stoichiometric term.
54    #[must_use]
55    pub const fn term(&self) -> &StoichiometricTerm {
56        &self.term
57    }
58
59    /// Consumes the quantity and returns its parts.
60    #[must_use]
61    pub fn into_parts(self) -> (StoichiometricCoefficient, ChemicalFormula) {
62        self.term.into_parts()
63    }
64}
65
66impl fmt::Display for FormulaQuantity {
67    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
68        write!(formatter, "{}", self.term)
69    }
70}