use std::fmt;
use std::ops::RangeInclusive;
pub trait Validator<T: ?Sized> {
fn validate(&self, value: &T) -> Result<(), String>;
}
impl<T: ?Sized, F> Validator<T> for F
where
F: Fn(&T) -> Result<(), String>,
{
fn validate(&self, value: &T) -> Result<(), String> {
self(value)
}
}
#[derive(Debug, Clone)]
pub struct RangeValidator<T> {
range: RangeInclusive<T>,
description: String,
}
pub fn range<T>(range: RangeInclusive<T>) -> RangeValidator<T>
where
T: PartialOrd + Clone + fmt::Display,
{
let description = format!("{}..={}", range.start(), range.end());
RangeValidator { range, description }
}
impl<T> Validator<T> for RangeValidator<T>
where
T: PartialOrd + Clone + fmt::Display,
{
fn validate(&self, value: &T) -> Result<(), String> {
if self.range.contains(value) {
Ok(())
} else {
Err(format!(
"value {value} is out of range {}",
self.description
))
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct NotEmpty;
#[must_use]
pub const fn not_empty() -> NotEmpty {
NotEmpty
}
impl Validator<String> for NotEmpty {
fn validate(&self, value: &String) -> Result<(), String> {
if value.is_empty() {
Err("must not be empty".to_owned())
} else {
Ok(())
}
}
}
impl Validator<str> for NotEmpty {
fn validate(&self, value: &str) -> Result<(), String> {
if value.is_empty() {
Err("must not be empty".to_owned())
} else {
Ok(())
}
}
}
#[derive(Debug, Clone)]
pub struct Contains {
substring: String,
}
pub fn contains(substring: impl Into<String>) -> Contains {
Contains {
substring: substring.into(),
}
}
impl Validator<String> for Contains {
fn validate(&self, value: &String) -> Result<(), String> {
if value.contains(&self.substring) {
Ok(())
} else {
Err(format!("must contain {:?}", self.substring))
}
}
}
#[derive(Debug, Clone)]
pub struct StartsWith {
prefix: String,
}
pub fn starts_with(prefix: impl Into<String>) -> StartsWith {
StartsWith {
prefix: prefix.into(),
}
}
impl Validator<String> for StartsWith {
fn validate(&self, value: &String) -> Result<(), String> {
if value.starts_with(&self.prefix) {
Ok(())
} else {
Err(format!("must start with {:?}", self.prefix))
}
}
}
#[derive(Debug, Clone)]
pub struct EndsWith {
suffix: String,
}
pub fn ends_with(suffix: impl Into<String>) -> EndsWith {
EndsWith {
suffix: suffix.into(),
}
}
impl Validator<String> for EndsWith {
fn validate(&self, value: &String) -> Result<(), String> {
if value.ends_with(&self.suffix) {
Ok(())
} else {
Err(format!("must end with {:?}", self.suffix))
}
}
}
#[derive(Debug, Clone)]
pub struct LengthValidator {
range: RangeInclusive<usize>,
description: String,
}
#[must_use]
pub fn length(range: RangeInclusive<usize>) -> LengthValidator {
let description = format!("{}..={}", range.start(), range.end());
LengthValidator { range, description }
}
impl LengthValidator {
fn check_len(&self, len: usize) -> Result<(), String> {
if self.range.contains(&len) {
Ok(())
} else {
Err(format!("length {len} is out of range {}", self.description))
}
}
}
impl Validator<String> for LengthValidator {
fn validate(&self, value: &String) -> Result<(), String> {
self.check_len(value.len())
}
}
impl Validator<str> for LengthValidator {
fn validate(&self, value: &str) -> Result<(), String> {
self.check_len(value.len())
}
}
impl<T> Validator<Vec<T>> for LengthValidator {
fn validate(&self, value: &Vec<T>) -> Result<(), String> {
self.check_len(value.len())
}
}
#[derive(Debug, Clone, Copy)]
pub struct Ip;
#[must_use]
pub const fn ip() -> Ip {
Ip
}
impl Validator<String> for Ip {
fn validate(&self, value: &String) -> Result<(), String> {
if value.parse::<std::net::IpAddr>().is_ok() {
Ok(())
} else {
Err("must be a valid IP address".to_owned())
}
}
}
impl Validator<str> for Ip {
fn validate(&self, value: &str) -> Result<(), String> {
if value.parse::<std::net::IpAddr>().is_ok() {
Ok(())
} else {
Err("must be a valid IP address".to_owned())
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct Email;
#[must_use]
pub const fn email() -> Email {
Email
}
impl Email {
fn check(value: &str) -> Result<(), String> {
if value.is_empty() {
return Err("must be a valid email address".to_owned());
}
if value.len() > 254 {
return Err("must be a valid email address".to_owned());
}
if value
.chars()
.any(|c| c.is_ascii_whitespace() || c.is_ascii_control())
{
return Err("must be a valid email address".to_owned());
}
let Some(at_pos) = value.find('@') else {
return Err("must be a valid email address".to_owned());
};
if value[at_pos + 1..].contains('@') {
return Err("must be a valid email address".to_owned());
}
let local = &value[..at_pos];
let domain = &value[at_pos + 1..];
if local.is_empty() || domain.is_empty() {
return Err("must be a valid email address".to_owned());
}
if local.starts_with('.')
|| local.ends_with('.')
|| domain.starts_with('.')
|| domain.ends_with('.')
{
return Err("must be a valid email address".to_owned());
}
if !domain.contains('.') {
return Err("must be a valid email address".to_owned());
}
Ok(())
}
}
impl Validator<String> for Email {
fn validate(&self, value: &String) -> Result<(), String> {
Self::check(value)
}
}
impl Validator<str> for Email {
fn validate(&self, value: &str) -> Result<(), String> {
Self::check(value)
}
}
#[derive(Debug, Clone, Copy)]
pub struct Hostname;
#[must_use]
pub const fn hostname() -> Hostname {
Hostname
}
impl Hostname {
fn check(value: &str) -> Result<(), String> {
if value.is_empty() {
return Err("must be a valid hostname".to_owned());
}
let trimmed = value.strip_suffix('.').unwrap_or(value);
if trimmed.is_empty() || trimmed.len() > 253 {
return Err("must be a valid hostname".to_owned());
}
for label in trimmed.split('.') {
if label.is_empty() || label.len() > 63 {
return Err("must be a valid hostname".to_owned());
}
if label.starts_with('-') || label.ends_with('-') {
return Err("must be a valid hostname".to_owned());
}
if !label
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-')
{
return Err("must be a valid hostname".to_owned());
}
}
Ok(())
}
}
impl Validator<String> for Hostname {
fn validate(&self, value: &String) -> Result<(), String> {
Self::check(value)
}
}
impl Validator<str> for Hostname {
fn validate(&self, value: &str) -> Result<(), String> {
Self::check(value)
}
}
#[derive(Debug, Clone, Copy)]
pub struct Host;
#[must_use]
pub const fn host() -> Host {
Host
}
impl Host {
fn check(value: &str) -> Result<(), String> {
if value.parse::<std::net::IpAddr>().is_ok() {
return Ok(());
}
Hostname::check(value)
}
}
impl Validator<String> for Host {
fn validate(&self, value: &String) -> Result<(), String> {
Self::check(value)
}
}
impl Validator<str> for Host {
fn validate(&self, value: &str) -> Result<(), String> {
Self::check(value)
}
}
#[derive(Debug, Clone, Copy)]
pub struct Url;
#[must_use]
pub const fn url() -> Url {
Url
}
impl Url {
fn check(value: &str) -> Result<(), String> {
crate::parse::url(value).map(|_| ())
}
}
impl Validator<String> for Url {
fn validate(&self, value: &String) -> Result<(), String> {
Self::check(value)
}
}
impl Validator<str> for Url {
fn validate(&self, value: &str) -> Result<(), String> {
Self::check(value)
}
}
#[derive(Debug, Clone)]
pub struct OneOf {
values: Vec<String>,
}
pub fn one_of<I, S>(values: I) -> OneOf
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
OneOf {
values: values.into_iter().map(Into::into).collect(),
}
}
impl OneOf {
fn check(&self, value: &str) -> Result<(), String> {
if self.values.iter().any(|v| v == value) {
Ok(())
} else {
Err(format!("must be one of: {}", self.values.join(", ")))
}
}
}
impl Validator<String> for OneOf {
fn validate(&self, value: &String) -> Result<(), String> {
self.check(value)
}
}
impl Validator<str> for OneOf {
fn validate(&self, value: &str) -> Result<(), String> {
self.check(value)
}
}
#[derive(Debug, Clone, Copy)]
pub struct Port;
#[must_use]
pub const fn port() -> Port {
Port
}
impl Validator<u16> for Port {
fn validate(&self, value: &u16) -> Result<(), String> {
if *value >= 1 {
Ok(())
} else {
Err("must be a valid port number (1..=65535)".to_owned())
}
}
}
impl Validator<u32> for Port {
fn validate(&self, value: &u32) -> Result<(), String> {
if *value >= 1 && *value <= 65535 {
Ok(())
} else {
Err(format!(
"must be a valid port number (1..=65535), got {value}"
))
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct PrivilegedPort;
#[must_use]
pub const fn privileged_port() -> PrivilegedPort {
PrivilegedPort
}
impl Validator<u16> for PrivilegedPort {
fn validate(&self, value: &u16) -> Result<(), String> {
if *value >= 1 && *value <= 1023 {
Ok(())
} else {
Err(format!("must be a privileged port (1..=1023), got {value}"))
}
}
}
impl Validator<u32> for PrivilegedPort {
fn validate(&self, value: &u32) -> Result<(), String> {
if *value >= 1 && *value <= 1023 {
Ok(())
} else {
Err(format!("must be a privileged port (1..=1023), got {value}"))
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct UserPort;
#[must_use]
pub const fn user_port() -> UserPort {
UserPort
}
impl Validator<u16> for UserPort {
fn validate(&self, value: &u16) -> Result<(), String> {
if *value >= 1024 {
Ok(())
} else {
Err(format!("must be a user port (1024..=65535), got {value}"))
}
}
}
impl Validator<u32> for UserPort {
fn validate(&self, value: &u32) -> Result<(), String> {
if *value >= 1024 && *value <= 65535 {
Ok(())
} else {
Err(format!("must be a user port (1024..=65535), got {value}"))
}
}
}
#[cfg(feature = "url")]
#[derive(Debug, Clone, Copy)]
pub struct StrictUrl;
#[cfg(feature = "url")]
#[must_use]
pub const fn strict_url() -> StrictUrl {
StrictUrl
}
#[cfg(feature = "url")]
impl StrictUrl {
fn check(value: &str) -> Result<(), String> {
::url::Url::parse(value.trim())
.map(|_| ())
.map_err(|e| format!("invalid URL: {e}"))
}
}
#[cfg(feature = "url")]
impl Validator<String> for StrictUrl {
fn validate(&self, value: &String) -> Result<(), String> {
Self::check(value)
}
}
#[cfg(feature = "url")]
impl Validator<str> for StrictUrl {
fn validate(&self, value: &str) -> Result<(), String> {
Self::check(value)
}
}
#[derive(Debug, Clone, Copy)]
pub struct FileExists;
#[must_use]
pub const fn file_exists() -> FileExists {
FileExists
}
impl Validator<String> for FileExists {
fn validate(&self, value: &String) -> Result<(), String> {
if std::path::Path::new(value).exists() {
Ok(())
} else {
Err("file does not exist".to_owned())
}
}
}
impl Validator<std::path::PathBuf> for FileExists {
fn validate(&self, value: &std::path::PathBuf) -> Result<(), String> {
if value.exists() {
Ok(())
} else {
Err("file does not exist".to_owned())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn range_accepts_in_bounds() {
let v = range(1..=65535);
assert!(v.validate(&1u16).is_ok());
assert!(v.validate(&8080u16).is_ok());
assert!(v.validate(&65535u16).is_ok());
}
#[test]
fn range_rejects_out_of_bounds() {
let v = range(1..=65535);
assert!(v.validate(&0u16).is_err());
}
#[test]
fn range_error_message() {
let v = range(1..=100);
let msg = v.validate(&200).unwrap_err();
assert!(msg.contains("200"), "message: {msg}");
assert!(msg.contains("1..=100"), "message: {msg}");
}
#[test]
fn not_empty_accepts_nonempty() {
let v = not_empty();
assert!(v.validate(&"x".to_owned()).is_ok());
}
#[test]
fn not_empty_rejects_empty_string() {
let v = not_empty();
let msg = v.validate(&String::new()).unwrap_err();
assert_eq!(msg, "must not be empty");
}
#[test]
fn not_empty_rejects_empty_str() {
let v = not_empty();
assert!(v.validate("").is_err());
assert!(v.validate("ok").is_ok());
}
#[test]
fn contains_match() {
let v = contains("@");
assert!(v.validate(&"a@b.com".to_owned()).is_ok());
}
#[test]
fn contains_no_match() {
let v = contains('@');
let msg = v.validate(&"nope".to_owned()).unwrap_err();
assert!(msg.contains('@'), "message: {msg}");
}
#[test]
fn starts_with_match() {
let v = starts_with("postgres://");
assert!(v.validate(&"postgres://localhost".to_owned()).is_ok());
}
#[test]
fn starts_with_no_match() {
let v = starts_with("postgres://");
let msg = v.validate(&"mysql://localhost".to_owned()).unwrap_err();
assert!(msg.contains("postgres://"), "message: {msg}");
}
#[test]
fn ends_with_match() {
let v = ends_with(".rs");
assert!(v.validate(&"lib.rs".to_owned()).is_ok());
}
#[test]
fn ends_with_no_match() {
let v = ends_with(".rs");
let msg = v.validate(&"lib.py".to_owned()).unwrap_err();
assert!(msg.contains(".rs"), "message: {msg}");
}
#[test]
fn closure_validator() {
let even = |n: &u32| {
if n % 2 == 0 {
Ok(())
} else {
Err(format!("{n} is odd"))
}
};
assert!(even.validate(&4).is_ok());
assert_eq!(even.validate(&3).unwrap_err(), "3 is odd");
}
#[test]
fn works_as_trait_object() {
let validators: Vec<Box<dyn Validator<String>>> =
vec![Box::new(not_empty()), Box::new(contains("@"))];
let value = "user@example.com".to_owned();
for v in &validators {
assert!(v.validate(&value).is_ok());
}
let bad = String::new();
assert!(validators[0].validate(&bad).is_err());
}
#[test]
fn length_accepts_string_in_range() {
let v = length(1..=5);
assert!(v.validate(&"abc".to_owned()).is_ok());
assert!(v.validate(&"a".to_owned()).is_ok());
assert!(v.validate(&"abcde".to_owned()).is_ok());
}
#[test]
fn length_rejects_too_short() {
let v = length(2..=5);
assert!(v.validate(&"a".to_owned()).is_err());
assert!(v.validate(&String::new()).is_err());
}
#[test]
fn length_rejects_too_long() {
let v = length(1..=3);
assert!(v.validate(&"abcdef".to_owned()).is_err());
}
#[test]
fn length_works_on_str() {
let v = length(1..=5);
assert!(v.validate("abc").is_ok());
assert!(v.validate("").is_err());
}
#[test]
fn length_works_on_vec() {
let v = length(1..=3);
assert!(v.validate(&vec![1, 2]).is_ok());
assert!(v.validate(&Vec::<u8>::new()).is_err());
assert!(v.validate(&vec![1, 2, 3, 4]).is_err());
}
#[test]
fn length_error_message() {
let v = length(2..=5);
let msg = v.validate(&"a".to_owned()).unwrap_err();
assert!(msg.contains("length 1"), "message: {msg}");
assert!(msg.contains("2..=5"), "message: {msg}");
}
#[test]
fn ip_accepts_ipv4() {
let v = ip();
assert!(v.validate(&"127.0.0.1".to_owned()).is_ok());
assert!(v.validate(&"192.168.1.1".to_owned()).is_ok());
assert!(v.validate(&"0.0.0.0".to_owned()).is_ok());
}
#[test]
fn ip_accepts_ipv6() {
let v = ip();
assert!(v.validate(&"::1".to_owned()).is_ok());
assert!(v.validate(&"2001:db8::1".to_owned()).is_ok());
}
#[test]
fn ip_rejects_invalid() {
let v = ip();
assert!(v.validate(&"999.999.999.999".to_owned()).is_err());
assert!(v.validate(&"not-an-ip".to_owned()).is_err());
assert!(v.validate(&"1.2.3".to_owned()).is_err());
assert!(v.validate(&String::new()).is_err());
}
#[test]
fn ip_works_on_str() {
let v = ip();
assert!(v.validate("10.0.0.1").is_ok());
assert!(v.validate("nope").is_err());
}
#[test]
fn ip_error_message() {
let v = ip();
let msg = v.validate(&"bad".to_owned()).unwrap_err();
assert!(msg.contains("IP address"), "message: {msg}");
}
#[test]
fn file_exists_accepts_existing_path() {
let v = file_exists();
assert!(v.validate(&".".to_owned()).is_ok());
}
#[test]
fn file_exists_rejects_missing_path() {
let v = file_exists();
assert!(
v.validate(&"definitely_missing_envigil_file_xyz".to_owned())
.is_err()
);
}
#[test]
fn file_exists_error_message() {
let v = file_exists();
let msg = v
.validate(&"definitely_missing_envigil_file_xyz".to_owned())
.unwrap_err();
assert!(msg.contains("does not exist"), "message: {msg}");
}
#[test]
fn file_exists_works_on_pathbuf() {
let v = file_exists();
assert!(v.validate(&std::path::PathBuf::from(".")).is_ok());
assert!(
v.validate(&std::path::PathBuf::from(
"definitely_missing_envigil_file_xyz"
))
.is_err()
);
}
#[test]
fn hostname_accepts_simple() {
let v = hostname();
assert!(v.validate(&"localhost".to_owned()).is_ok());
assert!(v.validate(&"example".to_owned()).is_ok());
}
#[test]
fn hostname_accepts_dotted() {
let v = hostname();
assert!(v.validate(&"example.com".to_owned()).is_ok());
assert!(v.validate(&"my-host.example.co.uk".to_owned()).is_ok());
}
#[test]
fn hostname_accepts_fqdn() {
let v = hostname();
assert!(v.validate(&"example.com.".to_owned()).is_ok());
}
#[test]
fn hostname_accepts_with_digits() {
let v = hostname();
assert!(v.validate(&"host123".to_owned()).is_ok());
assert!(v.validate(&"123host".to_owned()).is_ok());
assert!(v.validate(&"a1b2c3".to_owned()).is_ok());
}
#[test]
fn hostname_rejects_leading_hyphen() {
let v = hostname();
assert!(v.validate(&"-bad.com".to_owned()).is_err());
}
#[test]
fn hostname_rejects_trailing_hyphen() {
let v = hostname();
assert!(v.validate(&"bad-.com".to_owned()).is_err());
}
#[test]
fn hostname_rejects_empty_label() {
let v = hostname();
assert!(v.validate(&"bad..host.com".to_owned()).is_err());
}
#[test]
fn hostname_rejects_underscore() {
let v = hostname();
assert!(v.validate(&"bad_host.com".to_owned()).is_err());
}
#[test]
fn hostname_rejects_space() {
let v = hostname();
assert!(v.validate(&"bad host.com".to_owned()).is_err());
}
#[test]
fn hostname_rejects_empty() {
let v = hostname();
assert!(v.validate(&String::new()).is_err());
assert!(v.validate("").is_err());
}
#[test]
fn hostname_rejects_only_dot() {
let v = hostname();
assert!(v.validate(&".".to_owned()).is_err());
}
#[test]
fn hostname_rejects_label_too_long() {
let v = hostname();
let long_label = "a".repeat(64);
assert!(v.validate(&long_label).is_err());
let ok_label = "a".repeat(63);
assert!(v.validate(&ok_label).is_ok());
}
#[test]
fn hostname_rejects_total_too_long() {
let v = hostname();
let long = format!("{}.{}.com", "a".repeat(63), "b".repeat(186));
assert_eq!(long.len(), 254);
assert!(v.validate(&long).is_err());
}
#[test]
fn hostname_works_on_str() {
let v = hostname();
assert!(v.validate("example.com").is_ok());
assert!(v.validate("bad..host").is_err());
}
#[test]
fn hostname_error_message() {
let v = hostname();
let msg = v.validate(&"-bad".to_owned()).unwrap_err();
assert!(msg.contains("hostname"), "message: {msg}");
}
#[test]
fn host_accepts_ipv4() {
let v = host();
assert!(v.validate(&"127.0.0.1".to_owned()).is_ok());
assert!(v.validate(&"10.0.0.1".to_owned()).is_ok());
}
#[test]
fn host_accepts_ipv6() {
let v = host();
assert!(v.validate(&"::1".to_owned()).is_ok());
assert!(v.validate(&"2001:db8::1".to_owned()).is_ok());
}
#[test]
fn host_accepts_hostname() {
let v = host();
assert!(v.validate(&"localhost".to_owned()).is_ok());
assert!(v.validate(&"db.example.com".to_owned()).is_ok());
}
#[test]
fn host_rejects_invalid() {
let v = host();
assert!(v.validate(&"-bad".to_owned()).is_err());
assert!(v.validate(&"bad..host".to_owned()).is_err());
assert!(v.validate(&String::new()).is_err());
}
#[test]
fn host_rejects_empty() {
let v = host();
assert!(v.validate(&String::new()).is_err());
}
#[test]
fn host_works_on_str() {
let v = host();
assert!(v.validate("127.0.0.1").is_ok());
assert!(v.validate("example.com").is_ok());
assert!(v.validate("-bad").is_err());
}
#[test]
fn host_error_message() {
let v = host();
let msg = v.validate(&"-bad".to_owned()).unwrap_err();
assert!(msg.contains("hostname"), "message: {msg}");
}
#[test]
fn url_validator_accepts_valid() {
let v = url();
assert!(v.validate(&"https://example.com".to_owned()).is_ok());
assert!(v.validate(&"postgres://localhost/db".to_owned()).is_ok());
}
#[test]
fn url_validator_rejects_invalid() {
let v = url();
assert!(v.validate(&"not-a-url".to_owned()).is_err());
assert!(v.validate(&String::new()).is_err());
assert!(v.validate(&"http://".to_owned()).is_err());
}
#[test]
fn url_validator_works_on_str() {
let v = url();
assert!(v.validate("https://example.com").is_ok());
assert!(v.validate("nope").is_err());
}
#[test]
fn url_validator_error_message() {
let v = url();
let msg = v.validate(&"bad".to_owned()).unwrap_err();
assert!(msg.contains("://") || msg.contains("URL"), "message: {msg}");
}
#[test]
fn one_of_accepts_matching_value() {
let v = one_of(["debug", "info", "warn", "error"]);
assert!(v.validate(&"info".to_owned()).is_ok());
assert!(v.validate(&"debug".to_owned()).is_ok());
assert!(v.validate(&"error".to_owned()).is_ok());
}
#[test]
fn one_of_rejects_non_matching() {
let v = one_of(["debug", "info", "warn", "error"]);
assert!(v.validate(&"trace".to_owned()).is_err());
assert!(v.validate(&"INFO".to_owned()).is_err()); }
#[test]
fn one_of_rejects_empty_when_not_allowed() {
let v = one_of(["a", "b"]);
assert!(v.validate(&String::new()).is_err());
}
#[test]
fn one_of_accepts_empty_when_allowed() {
let v = one_of(["", "a", "b"]);
assert!(v.validate(&String::new()).is_ok());
}
#[test]
fn one_of_works_on_str() {
let v = one_of(["x", "y"]);
assert!(v.validate("x").is_ok());
assert!(v.validate("z").is_err());
}
#[test]
fn one_of_error_lists_allowed_values() {
let v = one_of(["debug", "info", "warn"]);
let msg = v.validate(&"trace".to_owned()).unwrap_err();
assert!(msg.contains("debug"), "message: {msg}");
assert!(msg.contains("info"), "message: {msg}");
assert!(msg.contains("warn"), "message: {msg}");
assert!(msg.contains("must be one of"), "message: {msg}");
}
#[test]
fn one_of_single_value() {
let v = one_of(["only"]);
assert!(v.validate(&"only".to_owned()).is_ok());
assert!(v.validate(&"other".to_owned()).is_err());
}
#[test]
fn one_of_from_vec() {
let allowed = vec!["a".to_owned(), "b".to_owned()];
let v = one_of(allowed);
assert!(v.validate(&"a".to_owned()).is_ok());
assert!(v.validate(&"c".to_owned()).is_err());
}
#[test]
fn one_of_derive_bare_syntax() {
let v = one_of(["prod", "staging", "dev"]);
assert!(v.validate(&"prod".to_owned()).is_ok());
}
#[test]
fn port_accepts_valid_u16() {
let v = port();
assert!(v.validate(&1u16).is_ok());
assert!(v.validate(&8080u16).is_ok());
assert!(v.validate(&65535u16).is_ok());
}
#[test]
fn port_rejects_zero_u16() {
let v = port();
let msg = v.validate(&0u16).unwrap_err();
assert!(msg.contains("port"), "message: {msg}");
}
#[test]
fn port_accepts_valid_u32() {
let v = port();
assert!(v.validate(&8080u32).is_ok());
assert!(v.validate(&1u32).is_ok());
assert!(v.validate(&65535u32).is_ok());
}
#[test]
fn port_rejects_out_of_range_u32() {
let v = port();
assert!(v.validate(&0u32).is_err());
assert!(v.validate(&65536u32).is_err());
assert!(v.validate(&100_000u32).is_err());
}
#[test]
fn port_error_message_contains_value() {
let v = port();
let msg = v.validate(&70000u32).unwrap_err();
assert!(msg.contains("70000"), "message: {msg}");
assert!(msg.contains("1..=65535"), "message: {msg}");
}
#[test]
fn privileged_port_accepts_valid_u16() {
let v = privileged_port();
assert!(v.validate(&1u16).is_ok());
assert!(v.validate(&80u16).is_ok());
assert!(v.validate(&443u16).is_ok());
assert!(v.validate(&1023u16).is_ok());
}
#[test]
fn privileged_port_rejects_user_ports_u16() {
let v = privileged_port();
assert!(v.validate(&1024u16).is_err());
assert!(v.validate(&8080u16).is_err());
}
#[test]
fn privileged_port_rejects_zero_u16() {
let v = privileged_port();
assert!(v.validate(&0u16).is_err());
}
#[test]
fn privileged_port_accepts_valid_u32() {
let v = privileged_port();
assert!(v.validate(&80u32).is_ok());
assert!(v.validate(&1023u32).is_ok());
}
#[test]
fn privileged_port_rejects_out_of_range_u32() {
let v = privileged_port();
assert!(v.validate(&0u32).is_err());
assert!(v.validate(&1024u32).is_err());
assert!(v.validate(&65536u32).is_err());
}
#[test]
fn privileged_port_error_message() {
let v = privileged_port();
let msg = v.validate(&8080u16).unwrap_err();
assert!(msg.contains("privileged"), "message: {msg}");
assert!(msg.contains("1..=1023"), "message: {msg}");
assert!(msg.contains("8080"), "message: {msg}");
}
#[test]
fn user_port_accepts_valid_u16() {
let v = user_port();
assert!(v.validate(&1024u16).is_ok());
assert!(v.validate(&8080u16).is_ok());
assert!(v.validate(&65535u16).is_ok());
}
#[test]
fn user_port_rejects_privileged_u16() {
let v = user_port();
assert!(v.validate(&1u16).is_err());
assert!(v.validate(&80u16).is_err());
assert!(v.validate(&1023u16).is_err());
}
#[test]
fn user_port_rejects_zero_u16() {
let v = user_port();
assert!(v.validate(&0u16).is_err());
}
#[test]
fn user_port_accepts_valid_u32() {
let v = user_port();
assert!(v.validate(&1024u32).is_ok());
assert!(v.validate(&65535u32).is_ok());
}
#[test]
fn user_port_rejects_out_of_range_u32() {
let v = user_port();
assert!(v.validate(&0u32).is_err());
assert!(v.validate(&1023u32).is_err());
assert!(v.validate(&65536u32).is_err());
}
#[test]
fn user_port_error_message() {
let v = user_port();
let msg = v.validate(&80u16).unwrap_err();
assert!(msg.contains("user port"), "message: {msg}");
assert!(msg.contains("1024..=65535"), "message: {msg}");
assert!(msg.contains("80"), "message: {msg}");
}
#[test]
fn email_accepts_standard() {
let v = email();
assert!(v.validate(&"user@example.com".to_owned()).is_ok());
assert!(v.validate(&"name@sub.domain.org".to_owned()).is_ok());
}
#[test]
fn email_accepts_plus_tag() {
let v = email();
assert!(v.validate(&"user+tag@example.com".to_owned()).is_ok());
}
#[test]
fn email_accepts_dots_in_local() {
let v = email();
assert!(v.validate(&"first.last@example.com".to_owned()).is_ok());
}
#[test]
fn email_accepts_hyphens_in_domain() {
let v = email();
assert!(v.validate(&"user@my-host.example.com".to_owned()).is_ok());
}
#[test]
fn email_rejects_no_at() {
let v = email();
assert!(v.validate(&"userexample.com".to_owned()).is_err());
}
#[test]
fn email_rejects_multiple_at() {
let v = email();
assert!(v.validate(&"user@@example.com".to_owned()).is_err());
assert!(v.validate(&"u@s@example.com".to_owned()).is_err());
}
#[test]
fn email_rejects_empty_local() {
let v = email();
assert!(v.validate(&"@example.com".to_owned()).is_err());
}
#[test]
fn email_rejects_empty_domain() {
let v = email();
assert!(v.validate(&"user@".to_owned()).is_err());
}
#[test]
fn email_rejects_no_dot_in_domain() {
let v = email();
assert!(v.validate(&"user@localhost".to_owned()).is_err());
}
#[test]
fn email_rejects_leading_dot_local() {
let v = email();
assert!(v.validate(&".user@example.com".to_owned()).is_err());
}
#[test]
fn email_rejects_trailing_dot_local() {
let v = email();
assert!(v.validate(&"user.@example.com".to_owned()).is_err());
}
#[test]
fn email_rejects_leading_dot_domain() {
let v = email();
assert!(v.validate(&"user@.example.com".to_owned()).is_err());
}
#[test]
fn email_rejects_trailing_dot_domain() {
let v = email();
assert!(v.validate(&"user@example.com.".to_owned()).is_err());
}
#[test]
fn email_rejects_spaces() {
let v = email();
assert!(v.validate(&"user @example.com".to_owned()).is_err());
assert!(v.validate(&"user@exam ple.com".to_owned()).is_err());
}
#[test]
fn email_rejects_empty() {
let v = email();
assert!(v.validate(&String::new()).is_err());
assert!(v.validate("").is_err());
}
#[test]
fn email_rejects_too_long() {
let v = email();
let long_local = "a".repeat(250);
let addr = format!("{long_local}@example.com");
assert!(addr.len() > 254);
assert!(v.validate(&addr).is_err());
}
#[test]
fn email_works_on_str() {
let v = email();
assert!(v.validate("user@example.com").is_ok());
assert!(v.validate("bad").is_err());
}
#[test]
fn email_error_message() {
let v = email();
let msg = v.validate(&"bad".to_owned()).unwrap_err();
assert!(msg.contains("email"), "message: {msg}");
}
}