Skip to main content

eml_nl/utils/
publication_language.rs

1use thiserror::Error;
2
3use crate::{EMLError, EMLValueResultExt as _, utils::StringValueData};
4
5/// The publication language of something in a document.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
7pub enum PublicationLanguage {
8    /// Dutch language.
9    #[default]
10    Dutch,
11
12    /// Frisian language.
13    Frisian,
14}
15
16impl PublicationLanguage {
17    /// Create a new PublicationLanguage from a string, validating its format.
18    pub fn new(s: impl AsRef<str>) -> Result<Self, EMLError> {
19        Self::from_eml_value(s).wrap_value_error()
20    }
21
22    /// Parse a publication language from its string representation.
23    pub fn from_eml_value(s: impl AsRef<str>) -> Result<Self, UnknownPublicationLanguageError> {
24        let data = s.as_ref();
25        match data {
26            "nl" => Ok(PublicationLanguage::Dutch),
27            "fy" => Ok(PublicationLanguage::Frisian),
28            _ => Err(UnknownPublicationLanguageError(data.to_string())),
29        }
30    }
31
32    /// Get the `&str` representation of this [`PublicationLanguage`].
33    pub fn to_eml_value(&self) -> &'static str {
34        match self {
35            PublicationLanguage::Dutch => "nl",
36            PublicationLanguage::Frisian => "fy",
37        }
38    }
39}
40
41/// Error returned when an unknown publication language string is encountered.
42#[derive(Debug, Clone, Error, PartialEq, Eq)]
43#[error("Unknown publication language: {0}")]
44pub struct UnknownPublicationLanguageError(String);
45
46impl StringValueData for PublicationLanguage {
47    type Error = UnknownPublicationLanguageError;
48
49    fn parse_from_str(s: &str) -> Result<Self, Self::Error>
50    where
51        Self: Sized,
52    {
53        Self::from_eml_value(s)
54    }
55
56    fn to_raw_value(&self) -> String {
57        self.to_eml_value().to_string()
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn test_valid_publication_languages() {
67        let valid_languages = ["nl", "fy"];
68        for lang in valid_languages {
69            assert!(
70                PublicationLanguage::from_eml_value(lang).is_ok(),
71                "PublicationLanguage should accept valid language code: {}",
72                lang
73            );
74        }
75    }
76
77    #[test]
78    fn test_invalid_publication_languages() {
79        let invalid_languages = ["", "de", "dutch", "nederlands"];
80        for lang in invalid_languages {
81            assert!(
82                PublicationLanguage::from_eml_value(lang).is_err(),
83                "PublicationLanguage should reject invalid language code: {}",
84                lang
85            );
86        }
87    }
88}