Skip to main content

use_chemical_formula/
formula_part.rs

1use std::collections::BTreeMap;
2use std::fmt;
3
4use crate::{FormulaTerm, FormulaValidationError};
5
6/// A contiguous formula part made of terms.
7#[derive(Clone, Debug, Eq, PartialEq)]
8pub struct FormulaPart {
9    terms: Vec<FormulaTerm>,
10}
11
12impl FormulaPart {
13    /// Creates a formula part.
14    ///
15    /// # Errors
16    ///
17    /// Returns [`FormulaValidationError::EmptyPart`] when `terms` is empty.
18    pub fn new(terms: Vec<FormulaTerm>) -> Result<Self, FormulaValidationError> {
19        if terms.is_empty() {
20            Err(FormulaValidationError::EmptyPart)
21        } else {
22            Ok(Self { terms })
23        }
24    }
25
26    /// Returns the terms in this part.
27    #[must_use]
28    pub fn terms(&self) -> &[FormulaTerm] {
29        &self.terms
30    }
31
32    pub(crate) fn add_counts(&self, counts: &mut BTreeMap<String, u64>, multiplier: u64) {
33        for term in &self.terms {
34            term.add_counts(counts, multiplier);
35        }
36    }
37}
38
39impl fmt::Display for FormulaPart {
40    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
41        for term in &self.terms {
42            write!(formatter, "{term}")?;
43        }
44        Ok(())
45    }
46}