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 a required string and rejects it when no content remains.
///
/// # Errors
///
/// Returns [`ParseErrorCode::Required`] for `field` when `value` contains only
/// Unicode whitespace.
pub fn require_trimmed(value: &str, field: impl Into<Cow<'static, str>>) -> ParseResult<String> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return Err(ParseError::for_field(field, ParseErrorCode::Required));
    }

    Ok(trimmed.to_owned())
}

/// Ensures a string does not exceed a Unicode scalar-value limit.
///
/// The limit counts [`char`] values, not bytes or user-perceived grapheme
/// clusters. The error parameters contain `max` and `actual` character counts.
///
/// # Errors
///
/// Returns [`ParseErrorCode::TooLong`] for `field` when the count exceeds
/// `max_len`.
pub fn enforce_max_len(
    value: &str,
    max_len: usize,
    field: impl Into<Cow<'static, str>>,
) -> ParseResult<()> {
    let actual_len = value.chars().count();
    if actual_len > max_len {
        return Err(ParseError::for_field(field, ParseErrorCode::TooLong)
            .with_parameter("max", max_len.to_string())
            .with_parameter("actual", actual_len.to_string()));
    }

    Ok(())
}

/// Trims an optional string and removes values with no remaining content.
#[must_use]
pub fn parse_optional_trimmed(value: Option<String>) -> Option<String> {
    value.and_then(|candidate| {
        let trimmed = candidate.trim();
        if trimmed.is_empty() {
            None
        } else if trimmed.len() == candidate.len() {
            Some(candidate)
        } else {
            Some(trimmed.to_owned())
        }
    })
}

#[cfg(test)]
mod tests {
    use super::{enforce_max_len, parse_optional_trimmed, require_trimmed};
    use crate::error::ParseErrorCode;

    #[test]
    fn rejects_all_supported_whitespace_only_required_values() {
        for value in ["", " ", "\t\r\n", "\u{00a0}", " \u{2003}\t"] {
            let error = require_trimmed(value, "identifier")
                .expect_err("whitespace-only input must be rejected");

            assert_eq!(error.code(), ParseErrorCode::Required);
            assert_eq!(error.field(), Some("identifier"));
            assert!(error.parameters().is_empty());
        }
    }

    #[test]
    fn returns_normalized_required_content() {
        assert_eq!(
            require_trimmed("  display name\n", "name").unwrap(),
            "display name"
        );
    }

    #[test]
    fn trims_or_removes_optional_values() {
        assert_eq!(parse_optional_trimmed(None), None);
        assert_eq!(parse_optional_trimmed(Some(" \n ".into())), None);
        assert_eq!(
            parse_optional_trimmed(Some("  display name ".into())),
            Some("display name".to_owned())
        );
        assert_eq!(
            parse_optional_trimmed(Some("display name".into())),
            Some("display name".to_owned())
        );
        assert_eq!(
            parse_optional_trimmed(Some("\u{2003}\u{00a0}".into())),
            None
        );
        assert_eq!(
            parse_optional_trimmed(Some("\u{2003}🦀ä\u{00a0}".into())),
            Some("🦀ä".to_owned())
        );
    }

    #[test]
    fn measures_character_limits_in_unicode_scalar_values() {
        for accepted in ["", "abc", "äbc", "🦀ab"] {
            enforce_max_len(accepted, 3, "name").unwrap();
        }

        let error = enforce_max_len("🦀äbc", 3, "name")
            .expect_err("four scalar values must exceed a limit of three");

        assert_eq!(error.code(), ParseErrorCode::TooLong);
        assert_eq!(error.field(), Some("name"));
        assert_eq!(error.parameter("max"), Some("3"));
        assert_eq!(error.parameter("actual"), Some("4"));
    }

    #[test]
    fn zero_length_limit_accepts_only_empty_input() {
        enforce_max_len("", 0, "value").unwrap();
        let error = enforce_max_len("x", 0, "value").unwrap_err();
        assert_eq!(error.parameter("max"), Some("0"));
        assert_eq!(error.parameter("actual"), Some("1"));
    }
}