Skip to main content

use_ion/
anion.rs

1use std::fmt;
2
3use use_chemical_formula::ChemicalFormula;
4
5use crate::{Ion, IonCharge, IonKind, IonValidationError};
6
7/// A negative ion wrapper.
8#[derive(Clone, Debug, Eq, PartialEq)]
9pub struct Anion(Ion);
10
11impl Anion {
12    /// Creates an anion from a formula and negative charge magnitude.
13    ///
14    /// # Errors
15    ///
16    /// Returns [`IonValidationError::ZeroChargeMagnitude`] when `magnitude` is zero.
17    pub fn new(formula: ChemicalFormula, magnitude: u8) -> Result<Self, IonValidationError> {
18        Ok(Self(
19            Ion::new(formula, IonCharge::negative(magnitude)?).with_kind(IonKind::Anion),
20        ))
21    }
22
23    /// Wraps an existing negative ion.
24    ///
25    /// # Errors
26    ///
27    /// Returns [`IonValidationError::ExpectedAnion`] when `ion` has a positive charge.
28    pub fn from_ion(ion: Ion) -> Result<Self, IonValidationError> {
29        if ion.is_anion() {
30            Ok(Self(ion.with_kind(IonKind::Anion)))
31        } else {
32            Err(IonValidationError::ExpectedAnion)
33        }
34    }
35
36    /// Returns the wrapped ion.
37    #[must_use]
38    pub const fn as_ion(&self) -> &Ion {
39        &self.0
40    }
41
42    /// Consumes the wrapper and returns the ion.
43    #[must_use]
44    pub fn into_ion(self) -> Ion {
45        self.0
46    }
47}
48
49impl fmt::Display for Anion {
50    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
51        write!(formatter, "{}", self.0)
52    }
53}