Skip to main content

use_oxidation_state/
oxidation_state_assignment.rs

1use std::fmt;
2
3use crate::{OxidationState, OxidationStateValidationError};
4
5/// A labeled oxidation-state assignment.
6#[derive(Clone, Debug, Eq, Hash, PartialEq)]
7pub struct OxidationStateAssignment {
8    label: String,
9    state: OxidationState,
10}
11
12impl OxidationStateAssignment {
13    /// Creates an oxidation-state assignment.
14    ///
15    /// # Errors
16    ///
17    /// Returns [`OxidationStateValidationError::EmptyAssignmentLabel`] when `label` is
18    /// empty or whitespace only.
19    pub fn new(label: &str, state: OxidationState) -> Result<Self, OxidationStateValidationError> {
20        let label = label.trim();
21
22        if label.is_empty() {
23            Err(OxidationStateValidationError::EmptyAssignmentLabel)
24        } else {
25            Ok(Self {
26                label: label.to_owned(),
27                state,
28            })
29        }
30    }
31
32    /// Returns the assignment label.
33    #[must_use]
34    pub fn label(&self) -> &str {
35        &self.label
36    }
37
38    /// Returns the assigned oxidation state.
39    #[must_use]
40    pub const fn state(&self) -> OxidationState {
41        self.state
42    }
43
44    /// Consumes the assignment and returns its parts.
45    #[must_use]
46    pub fn into_parts(self) -> (String, OxidationState) {
47        (self.label, self.state)
48    }
49}
50
51impl fmt::Display for OxidationStateAssignment {
52    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
53        write!(formatter, "{}: {}", self.label, self.state)
54    }
55}