1
0

feat: add verb concept

This commit is contained in:
2026-04-29 18:58:51 +08:00
parent e8ff9a3e4f
commit 10b27c0fc2
2 changed files with 99 additions and 4 deletions

View File

@@ -834,7 +834,80 @@ impl FromStr for FileName {
} }
// Build self and return // Build self and return
Ok(Self { filename: s.to_string() }) Ok(Self {
filename: s.to_string(),
})
}
}
// endregion
// region: Verb
pub type BadVerbError = ParseVerbError;
/// The struct representing a verb when manipulating file
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Verb {
/// The validated verb name.
verb: String,
}
impl Verb {
pub const OPEN: LazyLock<Verb> = LazyLock::new(|| Verb::new("open").expect("unexpected bad verb"));
pub const EDIT: LazyLock<Verb> = LazyLock::new(|| Verb::new("edit").expect("unexpected bad verb"));
pub const PLAY: LazyLock<Verb> = LazyLock::new(|| Verb::new("play").expect("unexpected bad verb"));
}
impl Verb {
/// Create a new verb.
///
/// `verb` is the verb for validating.
/// This function will validate whether given verb is legal.
pub fn new(verb: &str) -> Result<Self, BadVerbError> {
Self::from_str(verb)
}
/// Get the validated verb name.
pub fn inner(&self) -> &str {
&self.verb
}
}
/// The error occurs when constructing Verb with bad verb name.
#[derive(Debug, TeError)]
#[error("given verb \"{inner}\" is illegal")]
pub struct ParseVerbError {
inner: String,
}
impl ParseVerbError {
fn new(inner: &str) -> Self {
Self {
inner: inner.to_string(),
}
}
}
impl Display for Verb {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.verb.fmt(f)
}
}
impl FromStr for Verb {
type Err = ParseVerbError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
static RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"^[a-zA-Z0-9_-]+$").expect("unexpected bad regex pattern string")
});
match RE.captures(s) {
Some(_) => Ok(Self {
verb: s.to_string(),
}),
None => Err(ParseVerbError::new(s)),
}
} }
} }

View File

@@ -254,3 +254,25 @@ fn test_file_name() {
} }
// endregion // endregion
// region: Verb
#[test]
fn test_verb() {
fn ok_tester(s: &str) {
let rv = Verb::from_str(s);
assert!(rv.is_ok());
let rv = rv.unwrap();
assert_eq!(s, rv.inner());
}
fn err_tester(s: &str) {
let rv = Verb::from_str(s);
assert!(rv.is_err());
}
ok_tester("Open");
ok_tester("open");
err_tester("Space Name");
}
// endregion