use crate::error::FieldIssue;
pub fn check_uuid(field: &str, value: &str) -> Result<(), FieldIssue> {
let bytes = value.as_bytes();
if bytes.len() != 36 {
return Err(FieldIssue::new(
field,
"INVALID_UUID",
"must be a canonical UUID (8-4-4-4-12)",
));
}
for (idx, &b) in bytes.iter().enumerate() {
let expect_dash = matches!(idx, 8 | 13 | 18 | 23);
if expect_dash {
if b != b'-' {
return Err(FieldIssue::new(
field,
"INVALID_UUID",
"must be a canonical UUID (8-4-4-4-12)",
));
}
} else if !b.is_ascii_hexdigit() {
return Err(FieldIssue::new(
field,
"INVALID_UUID",
"must be a canonical UUID (8-4-4-4-12)",
));
}
}
Ok(())
}
pub fn check_url(field: &str, value: &str, require_https: bool) -> Result<(), FieldIssue> {
if value.chars().any(|c| c.is_whitespace() || c.is_control()) {
return Err(FieldIssue::new(
field,
"INVALID_URL",
"url must not contain whitespace or control characters",
));
}
let bytes = value.as_bytes();
let rest = if bytes.len() >= 8 && bytes[..8].eq_ignore_ascii_case(b"https://") {
&value[8..]
} else if !require_https && bytes.len() >= 7 && bytes[..7].eq_ignore_ascii_case(b"http://") {
&value[7..]
} else if require_https {
return Err(FieldIssue::new(
field,
"INVALID_URL",
"url must start with https://",
));
} else {
return Err(FieldIssue::new(
field,
"INVALID_URL",
"url must start with http:// or https://",
));
};
let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
let host_port = if let Some((userinfo, hp)) = authority.split_once('@') {
if userinfo.is_empty()
|| hp.contains('@')
|| userinfo.bytes().any(|b| {
matches!(
b,
b'<' | b'>' | b'"' | b'{' | b'}' | b'|' | b'\\' | b'^' | b'`' | b'[' | b']'
)
})
{
return Err(FieldIssue::new(
field,
"INVALID_URL",
"url contains invalid authority userinfo",
));
}
hp
} else {
authority
};
if !is_valid_url_host_port(host_port) {
return Err(FieldIssue::new(
field,
"INVALID_URL",
"url must include a valid host",
));
}
Ok(())
}
fn is_valid_url_port(port: &str) -> bool {
!port.is_empty()
&& port.bytes().all(|b| b.is_ascii_digit())
&& matches!(port.parse::<u16>(), Ok(1..=u16::MAX))
}
fn is_valid_url_host_port(host_port: &str) -> bool {
if host_port.is_empty() {
return false;
}
if let Some(after_open) = host_port.strip_prefix('[') {
let Some((ipv6_lit, after_close)) = after_open.split_once(']') else {
return false;
};
if ipv6_lit.parse::<core::net::Ipv6Addr>().is_err() {
return false;
}
return match after_close.strip_prefix(':') {
Some(port) => is_valid_url_port(port),
None => after_close.is_empty(),
};
}
let (host, port) = match host_port.split_once(':') {
Some((h, p)) => (h, Some(p)),
None => (host_port, None),
};
if let Some(port) = port {
if !is_valid_url_port(port) {
return false;
}
}
if host.is_empty() || host.starts_with('.') || host.ends_with('.') || host.contains("..") {
return false;
}
if host.parse::<core::net::Ipv4Addr>().is_ok() {
return true;
}
for label in host.split('.') {
let b = label.as_bytes();
if b.is_empty()
|| b.len() > 63
|| b[0] == b'-'
|| b[b.len() - 1] == b'-'
|| !b
.iter()
.all(|&c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
{
return false;
}
}
true
}
pub fn check_slug(field: &str, value: &str) -> Result<(), FieldIssue> {
if value.is_empty()
|| value.starts_with('-')
|| value.ends_with('-')
|| value.contains("--")
|| !value
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
{
return Err(FieldIssue::new(
field,
"INVALID_SLUG",
"must be lowercase alphanumeric words separated by single hyphens",
));
}
Ok(())
}
pub fn check_charset(field: &str, value: &str, spec: &str) -> Result<(), FieldIssue> {
let ok = if spec.is_ascii() {
let mask = build_ascii_charset_mask(spec.as_bytes());
value
.bytes()
.all(|b| b < 128 && (mask & (1_u128 << b)) != 0)
} else {
value.chars().all(|ch| char_matches_unicode_spec(ch, spec))
};
if ok {
Ok(())
} else {
Err(FieldIssue::new(
field,
"STRING_INVALID_CHARSET",
format!("contains characters outside allowed set [{spec}]"),
))
}
}
fn build_ascii_charset_mask(bytes: &[u8]) -> u128 {
let mut mask = 0_u128;
let mut i = 0;
while i < bytes.len() {
if i + 2 < bytes.len() && bytes[i] != b'-' && bytes[i + 1] == b'-' && bytes[i + 2] != b'-' {
let start = bytes[i];
let end = bytes[i + 2];
if start <= end {
for b in start..=end {
mask |= 1_u128 << b;
}
}
i += 3;
} else {
mask |= 1_u128 << bytes[i];
i += 1;
}
}
mask
}
fn char_matches_unicode_spec(ch: char, spec: &str) -> bool {
let mut iter = spec.chars().peekable();
while let Some(first) = iter.next() {
if first != '-' && iter.peek() == Some(&'-') {
let _dash = iter.next();
if let Some(end) = iter.next() {
if end != '-' {
if start_to_end_contains(first, end, ch) {
return true;
}
continue;
}
if ch == first || ch == '-' {
return true;
}
continue;
}
if ch == first || ch == '-' {
return true;
}
} else if ch == first {
return true;
}
}
false
}
const fn start_to_end_contains(start: char, end: char, ch: char) -> bool {
start <= end && ch >= start && ch <= end
}
pub fn check_ipv4(field: &str, value: &str) -> Result<(), FieldIssue> {
value
.parse::<core::net::Ipv4Addr>()
.map(|_| ())
.map_err(|_| FieldIssue::new(field, "INVALID_IPV4", "must be a valid IPv4 address"))
}
pub fn check_ipv6(field: &str, value: &str) -> Result<(), FieldIssue> {
value
.parse::<core::net::Ipv6Addr>()
.map(|_| ())
.map_err(|_| FieldIssue::new(field, "INVALID_IPV6", "must be a valid IPv6 address"))
}
pub fn check_ip(field: &str, value: &str) -> Result<(), FieldIssue> {
value
.parse::<core::net::IpAddr>()
.map(|_| ())
.map_err(|_| FieldIssue::new(field, "INVALID_IP", "must be a valid IPv4 or IPv6 address"))
}
pub fn check_hostname(field: &str, value: &str) -> Result<(), FieldIssue> {
let bad = || {
Err(FieldIssue::new(
field,
"INVALID_HOSTNAME",
"must be a valid RFC 1123 hostname",
))
};
if value.is_empty() || value.len() > 253 || value.starts_with('.') || value.ends_with('.') {
return bad();
}
let mut count = 0usize;
let mut last = "";
for label in value.split('.') {
let b = label.as_bytes();
if b.is_empty()
|| b.len() > 63
|| b[0] == b'-'
|| b[b.len() - 1] == b'-'
|| !b.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'-')
{
return bad();
}
count += 1;
last = label;
}
if count > 1 && last.bytes().all(|c| c.is_ascii_digit()) {
return bad();
}
Ok(())
}
pub fn check_semver(field: &str, value: &str) -> Result<(), FieldIssue> {
let bad = || {
Err(FieldIssue::new(
field,
"INVALID_SEMVER",
"must be a valid SemVer 2.0.0 version",
))
};
let (rest, build) = match value.split_once('+') {
Some((r, b)) => (r, Some(b)),
None => (value, None),
};
let (core_part, pre) = match rest.split_once('-') {
Some((c, p)) => (c, Some(p)),
None => (rest, None),
};
let mut core_iter = core_part.split('.');
let (Some(major), Some(minor), Some(patch), None) = (
core_iter.next(),
core_iter.next(),
core_iter.next(),
core_iter.next(),
) else {
return bad();
};
for n in [major, minor, patch] {
if n.is_empty()
|| !n.bytes().all(|c| c.is_ascii_digit())
|| (n.len() > 1 && n.starts_with('0'))
{
return bad();
}
}
if let Some(pre) = pre {
for id in pre.split('.') {
if id.is_empty() || !id.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-') {
return bad();
}
if id.bytes().all(|c| c.is_ascii_digit()) && id.len() > 1 && id.starts_with('0') {
return bad();
}
}
}
if let Some(build) = build {
for id in build.split('.') {
if id.is_empty() || !id.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-') {
return bad();
}
}
}
Ok(())
}
pub fn check_hex(field: &str, value: &str) -> Result<(), FieldIssue> {
if !value.is_empty() && value.bytes().all(|b| b.is_ascii_hexdigit()) {
Ok(())
} else {
Err(FieldIssue::new(
field,
"INVALID_HEX",
"must be a non-empty hexadecimal string",
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn uuid_check() {
assert!(check_uuid("id", "550e8400-e29b-41d4-a716-446655440000").is_ok());
assert!(check_uuid("id", "not-a-uuid").is_err());
}
#[test]
fn url_check() {
assert!(check_url("u", "https://example.com/a?b=1", true).is_ok());
assert!(check_url("u", "HTTPS://example.com:8443/a", true).is_ok());
assert!(check_url("u", "http://[::1]:8080/health", false).is_ok());
assert!(check_url("u", "http://example.com", true).is_err());
assert!(check_url("u", "http://example.com", false).is_ok());
assert!(check_url("u", "https:///path", true).is_err());
assert!(check_url("u", "https://<>\"{}|\\^`[]", true).is_err());
assert!(check_url("u", "https://example.com:99999", true).is_err());
assert!(check_url("u", "https://example.com:notaport", true).is_err());
assert!(check_url("u", "https://example.com:80:80", true).is_err());
assert!(check_url("u", "https://user@host@evil.com", true).is_err());
assert!(check_url("u", "https://[not-ipv6]", true).is_err());
assert!(check_url("u", "https://a..b", true).is_err());
assert!(check_url("u", "https://bad.:80", true).is_err());
}
#[test]
fn slug_and_charset_checks() {
assert!(check_slug("slug", "wire-v1-alpha").is_ok());
assert!(check_slug("slug", "Bad_Slug").is_err());
assert!(check_slug("slug", "a--b").is_err());
assert!(check_charset("handle", "ada_99-x", "a-z0-9_-").is_ok());
assert!(check_charset("handle", "ada-x", "-a-z").is_ok());
assert!(check_charset("handle", "ada.x", "--z").is_err());
assert!(check_charset("handle", "Ada!", "a-z0-9_-").is_err());
assert!(check_charset("umlaut", "äöü", "äöü").is_ok());
assert!(check_charset("umlaut", "Ã", "äöü").is_err());
}
#[test]
fn ip_checks() {
assert!(check_ipv4("ip", "192.168.0.1").is_ok());
assert!(check_ipv4("ip", "256.1.1.1").is_err());
assert!(check_ipv4("ip", "::1").is_err());
assert!(check_ipv6("ip", "::1").is_ok());
assert!(check_ipv6("ip", "2001:db8::ff00:42:8329").is_ok());
assert!(check_ipv6("ip", "1.2.3.4").is_err());
assert!(check_ip("ip", "1.2.3.4").is_ok());
assert!(check_ip("ip", "::1").is_ok());
assert!(check_ip("ip", "nope").is_err());
}
#[test]
fn hostname_checks() {
assert!(check_hostname("h", "example.com").is_ok());
assert!(check_hostname("h", "localhost").is_ok());
assert!(check_hostname("h", "a-b.example.org").is_ok());
assert!(check_hostname("h", "").is_err());
assert!(check_hostname("h", "-bad.com").is_err());
assert!(check_hostname("h", "bad-.com").is_err());
assert!(check_hostname("h", "a..b").is_err());
assert!(check_hostname("h", ".a.com").is_err());
assert!(check_hostname("h", "a.com.").is_err());
assert!(check_hostname("h", "1.2.3.4").is_err());
assert!(check_hostname("h", "under_score.com").is_err());
assert!(check_hostname("h", &"a".repeat(64)).is_err());
assert!(check_hostname("h", &"a".repeat(63)).is_ok());
}
#[test]
fn semver_checks() {
assert!(check_semver("v", "1.2.3").is_ok());
assert!(check_semver("v", "0.0.0").is_ok());
assert!(check_semver("v", "1.0.0-alpha.1+build.5").is_ok());
assert!(check_semver("v", "1.0.0-0.3.7").is_ok());
assert!(check_semver("v", "1.2").is_err());
assert!(check_semver("v", "01.2.3").is_err());
assert!(check_semver("v", "1.2.3-01").is_err());
assert!(check_semver("v", "1.2.3-").is_err());
assert!(check_semver("v", "1.2.3+").is_err());
assert!(check_semver("v", "v1.2.3").is_err());
}
#[test]
fn hex_checks() {
assert!(check_hex("h", "deadBEEF09").is_ok());
assert!(check_hex("h", "").is_err());
assert!(check_hex("h", "xyz").is_err());
}
}