Skip to main content

ass_core/utils/
fields.rs

1//! Field value parsing, validation, and normalization helpers.
2//!
3//! Provides numeric parsing with ASS-friendly error messages along with
4//! whitespace normalization and name validation for ASS field values.
5
6#[cfg(not(feature = "std"))]
7use alloc::format;
8use core::fmt;
9#[cfg(feature = "std")]
10use std::format;
11
12use super::CoreError;
13
14/// Parse numeric value from ASS field with validation
15///
16/// Handles integer and floating-point parsing with ASS-specific validation.
17/// Provides better error messages than standard parsing.
18///
19/// # Errors
20///
21/// Returns an error if the string cannot be parsed as the target numeric type.
22pub fn parse_numeric<T>(value_str: &str) -> Result<T, CoreError>
23where
24    T: core::str::FromStr,
25    T::Err: fmt::Display,
26{
27    value_str
28        .trim()
29        .parse()
30        .map_err(|e| CoreError::InvalidNumeric(format!("Failed to parse '{value_str}': {e}")))
31}
32
33/// Trim and normalize whitespace in ASS field values
34///
35/// ASS fields may have inconsistent whitespace that should be normalized
36/// while preserving intentional spacing in text content.
37#[must_use]
38pub fn normalize_field_value(value: &str) -> &str {
39    value.trim()
40}
41
42/// Check if string contains only valid ASS characters
43///
44/// ASS has restrictions on certain characters in names and style definitions.
45#[must_use]
46pub fn validate_ass_name(name: &str) -> bool {
47    !name.is_empty()
48        && !name.contains(',') // Comma is field separator
49        && !name.contains(':') // Colon is key-value separator
50        && !name.contains('{') // Override block start
51        && !name.contains('}') // Override block end
52        && name.chars().all(|c| !c.is_control() || c == '\t')
53}