pactum-annotations 0.1.0

Declarative field normalization and validation for pactum contracts
Documentation
use crate::error::FieldIssue;

/// Canonical lowercase/uppercase hyphenated UUID (`8-4-4-4-12` hex digits).
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(())
}

/// Structural URL check (`http://` or `https://`, non-empty host, no whitespace/control chars).
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 rest = if let Some(rest) = value.strip_prefix("https://") {
        rest
    } else if !require_https {
        let Some(rest) = value.strip_prefix("http://") else {
            return Err(FieldIssue::new(
                field,
                "INVALID_URL",
                "url must start with http:// or https://",
            ));
        };
        rest
    } else {
        return Err(FieldIssue::new(
            field,
            "INVALID_URL",
            "url must start with https://",
        ));
    };

    let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
    let host = authority.rsplit('@').next().unwrap_or("");
    if host.is_empty() || host.starts_with(':') || host.starts_with('.') || host.ends_with('.') {
        return Err(FieldIssue::new(
            field,
            "INVALID_URL",
            "url must include a valid host",
        ));
    }
    Ok(())
}

/// Lowercase ASCII slug: `[a-z0-9]` segments joined by single `-` characters.
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(())
}

/// Validate every character against a compact ASCII class spec such as `"a-z0-9_-"`.
pub fn check_charset(field: &str, value: &str, spec: &str) -> Result<(), FieldIssue> {
    if value.chars().all(|ch| char_matches_spec(ch, spec)) {
        Ok(())
    } else {
        Err(FieldIssue::new(
            field,
            "STRING_INVALID_CHARSET",
            format!("contains characters outside allowed set [{spec}]"),
        ))
    }
}

fn char_matches_spec(ch: char, spec: &str) -> bool {
    let bytes = spec.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if i + 2 < bytes.len() && bytes[i + 1] == b'-' {
            let start = bytes[i] as char;
            let end = bytes[i + 2] as char;
            if ch >= start && ch <= end {
                return true;
            }
            i += 3;
        } else {
            if ch == bytes[i] as char {
                return true;
            }
            i += 1;
        }
    }
    false
}

#[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", "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());
    }

    #[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!", "a-z0-9_-").is_err());
    }
}