1use std::fmt;
2
3use use_chemical_formula::ChemicalFormula;
4
5use crate::{Ion, IonCharge, IonKind, IonValidationError};
6
7#[derive(Clone, Debug, Eq, PartialEq)]
9pub struct Cation(Ion);
10
11impl Cation {
12 pub fn new(formula: ChemicalFormula, magnitude: u8) -> Result<Self, IonValidationError> {
18 Ok(Self(
19 Ion::new(formula, IonCharge::positive(magnitude)?).with_kind(IonKind::Cation),
20 ))
21 }
22
23 pub fn from_ion(ion: Ion) -> Result<Self, IonValidationError> {
29 if ion.is_cation() {
30 Ok(Self(ion.with_kind(IonKind::Cation)))
31 } else {
32 Err(IonValidationError::ExpectedCation)
33 }
34 }
35
36 #[must_use]
38 pub const fn as_ion(&self) -> &Ion {
39 &self.0
40 }
41
42 #[must_use]
44 pub fn into_ion(self) -> Ion {
45 self.0
46 }
47}
48
49impl fmt::Display for Cation {
50 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
51 write!(formatter, "{}", self.0)
52 }
53}