Skip to main content

use_oxidation_state/
formula_oxidation_state.rs

1use std::fmt;
2
3use crate::{OxidationStateSet, OxidationStateValidationError};
4
5/// Oxidation-state assignments in a formula or caller-defined formula context.
6#[derive(Clone, Debug, Default, Eq, PartialEq)]
7pub struct FormulaOxidationState {
8    formula_label: String,
9    states: OxidationStateSet,
10}
11
12impl FormulaOxidationState {
13    /// Creates formula-context oxidation-state assignments.
14    ///
15    /// # Errors
16    ///
17    /// Returns [`OxidationStateValidationError::EmptyFormulaLabel`] when `formula_label`
18    /// is empty or whitespace only.
19    pub fn new(
20        formula_label: &str,
21        states: OxidationStateSet,
22    ) -> Result<Self, OxidationStateValidationError> {
23        let formula_label = formula_label.trim();
24
25        if formula_label.is_empty() {
26            Err(OxidationStateValidationError::EmptyFormulaLabel)
27        } else {
28            Ok(Self {
29                formula_label: formula_label.to_owned(),
30                states,
31            })
32        }
33    }
34
35    /// Returns the formula or formula-context label.
36    #[must_use]
37    pub fn formula_label(&self) -> &str {
38        &self.formula_label
39    }
40
41    /// Returns the oxidation-state assignments.
42    #[must_use]
43    pub const fn states(&self) -> &OxidationStateSet {
44        &self.states
45    }
46
47    /// Consumes the value and returns its parts.
48    #[must_use]
49    pub fn into_parts(self) -> (String, OxidationStateSet) {
50        (self.formula_label, self.states)
51    }
52}
53
54impl fmt::Display for FormulaOxidationState {
55    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
56        if self.states.is_empty() {
57            formatter.write_str(&self.formula_label)
58        } else {
59            write!(formatter, "{} [{}]", self.formula_label, self.states)
60        }
61    }
62}