Skip to main content

use_reaction/
solvent.rs

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