ch-parsing 0.2.0

Typed input parsing with structured, locale-neutral errors
Documentation
use std::borrow::Cow;

use crate::error::{ParseError, ParseErrorCode, ParseResult};

/// Trims and validates a required email address.
///
/// Display names and angle brackets are rejected. Letter case is preserved.
///
/// # Errors
///
/// Returns [`ParseErrorCode::Required`] when the input is empty, or
/// [`ParseErrorCode::InvalidFormat`] when the email syntax is invalid.
pub fn parse_required_email(
    value: &str,
    field: impl Into<Cow<'static, str>>,
) -> ParseResult<String> {
    let field = field.into();
    let trimmed = value.trim();

    if trimmed.is_empty() {
        return Err(ParseError::for_field(field, ParseErrorCode::Required));
    }

    validate_email(trimmed, field)
}

/// Trims and validates an optional email address.
///
/// Empty input becomes `None`. A successful result preserves the address
/// spelling after trimming. Display names and angle brackets are rejected.
/// Applications may apply a separate canonicalization policy where their
/// domain requires one.
///
/// # Errors
///
/// Returns [`ParseErrorCode::InvalidFormat`] when a non-empty email address has
/// invalid syntax.
pub fn parse_optional_email(
    value: &str,
    field: impl Into<Cow<'static, str>>,
) -> ParseResult<Option<String>> {
    let field = field.into();
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return Ok(None);
    }

    validate_email(trimmed, field).map(Some)
}

fn validate_email(trimmed: &str, field: Cow<'static, str>) -> ParseResult<String> {
    email_address::EmailAddress::parse_with_options(
        trimmed,
        email_address::Options::default().without_display_text(),
    )
    .map(String::from)
    .map_err(|_| {
        ParseError::for_field(field, ParseErrorCode::InvalidFormat)
            .with_parameter("expected", "email_address")
    })
}

#[cfg(test)]
mod tests {
    use super::{parse_optional_email, parse_required_email};
    use crate::error::ParseErrorCode;

    #[test]
    fn distinguishes_missing_and_malformed_addresses() {
        let missing = parse_required_email(" \t ", "email").unwrap_err();
        assert_eq!(missing.code(), ParseErrorCode::Required);
        assert_eq!(missing.field(), Some("email"));
        assert!(missing.parameters().is_empty());

        for value in [
            "invalid",
            "missing-domain@",
            "@missing-local",
            "a b@example.com",
        ] {
            let malformed = parse_optional_email(value, "email").unwrap_err();
            assert_eq!(malformed.code(), ParseErrorCode::InvalidFormat);
            assert_eq!(malformed.field(), Some("email"));
            assert_eq!(malformed.parameter("expected"), Some("email_address"));
        }
    }

    #[test]
    fn accepts_optional_empty_input() {
        assert_eq!(parse_optional_email("\n", "email").unwrap(), None);
    }

    #[test]
    fn rejects_display_names_and_angle_brackets() {
        for raw in [
            "Person <person@example.com>",
            "<person@example.com>",
            "  Person <person@example.com>  ",
        ] {
            for error in [
                parse_required_email(raw, "email").unwrap_err(),
                parse_optional_email(raw, "email").unwrap_err(),
            ] {
                assert_eq!(error.code(), ParseErrorCode::InvalidFormat);
                assert_eq!(error.field(), Some("email"));
                assert_eq!(error.parameter("expected"), Some("email_address"));
            }
        }
    }

    #[test]
    fn trims_and_preserves_valid_address_spelling() {
        for (raw, expected) in [
            ("person@example.com", "person@example.com"),
            (" name+tag@example.com ", "name+tag@example.com"),
            ("UPPER@EXAMPLE.COM", "UPPER@EXAMPLE.COM"),
        ] {
            assert_eq!(parse_required_email(raw, "email").unwrap(), expected);
            assert_eq!(
                parse_optional_email(raw, "email").unwrap().as_deref(),
                Some(expected)
            );
        }
    }
}