Skip to main content

chrono_node/core/
context.rs

1//! upstream `ParsingContext` and `ParsingOption`.
2
3use super::components::{Component, ParsingComponents};
4use super::js_date::JsDate;
5use super::reference::{ReferenceInput, ReferenceWithTimezone};
6use super::result::ParsingResult;
7use super::timezone::TimezoneAbbrMap;
8
9/// upstream `ParsingOption` (without the `debug` handler).
10#[derive(Clone, Debug, Default, PartialEq)]
11pub struct ParsingOption {
12    /// `forwardDate`: prefer dates after the reference.
13    pub forward_date: bool,
14    /// `timezones`: abbreviation overrides.
15    pub timezones: TimezoneAbbrMap,
16}
17
18/// upstream `ParsingContext`.
19#[derive(Clone, Debug)]
20pub struct ParsingContext {
21    pub text: String,
22    pub option: ParsingOption,
23    pub reference: ReferenceWithTimezone,
24    /// Deprecated upstream alias of `reference.instant`; parsers still read it.
25    pub ref_date: JsDate,
26}
27
28impl ParsingContext {
29    /// `new ParsingContext(text, refDate, option)`. `now` stands in for `new Date()`.
30    pub fn new(text: &str, reference: &ReferenceInput, option: ParsingOption, now: JsDate) -> ParsingContext {
31        let reference = ReferenceWithTimezone::from_input(reference, &option.timezones, now);
32        ParsingContext {
33            text: text.to_string(),
34            option,
35            ref_date: reference.instant,
36            reference,
37        }
38    }
39
40    /// `createParsingComponents(components)`.
41    pub fn create_parsing_components(&self, known: &[(Component, i64)]) -> ParsingComponents {
42        ParsingComponents::new(self.reference, known)
43    }
44
45    /// `createParsingResult(index, text, start?, end?)`.
46    pub fn create_parsing_result(
47        &self,
48        index: usize,
49        text: impl Into<String>,
50        start: Option<ParsingComponents>,
51        end: Option<ParsingComponents>,
52    ) -> ParsingResult {
53        ParsingResult::new(self.reference, index, text, start, end)
54    }
55
56    /// `createParsingResult(index, endIndex, ...)`: the text is `context.text.substring(index, endIndex)`.
57    pub fn create_parsing_result_to(
58        &self,
59        index: usize,
60        end_index: usize,
61        start: Option<ParsingComponents>,
62        end: Option<ParsingComponents>,
63    ) -> ParsingResult {
64        let text = self.text.get(index..end_index).unwrap_or("").to_string();
65        ParsingResult::new(self.reference, index, text, start, end)
66    }
67}