Skip to content

Commit

Permalink
feat(polychem): add Display impl for Element
Browse files Browse the repository at this point in the history
  • Loading branch information
TheLostLambda committed Mar 27, 2024
1 parent 23a4093 commit c6d72f5
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion crates/polychem/src/atoms/element.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use std::convert::identity;
use std::{
convert::identity,
fmt::{self, Display, Formatter},
};

use itertools::Itertools;
use rust_decimal::Decimal;
Expand Down Expand Up @@ -86,6 +89,17 @@ impl<'a> Element<'a> {
}
}

impl Display for Element<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let symbol = self.symbol;
if let Some(mass_number) = self.mass_number {
write!(f, "[{mass_number}{symbol}]")
} else {
write!(f, "{symbol}")
}
}
}

impl Massive for Element<'_> {
fn monoisotopic_mass(&self) -> Decimal {
// SAFETY: The call to `.unwrap()` is safe here since `.isotope_abundances()` is guaranteed to yield at
Expand Down Expand Up @@ -167,6 +181,18 @@ mod tests {
assert_miette_snapshot!(Element::new_isotope(&DB, "C", 15));
}

#[test]
fn element_display() {
let c = Element::new(&DB, "C").unwrap();
assert_eq!(c.to_string(), "C");
let c13 = Element::new_isotope(&DB, "C", 13).unwrap();
assert_eq!(c13.to_string(), "[13C]");
let th = Element::new(&DB, "Th").unwrap();
assert_eq!(th.to_string(), "Th");
let th230 = Element::new_isotope(&DB, "Th", 230).unwrap();
assert_eq!(th230.to_string(), "[230Th]");
}

#[test]
fn element_monoisotopic_mass() {
// Successfully calculate the monoisotopic mass of elements with natural abundances
Expand Down

0 comments on commit c6d72f5

Please sign in to comment.