chrono-node-rs 0.1.0

Behaviour-matched Rust port of chrono-node: natural-language date parsing, checked against chrono-node's own output
Documentation
//! upstream `locales/vi/parsers/VITimeUnitWithinFormatParser.ts`.

use std::sync::LazyLock;

use crate::common::word_boundary::{WithWordBoundary, WordBoundaryParser};
use crate::core::chrono::{Extracted, Parser};
use crate::core::components::ParsingComponents;
use crate::core::configuration::Flags;
use crate::core::context::ParsingContext;
use crate::core::regex::{JsRegex, RegexMatch};
use crate::locales::vi::constants::{parse_duration, TIME_UNITS_PATTERN};

pub const UPSTREAM: &str = "VITimeUnitWithinFormatParser";

/// `strictMode` is unused upstream: VI has no unit abbreviations, so both patterns are the same.
pub fn create(_flags: &Flags) -> Box<dyn Parser> {
    Box::new(WithWordBoundary::new(ViTimeUnitWithinFormatParser))
}

// trong 2 ngày  |  trong 3 tuần  |  trong vòng 1 tháng
static PATTERN: LazyLock<JsRegex> =
    LazyLock::new(|| JsRegex::new(&format!(r"(?:trong\s*(?:vòng\s*)?)({})(?=\W|$)", *TIME_UNITS_PATTERN), "i"));

struct ViTimeUnitWithinFormatParser;

impl WordBoundaryParser for ViTimeUnitWithinFormatParser {
    fn inner_pattern(&self, _context: &ParsingContext) -> JsRegex {
        PATTERN.clone()
    }

    fn inner_extract(&self, context: &ParsingContext, m: &mut RegexMatch) -> Extracted {
        // `if (!timeUnits) return null` never fires: a duration is always an object.
        let mut time_units = parse_duration(m.get(1).unwrap_or(""));
        Extracted::Components(ParsingComponents::create_relative_from_reference(
            context.reference,
            &mut time_units,
        ))
    }
}