use std::time::Duration;
pub fn secs(raw: &str) -> Result<Duration, String> {
raw.trim()
.parse::<u64>()
.map(Duration::from_secs)
.map_err(|e| format!("invalid number of seconds: {e}"))
}
pub fn millis(raw: &str) -> Result<Duration, String> {
raw.trim()
.parse::<u64>()
.map(Duration::from_millis)
.map_err(|e| format!("invalid number of milliseconds: {e}"))
}
pub fn flag(raw: &str) -> Result<bool, String> {
match raw.trim().to_ascii_lowercase().as_str() {
"true" | "1" | "yes" | "on" => Ok(true),
"false" | "0" | "no" | "off" => Ok(false),
other => Err(format!(
"expected true/false, 1/0, yes/no, or on/off; got {other:?}"
)),
}
}
pub fn list(raw: &str) -> Result<Vec<String>, String> {
list_sep(',')(raw)
}
pub fn list_sep(sep: char) -> impl Fn(&str) -> Result<Vec<String>, String> {
move |raw| {
if raw.trim().is_empty() {
return Ok(Vec::new());
}
Ok(raw.split(sep).map(|s| s.trim().to_owned()).collect())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn secs_valid() {
assert_eq!(secs("30").unwrap(), Duration::from_secs(30));
assert_eq!(secs(" 10 ").unwrap(), Duration::from_secs(10));
assert_eq!(secs("0").unwrap(), Duration::from_secs(0));
}
#[test]
fn secs_invalid() {
assert!(secs("abc").is_err());
assert!(secs("-1").is_err());
assert!(secs("1.5").is_err());
}
#[test]
fn millis_valid() {
assert_eq!(millis("500").unwrap(), Duration::from_millis(500));
assert_eq!(millis("0").unwrap(), Duration::from_millis(0));
}
#[test]
fn millis_invalid() {
assert!(millis("abc").is_err());
assert!(millis("-1").is_err());
}
#[test]
fn flag_true_variants() {
for v in ["true", "1", "yes", "on", "TRUE", "Yes", "ON"] {
assert!(flag(v).unwrap(), "input: {v}");
}
}
#[test]
fn flag_false_variants() {
for v in ["false", "0", "no", "off", "FALSE", "No", "OFF"] {
assert!(!flag(v).unwrap(), "input: {v}");
}
}
#[test]
fn flag_invalid() {
assert!(flag("maybe").is_err());
assert!(flag("2").is_err());
assert!(flag("").is_err());
}
#[test]
fn flag_trims_whitespace() {
assert!(flag(" true ").unwrap());
}
#[test]
fn list_basic() {
assert_eq!(
list("a,b,c").unwrap(),
vec!["a".to_owned(), "b".to_owned(), "c".to_owned()]
);
}
#[test]
fn list_trims_whitespace() {
assert_eq!(
list(" a , b , c ").unwrap(),
vec!["a".to_owned(), "b".to_owned(), "c".to_owned()]
);
}
#[test]
fn list_empty_string() {
assert_eq!(list("").unwrap(), Vec::<String>::new());
assert_eq!(list(" ").unwrap(), Vec::<String>::new());
}
#[test]
fn list_single_item() {
assert_eq!(list("solo").unwrap(), vec!["solo".to_owned()]);
}
#[test]
fn list_sep_semicolon() {
let parser = list_sep(';');
assert_eq!(
parser("x; y; z").unwrap(),
vec!["x".to_owned(), "y".to_owned(), "z".to_owned()]
);
}
#[test]
fn list_sep_pipe() {
let parser = list_sep('|');
assert_eq!(parser("a|b").unwrap(), vec!["a".to_owned(), "b".to_owned()]);
}
#[test]
fn list_sep_empty() {
let parser = list_sep(';');
assert_eq!(parser("").unwrap(), Vec::<String>::new());
}
}