Skip to main content

chrono_node/core/
result.rs

1//! upstream `ParsingResult`.
2
3use super::components::ParsingComponents;
4use super::js_date::JsDate;
5use super::reference::ReferenceWithTimezone;
6
7/// upstream `ParsingResult`. `index` is a **byte** offset into the parsed text; JSON output
8/// converts it to UTF-16 units to match JavaScript.
9#[derive(Clone, Debug, PartialEq)]
10pub struct ParsingResult {
11    pub reference: ReferenceWithTimezone,
12    pub ref_date: JsDate,
13    pub index: usize,
14    pub text: String,
15    pub start: ParsingComponents,
16    pub end: Option<ParsingComponents>,
17}
18
19impl ParsingResult {
20    /// upstream `clone()`: start and end are cloned the upstream way, without their tags
21    /// ([`ParsingComponents::js_clone`]).
22    pub fn js_clone(&self) -> ParsingResult {
23        ParsingResult {
24            reference: self.reference,
25            ref_date: self.ref_date,
26            index: self.index,
27            text: self.text.clone(),
28            start: self.start.js_clone(),
29            end: self.end.as_ref().map(ParsingComponents::js_clone),
30        }
31    }
32
33    /// `new ParsingResult(reference, index, text, start?, end?)`.
34    pub fn new(
35        reference: ReferenceWithTimezone,
36        index: usize,
37        text: impl Into<String>,
38        start: Option<ParsingComponents>,
39        end: Option<ParsingComponents>,
40    ) -> ParsingResult {
41        ParsingResult {
42            reference,
43            ref_date: reference.instant,
44            index,
45            text: text.into(),
46            start: start.unwrap_or_else(|| ParsingComponents::new(reference, &[])),
47            end,
48        }
49    }
50
51    /// `date()`.
52    pub fn date(&self) -> JsDate {
53        self.start.date()
54    }
55
56    pub fn add_tag(&mut self, tag: &str) -> &mut Self {
57        self.start.add_tag(tag);
58        if let Some(end) = self.end.as_mut() {
59            end.add_tag(tag);
60        }
61        self
62    }
63
64    pub fn add_tags<'a>(&mut self, tags: impl IntoIterator<Item = &'a str> + Clone) -> &mut Self {
65        self.start.add_tags(tags.clone());
66        if let Some(end) = self.end.as_mut() {
67            end.add_tags(tags);
68        }
69        self
70    }
71
72    /// `tags()`: start's tags, then end's, without duplicates.
73    pub fn tags(&self) -> Vec<String> {
74        let mut tags: Vec<String> = self.start.tags().to_vec();
75        if let Some(end) = &self.end {
76            for t in end.tags() {
77                if !tags.contains(t) {
78                    tags.push(t.clone());
79                }
80            }
81        }
82        tags
83    }
84}