Skip to main content

use_molecule/
molecule_name.rs

1use std::fmt;
2
3use crate::MoleculeValidationError;
4
5/// A validated molecule name.
6#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
7pub struct MoleculeName(String);
8
9impl MoleculeName {
10    /// Creates a molecule name.
11    ///
12    /// # Errors
13    ///
14    /// Returns [`MoleculeValidationError::EmptyName`] when `name` is empty after trimming.
15    pub fn new(name: &str) -> Result<Self, MoleculeValidationError> {
16        let trimmed = name.trim();
17        if trimmed.is_empty() {
18            Err(MoleculeValidationError::EmptyName)
19        } else {
20            Ok(Self(trimmed.to_owned()))
21        }
22    }
23
24    /// Returns the molecule name text.
25    #[must_use]
26    pub fn as_str(&self) -> &str {
27        &self.0
28    }
29
30    /// Consumes the name and returns the owned text.
31    #[must_use]
32    pub fn into_string(self) -> String {
33        self.0
34    }
35}
36
37impl AsRef<str> for MoleculeName {
38    fn as_ref(&self) -> &str {
39        self.as_str()
40    }
41}
42
43impl TryFrom<&str> for MoleculeName {
44    type Error = MoleculeValidationError;
45
46    fn try_from(value: &str) -> Result<Self, Self::Error> {
47        Self::new(value)
48    }
49}
50
51impl fmt::Display for MoleculeName {
52    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
53        formatter.write_str(self.as_str())
54    }
55}