use std::fmt;
use std::str::FromStr;
use crate::types::frontmatter::error::FrontmatterError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Invocation {
User,
#[default]
Any,
}
impl Invocation {
pub const ALL: [Self; 2] = [Self::User, Self::Any];
pub fn new(value: &str) -> Result<Self, FrontmatterError> {
Self::ALL
.into_iter()
.find(|candidate| candidate.as_str() == value)
.ok_or_else(|| {
FrontmatterError::not_one_of(value, Self::ALL.into_iter().map(Self::as_str))
})
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::User => "user",
Self::Any => "any",
}
}
}
impl fmt::Display for Invocation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for Invocation {
type Err = FrontmatterError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
Self::new(value)
}
}
impl TryFrom<&str> for Invocation {
type Error = FrontmatterError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::new(value)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn invocation_parses_each_value() {
for (text, expected) in [("user", Invocation::User), ("any", Invocation::Any)] {
assert_eq!(text.parse::<Invocation>().ok(), Some(expected));
assert_eq!(expected.to_string(), text);
}
}
#[test]
fn invocation_refuses_other_values() {
for text in ["manual", "User"] {
assert!(text.parse::<Invocation>().is_err(), "{text}");
}
let refused = "manual".parse::<Invocation>().err().map(|e| e.to_string());
assert_eq!(refused.as_deref(), Some("\"manual\" (expected user, any)"));
}
#[test]
fn invocation_defaults_to_any() {
assert_eq!(Invocation::default(), Invocation::Any);
}
#[test]
fn invocation_builds_alike_through_new_from_str_and_try_from() {
fn shown(built: Result<Invocation, FrontmatterError>) -> Result<String, String> {
built
.map(|value| value.to_string())
.map_err(|error| error.to_string())
}
for text in ["user", "anyone"] {
let expected = shown(Invocation::new(text));
assert_eq!(shown(text.parse::<Invocation>()), expected);
assert_eq!(shown(Invocation::try_from(text)), expected);
}
assert!(Invocation::new("user").is_ok());
assert!(Invocation::new("anyone").is_err());
}
}