Skip to main content

use_ion/
ion_name.rs

1use std::fmt;
2
3use crate::IonValidationError;
4
5/// A validated ion name.
6#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
7pub struct IonName(String);
8
9impl IonName {
10    /// Creates an ion name.
11    ///
12    /// # Errors
13    ///
14    /// Returns [`IonValidationError::EmptyName`] when `name` is empty after trimming.
15    pub fn new(name: &str) -> Result<Self, IonValidationError> {
16        let trimmed = name.trim();
17        if trimmed.is_empty() {
18            Err(IonValidationError::EmptyName)
19        } else {
20            Ok(Self(trimmed.to_owned()))
21        }
22    }
23
24    /// Returns the ion 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 IonName {
38    fn as_ref(&self) -> &str {
39        self.as_str()
40    }
41}
42
43impl TryFrom<&str> for IonName {
44    type Error = IonValidationError;
45
46    fn try_from(value: &str) -> Result<Self, Self::Error> {
47        Self::new(value)
48    }
49}
50
51impl fmt::Display for IonName {
52    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
53        formatter.write_str(self.as_str())
54    }
55}