Skip to main content

use_molecule/
molecule_charge.rs

1use std::fmt;
2
3/// A formal molecule charge.
4#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
5pub struct MoleculeCharge(i16);
6
7impl MoleculeCharge {
8    /// Neutral charge.
9    pub const NEUTRAL: Self = Self(0);
10
11    /// Creates a molecule charge.
12    #[must_use]
13    pub const fn new(charge: i16) -> Self {
14        Self(charge)
15    }
16
17    /// Returns the signed charge value.
18    #[must_use]
19    pub const fn get(self) -> i16 {
20        self.0
21    }
22
23    /// Returns `true` when the charge is neutral.
24    #[must_use]
25    pub const fn is_neutral(self) -> bool {
26        self.0 == 0
27    }
28}
29
30impl Default for MoleculeCharge {
31    fn default() -> Self {
32        Self::NEUTRAL
33    }
34}
35
36impl fmt::Display for MoleculeCharge {
37    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
38        match self.0.cmp(&0) {
39            std::cmp::Ordering::Greater => write!(formatter, "+{}", self.0),
40            std::cmp::Ordering::Equal => formatter.write_str("0"),
41            std::cmp::Ordering::Less => write!(formatter, "{}", self.0),
42        }
43    }
44}