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}"))
}
#[allow(deprecated)]
pub fn bool(raw: &str) -> Result<bool, String> {
flag(raw)
}
#[deprecated(since = "0.4.0", note = "use `envigil::parse::bool` instead")]
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}"))
}
pub fn url(raw: &str) -> Result<String, String> {
let trimmed = raw.trim();
if trimmed.is_empty() {
return Err("URL must not be empty".to_owned());
}
if trimmed
.chars()
.any(|c| c.is_ascii_control() || c == ' ' || c == '\t')
{
return Err(format!(
"URL contains invalid whitespace or control characters: {trimmed:?}"
));
}
let scheme_end = trimmed
.find("://")
.ok_or_else(|| format!("URL must contain '://' scheme separator: {trimmed:?}"))?;
if scheme_end == 0 {
return Err(format!("URL scheme must not be empty: {trimmed:?}"));
}
let scheme = &trimmed[..scheme_end];
if !scheme.starts_with(|c: char| c.is_ascii_alphabetic()) {
return Err(format!("URL scheme must start with a letter: {trimmed:?}"));
}
if !scheme
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.')
{
return Err(format!(
"URL scheme contains invalid characters: {trimmed:?}"
));
}
let after_scheme = &trimmed[scheme_end + 3..];
if after_scheme.is_empty() {
return Err(format!(
"URL must have an authority after '://': {trimmed:?}"
));
}
let normalized_scheme = scheme.to_ascii_lowercase();
Ok(format!("{normalized_scheme}://{after_scheme}"))
}
#[cfg(feature = "url")]
pub fn strict_url(raw: &str) -> Result<::url::Url, String> {
::url::Url::parse(raw.trim()).map_err(|e| format!("invalid URL: {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]
#[allow(deprecated)]
fn flag_true_variants() {
for v in ["true", "1", "yes", "on", "TRUE", "Yes", "ON"] {
assert!(flag(v).unwrap(), "input: {v}");
}
}
#[test]
#[allow(deprecated)]
fn flag_false_variants() {
for v in ["false", "0", "no", "off", "FALSE", "No", "OFF"] {
assert!(!flag(v).unwrap(), "input: {v}");
}
}
#[test]
#[allow(deprecated)]
fn flag_invalid() {
assert!(flag("maybe").is_err());
assert!(flag("2").is_err());
assert!(flag("").is_err());
}
#[test]
#[allow(deprecated)]
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());
}
#[test]
fn url_basic_http() {
assert_eq!(url("http://example.com").unwrap(), "http://example.com");
}
#[test]
fn url_normalizes_scheme_to_lowercase() {
assert_eq!(
url("HTTPS://Example.COM/path").unwrap(),
"https://Example.COM/path"
);
}
#[test]
fn url_preserves_trailing_slash() {
assert_eq!(url("https://example.com/").unwrap(), "https://example.com/");
assert_eq!(
url("https://example.com/path/").unwrap(),
"https://example.com/path/"
);
}
#[test]
fn url_preserves_root_slash() {
assert_eq!(url("https://example.com/").unwrap(), "https://example.com/");
}
#[test]
fn url_trims_whitespace() {
assert_eq!(
url(" https://example.com ").unwrap(),
"https://example.com"
);
}
#[test]
fn url_custom_schemes() {
assert_eq!(
url("postgres://localhost/db").unwrap(),
"postgres://localhost/db"
);
assert_eq!(
url("redis+tls://cache:6379").unwrap(),
"redis+tls://cache:6379"
);
assert_eq!(url("my-app.v2://host").unwrap(), "my-app.v2://host");
}
#[test]
fn url_with_port_and_path() {
assert_eq!(
url("http://localhost:8080/api/v1").unwrap(),
"http://localhost:8080/api/v1"
);
}
#[test]
fn url_with_query_and_fragment() {
assert_eq!(
url("https://example.com/path?key=val#frag").unwrap(),
"https://example.com/path?key=val#frag"
);
}
#[test]
fn url_rejects_empty() {
assert!(url("").is_err());
assert!(url(" ").is_err());
}
#[test]
fn url_rejects_no_scheme() {
assert!(url("example.com").is_err());
assert!(url("/just/a/path").is_err());
}
#[test]
fn url_rejects_empty_scheme() {
assert!(url("://no-scheme").is_err());
}
#[test]
fn url_rejects_invalid_scheme_start() {
assert!(url("1bad://host").is_err());
assert!(url("-bad://host").is_err());
}
#[test]
fn url_rejects_invalid_scheme_chars() {
assert!(url("bad scheme://host").is_err());
assert!(url("bad!scheme://host").is_err());
}
#[test]
fn url_rejects_empty_authority() {
assert!(url("http://").is_err());
}
#[test]
fn url_rejects_whitespace_inside() {
assert!(url("http://exam ple.com").is_err());
assert!(url("http://example.com/pa th").is_err());
}
#[test]
fn url_rejects_control_characters() {
assert!(url("http://example.com\x00").is_err());
assert!(url("http://example.\x01com").is_err());
}
#[test]
fn url_error_messages_are_descriptive() {
let msg = url("no-scheme").unwrap_err();
assert!(msg.contains("://"), "message: {msg}");
let msg = url("://empty").unwrap_err();
assert!(msg.contains("scheme"), "message: {msg}");
let msg = url("http://").unwrap_err();
assert!(msg.contains("authority"), "message: {msg}");
}
#[test]
fn bool_true_variants() {
for v in ["true", "1", "yes", "on", "TRUE", "Yes", "ON"] {
assert!(bool(v).unwrap(), "input: {v}");
}
}
#[test]
fn bool_false_variants() {
for v in ["false", "0", "no", "off", "FALSE", "No", "OFF"] {
assert!(!bool(v).unwrap(), "input: {v}");
}
}
#[test]
fn bool_invalid() {
assert!(bool("maybe").is_err());
assert!(bool("2").is_err());
assert!(bool("").is_err());
}
#[test]
fn bool_trims_whitespace() {
assert!(bool(" true ").unwrap());
}
#[test]
#[allow(deprecated)]
fn flag_still_works() {
assert!(flag("true").unwrap());
assert!(!flag("0").unwrap());
}
}