Skip to main content

use_bond/
bond_length.rs

1use std::fmt;
2
3use crate::BondValidationError;
4
5/// A positive displayable bond length.
6#[derive(Clone, Debug, PartialEq)]
7pub struct BondLength {
8    value: f64,
9    unit: String,
10}
11
12impl BondLength {
13    /// Creates a bond length.
14    ///
15    /// # Errors
16    ///
17    /// Returns [`BondValidationError::NonFiniteBondLength`] when `value` is not finite,
18    /// [`BondValidationError::NonPositiveBondLength`] when `value` is zero or negative, or
19    /// [`BondValidationError::EmptyLengthUnit`] when `unit` is empty after trimming.
20    pub fn new(value: f64, unit: &str) -> Result<Self, BondValidationError> {
21        if !value.is_finite() {
22            return Err(BondValidationError::NonFiniteBondLength);
23        }
24        if value <= 0.0 {
25            return Err(BondValidationError::NonPositiveBondLength);
26        }
27
28        let trimmed = unit.trim();
29        if trimmed.is_empty() {
30            Err(BondValidationError::EmptyLengthUnit)
31        } else {
32            Ok(Self {
33                value,
34                unit: trimmed.to_owned(),
35            })
36        }
37    }
38
39    /// Returns the bond length value.
40    #[must_use]
41    pub const fn value(&self) -> f64 {
42        self.value
43    }
44
45    /// Returns the bond length unit label.
46    #[must_use]
47    pub fn unit(&self) -> &str {
48        &self.unit
49    }
50}
51
52impl fmt::Display for BondLength {
53    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
54        write!(formatter, "{} {}", self.value, self.unit)
55    }
56}