ch-parsing 0.2.0

Typed input parsing with structured, locale-neutral errors
Documentation
//! Stable, locale-neutral parsing errors.

use std::borrow::Cow;
use std::fmt;

use thiserror::Error;

/// Machine-readable reason why an input could not be parsed.
///
/// Each variant maps to a stable code that applications can translate at their
/// presentation boundary. Adding a variant is not considered exhaustive, so
/// consumers should keep a fallback for codes introduced by newer releases.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ParseErrorCode {
    /// A required value was absent or empty after normalization.
    Required,
    /// The value does not conform to the expected syntax.
    InvalidFormat,
    /// The value is syntactically valid but is not accepted in this context.
    InvalidValue,
    /// The value exceeds the configured character limit.
    TooLong,
}

impl ParseErrorCode {
    /// Returns the stable, locale-neutral representation of this code.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Required => "parse.required",
            Self::InvalidFormat => "parse.invalid_format",
            Self::InvalidValue => "parse.invalid_value",
            Self::TooLong => "parse.too_long",
        }
    }
}

impl fmt::Display for ParseErrorCode {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// A named value that adds structured context to a [`ParseError`].
///
/// Parameter values intentionally remain strings so they can be forwarded to
/// serialization and localization layers without this crate depending on a
/// particular wire format.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ParseErrorParameter {
    name: Cow<'static, str>,
    value: Cow<'static, str>,
}

impl ParseErrorParameter {
    /// Returns the parameter name.
    #[must_use]
    pub fn name(&self) -> &str {
        self.name.as_ref()
    }

    /// Returns the parameter value.
    #[must_use]
    pub fn value(&self) -> &str {
        self.value.as_ref()
    }
}

/// Locale-neutral error raised when inbound data cannot be parsed.
///
/// `Display` exposes only the stable [`ParseErrorCode`]. User-visible copy is
/// deliberately owned by the consuming application.
#[derive(Clone, Debug, Error, PartialEq, Eq)]
#[error("{code}")]
pub struct ParseError {
    code: ParseErrorCode,
    field: Option<Cow<'static, str>>,
    parameters: Vec<ParseErrorParameter>,
}

impl ParseError {
    /// Creates a payload-level error without field context.
    #[must_use]
    pub const fn new(code: ParseErrorCode) -> Self {
        Self {
            code,
            field: None,
            parameters: Vec::new(),
        }
    }

    /// Creates an error tied to a named input field.
    #[must_use]
    pub fn for_field(field: impl Into<Cow<'static, str>>, code: ParseErrorCode) -> Self {
        Self {
            code,
            field: Some(field.into()),
            parameters: Vec::new(),
        }
    }

    /// Adds or replaces a structured parameter.
    ///
    /// Parameter names are unique. Calling this method again with the same
    /// name updates its value while retaining insertion order.
    #[must_use]
    pub fn with_parameter(
        mut self,
        name: impl Into<Cow<'static, str>>,
        value: impl Into<Cow<'static, str>>,
    ) -> Self {
        let name = name.into();
        let value = value.into();

        if let Some(parameter) = self
            .parameters
            .iter_mut()
            .find(|parameter| parameter.name == name)
        {
            parameter.value = value;
        } else {
            self.parameters.push(ParseErrorParameter { name, value });
        }

        self
    }

    /// Returns the machine-readable error code.
    #[must_use]
    pub const fn code(&self) -> ParseErrorCode {
        self.code
    }

    /// Returns the stable string form of [`Self::code`].
    #[must_use]
    pub const fn code_str(&self) -> &'static str {
        self.code.as_str()
    }

    /// Returns the input field associated with this error, when present.
    #[must_use]
    pub fn field(&self) -> Option<&str> {
        self.field.as_deref()
    }

    /// Returns the structured parameters in deterministic insertion order.
    #[must_use]
    pub fn parameters(&self) -> &[ParseErrorParameter] {
        self.parameters.as_slice()
    }

    /// Looks up a structured parameter by name.
    #[must_use]
    pub fn parameter(&self, name: &str) -> Option<&str> {
        self.parameters
            .iter()
            .find(|parameter| parameter.name == name)
            .map(ParseErrorParameter::value)
    }
}

impl From<ParseErrorCode> for ParseError {
    fn from(code: ParseErrorCode) -> Self {
        Self::new(code)
    }
}

/// Result type returned by parsing helpers.
pub type ParseResult<T> = Result<T, ParseError>;

#[cfg(test)]
mod tests {
    use super::{ParseError, ParseErrorCode};

    #[test]
    fn exposes_stable_machine_readable_context() {
        let error = ParseError::for_field("display_name", ParseErrorCode::TooLong)
            .with_parameter("max", "40")
            .with_parameter("actual", "41");

        assert_eq!(error.code(), ParseErrorCode::TooLong);
        assert_eq!(error.code_str(), "parse.too_long");
        assert_eq!(error.to_string(), "parse.too_long");
        assert_eq!(error.field(), Some("display_name"));
        assert_eq!(error.parameter("max"), Some("40"));
        assert_eq!(error.parameter("actual"), Some("41"));
        assert_eq!(error.parameter("missing"), None);
    }

    #[test]
    fn replaces_duplicate_parameters_without_reordering_them() {
        let error = ParseError::new(ParseErrorCode::InvalidValue)
            .with_parameter("expected", "first")
            .with_parameter("other", "unchanged")
            .with_parameter("expected", "replacement");

        assert_eq!(error.field(), None);
        assert_eq!(error.parameters().len(), 2);
        assert_eq!(error.parameters()[0].name(), "expected");
        assert_eq!(error.parameters()[0].value(), "replacement");
        assert_eq!(error.parameters()[1].name(), "other");
    }

    #[test]
    fn every_code_has_a_stable_namespace() {
        for code in [
            ParseErrorCode::Required,
            ParseErrorCode::InvalidFormat,
            ParseErrorCode::InvalidValue,
            ParseErrorCode::TooLong,
        ] {
            assert!(code.as_str().starts_with("parse."));
            assert!(!code.as_str().contains(char::is_whitespace));
        }
    }
}