use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReaderRule {
Author {
#[serde(default, skip_serializing_if = "Option::is_none")]
until: Option<String>,
},
Field { field: String },
AuthorAnd { role: crate::Role },
}
impl ReaderRule {
#[must_use]
pub fn parse(words: &str) -> Option<Self> {
let field = |word: &str| {
!word.is_empty() && word.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
};
match words.split_whitespace().collect::<Vec<_>>().as_slice() {
["author"] => Some(Self::Author { until: None }),
["author", "until", until] if field(until) => Some(Self::Author {
until: Some((*until).to_owned()),
}),
["author", "and", role] => {
crate::Role::parse(role).map(|role| Self::AuthorAnd { role })
}
[name] if field(name) && *name != "author" => Some(Self::Field {
field: (*name).to_owned(),
}),
_ => None,
}
}
}
impl std::fmt::Display for ReaderRule {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Author { until: None } => f.write_str("author"),
Self::Author { until: Some(field) } => write!(f, "author until {field}"),
Self::Field { field } => f.write_str(field),
Self::AuthorAnd { role } => write!(f, "author and {}", role.key()),
}
}
}