use std::net::SocketAddr;
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())
}
}
pub fn duration(raw: &str) -> Result<Duration, String> {
let mut rest = raw.trim();
if rest.is_empty() {
return Err("duration must not be empty".to_owned());
}
let mut total = Duration::ZERO;
while !rest.is_empty() {
rest = rest.trim_start();
if rest.is_empty() {
break;
}
let num_end = rest
.find(|c: char| !c.is_ascii_digit())
.unwrap_or(rest.len());
if num_end == 0 {
return Err(format!("expected a number in duration {raw:?}"));
}
let (num_str, after_num) = rest.split_at(num_end);
let value: u64 = num_str
.parse()
.map_err(|e| format!("invalid number {num_str:?} in duration: {e}"))?;
let unit_end = after_num
.find(|c: char| !c.is_ascii_alphabetic())
.unwrap_or(after_num.len());
let (unit, tail) = after_num.split_at(unit_end);
if unit.is_empty() {
return Err(format!(
"missing unit after {num_str:?} in duration {raw:?}"
));
}
let part = duration_component(value, unit)?;
total = total
.checked_add(part)
.ok_or_else(|| format!("duration overflow for {raw:?}"))?;
rest = tail;
}
Ok(total)
}
fn duration_component(value: u64, unit: &str) -> Result<Duration, String> {
match unit.to_ascii_lowercase().as_str() {
"ms" => Ok(Duration::from_millis(value)),
"s" => Ok(Duration::from_secs(value)),
"m" => {
let secs = value
.checked_mul(60)
.ok_or_else(|| format!("duration overflow for {value}{unit}"))?;
Ok(Duration::from_secs(secs))
}
"h" => {
let secs = value
.checked_mul(3600)
.ok_or_else(|| format!("duration overflow for {value}{unit}"))?;
Ok(Duration::from_secs(secs))
}
other => Err(format!(
"unknown duration unit {other:?}; expected ms, s, m, or h"
)),
}
}
pub fn bytes(raw: &str) -> Result<u64, String> {
let raw = raw.trim();
if raw.is_empty() {
return Err("byte size must not be empty".to_owned());
}
let num_end = raw.find(|c: char| !c.is_ascii_digit()).unwrap_or(raw.len());
if num_end == 0 {
return Err(format!("expected a number of bytes, got {raw:?}"));
}
let (num_str, unit_raw) = raw.split_at(num_end);
let value: u64 = num_str
.parse()
.map_err(|e| format!("invalid number {num_str:?}: {e}"))?;
let unit = unit_raw.trim();
if !unit.chars().all(|c| c.is_ascii_alphabetic()) {
return Err(format!("invalid byte size {raw:?}"));
}
let multiplier: u64 = match unit.to_ascii_lowercase().as_str() {
"" | "b" => 1,
"kb" => 1_000,
"mb" => 1_000_000,
"gb" => 1_000_000_000,
"kib" => 1_024,
"mib" => 1_048_576,
"gib" => 1_073_741_824,
other => {
return Err(format!(
"unknown byte unit {other:?}; expected B, KB, MB, GB, KiB, MiB, or GiB"
));
}
};
value
.checked_mul(multiplier)
.ok_or_else(|| format!("byte size overflow for {raw:?}"))
}
pub fn socket_addr(raw: &str) -> Result<SocketAddr, String> {
raw.trim()
.parse::<SocketAddr>()
.map_err(|e| format!("invalid socket address: {e}"))
}
#[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());
}
#[test]
fn duration_single_unit() {
assert_eq!(duration("30s").unwrap(), Duration::from_secs(30));
assert_eq!(duration("5m").unwrap(), Duration::from_secs(300));
assert_eq!(duration("2h").unwrap(), Duration::from_secs(7200));
assert_eq!(duration("500ms").unwrap(), Duration::from_millis(500));
}
#[test]
fn duration_multiple_units() {
assert_eq!(duration("5m 30s").unwrap(), Duration::from_secs(330));
assert_eq!(duration("1h 2m 3s").unwrap(), Duration::from_secs(3723));
assert_eq!(duration("1s 500ms").unwrap(), Duration::from_millis(1500));
}
#[test]
fn duration_no_spaces_between_components() {
assert_eq!(duration("5m30s").unwrap(), Duration::from_secs(330));
}
#[test]
fn duration_surrounding_whitespace() {
assert_eq!(duration(" 5m 30s ").unwrap(), Duration::from_secs(330));
}
#[test]
fn duration_case_insensitive_units() {
assert_eq!(duration("5M").unwrap(), Duration::from_secs(300));
assert_eq!(duration("1H").unwrap(), Duration::from_secs(3600));
assert_eq!(duration("250MS").unwrap(), Duration::from_millis(250));
}
#[test]
fn duration_errors() {
assert!(duration("").is_err());
assert!(duration(" ").is_err());
assert!(duration("5").is_err()); assert!(duration("abc").is_err());
assert!(duration("5x").is_err()); assert!(duration("m").is_err()); assert!(duration("5m abc").is_err()); }
#[test]
fn duration_mul_overflow_is_error() {
assert!(duration("9999999999999999999h").is_err());
}
#[test]
fn duration_add_overflow_is_error() {
assert!(duration("18446744073709551615s 1s").is_err());
}
#[test]
fn bytes_plain_number() {
assert_eq!(bytes("1024").unwrap(), 1024);
assert_eq!(bytes("0").unwrap(), 0);
}
#[test]
fn bytes_decimal_units() {
assert_eq!(bytes("1KB").unwrap(), 1_000);
assert_eq!(bytes("10MB").unwrap(), 10_000_000);
assert_eq!(bytes("2GB").unwrap(), 2_000_000_000);
}
#[test]
fn bytes_binary_units() {
assert_eq!(bytes("1KiB").unwrap(), 1_024);
assert_eq!(bytes("1MiB").unwrap(), 1_048_576);
assert_eq!(bytes("1GiB").unwrap(), 1_073_741_824);
}
#[test]
fn bytes_b_suffix() {
assert_eq!(bytes("5B").unwrap(), 5);
}
#[test]
fn bytes_case_insensitive() {
assert_eq!(bytes("10mb").unwrap(), 10_000_000);
assert_eq!(bytes("1kib").unwrap(), 1_024);
assert_eq!(bytes("2gb").unwrap(), 2_000_000_000);
}
#[test]
fn bytes_whitespace_between_number_and_unit() {
assert_eq!(bytes(" 10 MB ").unwrap(), 10_000_000);
}
#[test]
fn bytes_errors() {
assert!(bytes("").is_err());
assert!(bytes("abc").is_err());
assert!(bytes("MB").is_err()); assert!(bytes("10XB").is_err()); assert!(bytes("1.5KB").is_err()); assert!(bytes("-5KB").is_err()); }
#[test]
fn bytes_overflow_is_error() {
assert!(bytes("18446744073709551615GB").is_err());
}
#[test]
fn socket_addr_ipv4() {
let addr = socket_addr("0.0.0.0:8080").unwrap();
assert_eq!(addr.to_string(), "0.0.0.0:8080");
}
#[test]
fn socket_addr_ipv6() {
let addr = socket_addr("[::1]:443").unwrap();
assert_eq!(addr.to_string(), "[::1]:443");
}
#[test]
fn socket_addr_trims_whitespace() {
let addr = socket_addr(" 127.0.0.1:80 ").unwrap();
assert_eq!(addr.to_string(), "127.0.0.1:80");
}
#[test]
fn socket_addr_errors() {
assert!(socket_addr("").is_err());
assert!(socket_addr("not-an-address").is_err());
assert!(socket_addr("1.2.3.4").is_err()); assert!(socket_addr("999.999.999.999:80").is_err());
}
}