laratext 0.1.0

Laratext for Laravel Rust: translation keys with their source text, and auto-translation with OpenAI, Claude, Google Translate or Translatorio.
Documentation
//! Laravel's `MessageSelector`: which form of `One item|You have :count items` a number takes.
//!
//! It follows the current Laravel 13, which reads a negative count by its absolute value and
//! allows spaces inside `{ 0 }` and `[ 1,* ]`. `resources/js/index.js` makes the same choice in
//! the browser, and the tests compare both.

use crate::plural::plural_index;
use crate::support::is_numeric;

fn is_space(character: char) -> bool {
    matches!(character, ' ' | '\t' | '\n' | '\x0b' | '\x0c' | '\r')
}

/// Select the form of a line for a number, as `MessageSelector::choose` does.
///
/// The forms are separated by `|`. A form may start with a condition, `{0}`, `{1}`, `[1,19]` or
/// `[20,*]`, which wins over the language's plural rule when the number matches it.
pub fn choose(line: &str, number: f64, locale: &str) -> String {
    let segments: Vec<&str> = line.split('|').collect();

    for part in &segments {
        if let Some(value) = extract(part, number) {
            return php_trim(value).to_owned();
        }
    }

    let stripped: Vec<&str> = segments
        .iter()
        .map(|part| condition(part).map_or(*part, |(_, rest)| rest))
        .collect();

    let index = plural_index(locale, number);

    if stripped.len() == 1 || index >= stripped.len() {
        return stripped[0].to_owned();
    }

    stripped[index].to_owned()
}

/// The condition at the start of a form and what follows it: `^\s*[{[]\s*([-?\d|*,.*]*)\s*[}\]]`.
fn condition(part: &str) -> Option<(&str, &str)> {
    let rest = part.trim_start_matches(is_space);
    let rest = rest.strip_prefix(['{', '['])?;
    let rest = rest.trim_start_matches(is_space);

    let end = rest
        .find(|c: char| !(c.is_ascii_digit() || matches!(c, '-' | '?' | '|' | '*' | ',' | '.')))
        .unwrap_or(rest.len());

    let (condition, rest) = rest.split_at(end);
    let rest = rest.trim_start_matches(is_space);
    let rest = rest.strip_prefix(['}', ']'])?;

    Some((condition, rest))
}

fn extract(part: &str, number: f64) -> Option<&str> {
    let (condition, value) = condition(part)?;

    if let Some((from, to)) = condition.split_once(',') {
        // The upper bound is open with `*`, the lower one too, and otherwise it is a range.
        let matches = (to == "*" && compare(number, from) >= 0)
            || (from == "*" && compare(number, to) <= 0)
            || (compare(number, from) >= 0 && compare(number, to) <= 0);

        if matches {
            return Some(value);
        }
    }

    (compare(number, condition) == 0).then_some(value)
}

/// PHP 8's comparison of a number with a string: numerically when the string is numeric,
/// otherwise as strings.
fn compare(number: f64, string: &str) -> i32 {
    if is_numeric(string) {
        let other: f64 = string.trim_matches(is_space).parse().unwrap_or(f64::NAN);

        return match number.partial_cmp(&other) {
            Some(std::cmp::Ordering::Less) => -1,
            Some(std::cmp::Ordering::Greater) => 1,
            _ => 0,
        };
    }

    match number_to_string(number).as_str().cmp(string) {
        std::cmp::Ordering::Less => -1,
        std::cmp::Ordering::Equal => 0,
        std::cmp::Ordering::Greater => 1,
    }
}

fn number_to_string(number: f64) -> String {
    if number.fract() == 0.0 && number.abs() < 1e15 {
        format!("{}", number as i64)
    } else {
        number.to_string()
    }
}

fn php_trim(value: &str) -> &str {
    value.trim_matches(|c| matches!(c, ' ' | '\t' | '\n' | '\r' | '\0' | '\x0b'))
}

#[cfg(test)]
mod tests {
    use super::choose;

    #[test]
    fn a_line_without_conditions_follows_the_plural_rule_of_the_language() {
        assert_eq!(choose("a|b", 1.0, "en"), "a");
        assert_eq!(choose("a|b", 2.0, "en"), "b");
        assert_eq!(choose("яблоко|яблока|яблок", 3.0, "ru"), "яблока");
        assert_eq!(choose("a|b", 0.0, "fr"), "a");
    }

    #[test]
    fn conditions_win_over_the_rule() {
        let line = "{0} none|[1,19] some|[20,*] many";

        assert_eq!(choose(line, 0.0, "en"), "none");
        assert_eq!(choose(line, 7.0, "en"), "some");
        assert_eq!(choose(line, 50.0, "en"), "many");
    }

    #[test]
    fn a_negative_count_is_read_by_its_absolute_value() {
        assert_eq!(choose("a|b", -1.0, "en"), "a");
    }

    #[test]
    fn spaces_are_allowed_inside_a_condition() {
        assert_eq!(choose(" { 0 } none|some", 0.0, "en"), "none");
    }
}