use std::fmt;
use std::str::FromStr;
use super::kebab::is_name_with_separator;
use crate::types::name::InvalidOptionName;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OptionName(String);
impl OptionName {
pub fn new(value: &str) -> Result<Self, InvalidOptionName> {
if is_name_with_separator(value, b'_') {
Ok(Self(value.to_owned()))
} else {
Err(InvalidOptionName::new(value))
}
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl FromStr for OptionName {
type Err = InvalidOptionName;
fn from_str(value: &str) -> Result<Self, Self::Err> {
Self::new(value)
}
}
impl TryFrom<&str> for OptionName {
type Error = InvalidOptionName;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl fmt::Display for OptionName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn option_name_accepts_snake_case() {
for value in ["archive_keep", "style_reinject", &"a".repeat(64)] {
assert_eq!(
OptionName::new(value).as_ref().map(OptionName::as_str),
Ok(value)
);
}
}
#[test]
fn option_name_refuses_bad_start_bad_character_overlong_and_empty() {
for value in ["a-b", "Archive", "9x", "_x", &"a".repeat(65), ""] {
assert_eq!(
OptionName::new(value).map_err(|e| e.to_string()),
Err(format!("\"{value}\" is not a valid option name"))
);
}
}
#[test]
fn from_str_try_from_and_display_agree_with_new() {
assert_eq!(
"archive_keep".parse::<OptionName>(),
OptionName::new("archive_keep")
);
assert_eq!(
OptionName::try_from("archive_keep"),
OptionName::new("archive_keep")
);
assert_eq!(
OptionName::new("archive_keep").map(|n| n.to_string()),
Ok("archive_keep".to_owned())
);
}
}