Skip to main content

use_molar_mass/
formula_molar_mass.rs

1use std::fmt;
2
3use use_chemical_formula::ChemicalFormula;
4
5use crate::{MassContributionSet, MolarMass, MolarMassValidationError};
6
7/// A formula with its calculated molar mass and element contributions.
8#[derive(Clone, Debug, PartialEq)]
9pub struct FormulaMolarMass {
10    formula: ChemicalFormula,
11    molar_mass: MolarMass,
12    contributions: MassContributionSet,
13}
14
15impl FormulaMolarMass {
16    /// Creates a formula molar mass from a formula and contribution set.
17    ///
18    /// # Errors
19    ///
20    /// Returns a molar-mass validation error if the contribution total is invalid.
21    pub fn new(
22        formula: ChemicalFormula,
23        contributions: MassContributionSet,
24    ) -> Result<Self, MolarMassValidationError> {
25        let molar_mass = contributions.molar_mass()?;
26
27        Ok(Self {
28            formula,
29            molar_mass,
30            contributions,
31        })
32    }
33
34    /// Returns the source formula.
35    #[must_use]
36    pub const fn formula(&self) -> &ChemicalFormula {
37        &self.formula
38    }
39
40    /// Returns the calculated molar mass.
41    #[must_use]
42    pub const fn molar_mass(&self) -> MolarMass {
43        self.molar_mass
44    }
45
46    /// Returns the element contribution set.
47    #[must_use]
48    pub const fn contributions(&self) -> &MassContributionSet {
49        &self.contributions
50    }
51}
52
53impl fmt::Display for FormulaMolarMass {
54    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
55        write!(formatter, "{}: {}", self.formula, self.molar_mass)
56    }
57}