Debian Codegraph @

debian/rust-vendor/parse_datetime/src/items/relative.rs

raw
1 // For the full copyright and license information, please view the LICENSE
2 // file that was distributed with this source code.
3
4 //! Parse a relative datetime item
5 //!
6 //! The GNU docs state:
7 //!
8 //! > The unit of time displacement may be selected by the string ‘year’ or
9 //! > ‘month’ for moving by whole years or months. These are fuzzy units, as
10 //! > years and months are not all of equal duration. More precise units are
11 //! > ‘fortnight’ which is worth 14 days, ‘week’ worth 7 days, ‘day’ worth 24
12 //! > hours, ‘hour’ worth 60 minutes, ‘minute’ or ‘min’ worth 60 seconds, and
13 //! > ‘second’ or ‘sec’ worth one second. An ‘s’ suffix on these units is
14 //! > accepted and ignored.
15 //! >
16 //! > The unit of time may be preceded by a multiplier, given as an optionally
17 //! > signed number. Unsigned numbers are taken as positively signed. No number
18 //! > at all implies 1 for a multiplier. Following a relative item by the
19 //! > string ‘ago’ is equivalent to preceding the unit by a multiplier with
20 //! > value -1.
21 //! >
22 //! > The string ‘tomorrow’ is worth one day in the future (equivalent to
23 //! > ‘day’), the string ‘yesterday’ is worth one day in the past (equivalent
24 //! > to ‘day ago’).
25 //! >
26 //! > The strings ‘now’ or ‘today’ are relative items corresponding to
27 //! > zero-valued time displacement, these strings come from the fact a
28 //! > zero-valued time displacement represents the current time when not
29 //! > otherwise changed by previous items. They may be used to stress other
30 //! > items, like in ‘12:00 today’. The string ‘this’ also has the meaning of a
31 //! > zero-valued time displacement, but is preferred in date strings like
32 //! > ‘this thursday’.
33
34 use winnow::{
35 ascii::alpha1,
36 combinator::{alt, opt},
37 ModalResult, Parser,
38 };
39
40 use super::{epoch::sec_and_nsec, ordinal::ordinal, primitive::s};
41
42 #[derive(Clone, Copy, Debug, PartialEq)]
43 pub(crate) enum Relative {
44 Years(i32),
45 Months(i32),
46 Days(i32),
47 Hours(i32),
48 Minutes(i32),
49 Seconds(i64, u32),
50 }
51
52 impl TryFrom<Relative> for jiff::Span {
53 type Error = &'static str;
54
55 fn try_from(relative: Relative) -> Result<Self, Self::Error> {
56 match relative {
57 Relative::Years(years) => jiff::Span::new().try_years(years),
58 Relative::Months(months) => jiff::Span::new().try_months(months),
59 Relative::Days(days) => jiff::Span::new().try_days(days),
60 Relative::Hours(hours) => jiff::Span::new().try_hours(hours),
61 Relative::Minutes(minutes) => jiff::Span::new().try_minutes(minutes),
62 Relative::Seconds(seconds, nanoseconds) => jiff::Span::new()
63 .try_seconds(seconds)
64 .and_then(|span| span.try_nanoseconds(nanoseconds)),
65 }
66 .map_err(|_| "relative value is invalid")
67 }
68 }
69
70 pub(super) fn parse(input: &mut &str) -> ModalResult<Relative> {
71 alt((
72 s("tomorrow").value(Relative::Days(1)),
73 s("yesterday").value(Relative::Days(-1)),
74 // For "today" and "now", the unit is arbitrary
75 s("today").value(Relative::Days(0)),
76 s("now").value(Relative::Days(0)),
77 seconds,
78 displacement,
79 ))
80 .parse_next(input)
81 }
82
83 fn seconds(input: &mut &str) -> ModalResult<Relative> {
84 (
85 opt(alt((s('+').value(1), s('-').value(-1)))),
86 s(sec_and_nsec),
87 s(alpha1).verify(|s: &str| matches!(s, "seconds" | "second" | "sec" | "secs")),
88 ago,
89 )
90 .verify_map(|(sign, (sec, nsec), _, ago)| {
91 let sec = i64::try_from(sec).ok()?;
92 let sign = sign.unwrap_or(1) * if ago { -1 } else { 1 };
93 let (second, nanosecond) = match (sign, nsec) {
94 (-1, 0) => (-sec, 0),
95 // Truncate towards minus infinity.
96 (-1, _) => ((-sec).checked_sub(1)?, 1_000_000_000 - nsec),
97 _ => (sec, nsec),
98 };
99 Some(Relative::Seconds(second, nanosecond))
100 })
101 .parse_next(input)
102 }
103
104 fn displacement(input: &mut &str) -> ModalResult<Relative> {
105 (opt(ordinal), s(alpha1), ago)
106 .verify_map(|(n, unit, ago): (Option<i32>, &str, bool)| {
107 let multiplier = n.unwrap_or(1) * if ago { -1 } else { 1 };
108 Some(match unit.strip_suffix('s').unwrap_or(unit) {
109 "year" => Relative::Years(multiplier),
110 "month" => Relative::Months(multiplier),
111 "fortnight" => Relative::Days(multiplier.checked_mul(14)?),
112 "week" => Relative::Days(multiplier.checked_mul(7)?),
113 "day" => Relative::Days(multiplier),
114 "hour" => Relative::Hours(multiplier),
115 "minute" | "min" => Relative::Minutes(multiplier),
116 "second" | "sec" => Relative::Seconds(multiplier as i64, 0),
117 _ => return None,
118 })
119 })
120 .parse_next(input)
121 }
122
123 fn ago(input: &mut &str) -> ModalResult<bool> {
124 opt(s("ago")).map(|o| o.is_some()).parse_next(input)
125 }
126
127 #[cfg(test)]
128 mod tests {
129 use super::{parse, Relative};
130
131 #[test]
132 fn all() {
133 for (s, rel) in [
134 // Seconds
135 ("second", Relative::Seconds(1, 0)),
136 ("sec", Relative::Seconds(1, 0)),
137 ("seconds", Relative::Seconds(1, 0)),
138 ("secs", Relative::Seconds(1, 0)),
139 ("second ago", Relative::Seconds(-1, 0)),
140 ("3 seconds", Relative::Seconds(3, 0)),
141 ("+ 3 seconds", Relative::Seconds(3, 0)),
142 ("3.5 seconds", Relative::Seconds(3, 500_000_000)),
143 ("-3.5 seconds", Relative::Seconds(-4, 500_000_000)),
144 ("+3.5 seconds", Relative::Seconds(3, 500_000_000)),
145 ("+ 3.5 seconds", Relative::Seconds(3, 500_000_000)),
146 ("3.5 seconds ago", Relative::Seconds(-4, 500_000_000)),
147 ("- 3.5 seconds ago", Relative::Seconds(3, 500_000_000)),
148 // Minutes
149 ("minute", Relative::Minutes(1)),
150 ("minutes", Relative::Minutes(1)),
151 ("min", Relative::Minutes(1)),
152 ("mins", Relative::Minutes(1)),
153 ("10 minutes", Relative::Minutes(10)),
154 ("-10 minutes", Relative::Minutes(-10)),
155 ("- 10 minutes", Relative::Minutes(-10)),
156 ("10 minutes ago", Relative::Minutes(-10)),
157 ("-10 minutes ago", Relative::Minutes(10)),
158 ("- 10 minutes ago", Relative::Minutes(10)),
159 ("-10 minutes ago", Relative::Minutes(10)),
160 ("- 10 minutes ago", Relative::Minutes(10)),
161 // Hours
162 ("hour", Relative::Hours(1)),
163 ("hours", Relative::Hours(1)),
164 ("10 hours", Relative::Hours(10)),
165 ("+10 hours", Relative::Hours(10)),
166 ("+ 10 hours", Relative::Hours(10)),
167 ("-10 hours", Relative::Hours(-10)),
168 ("- 10 hours", Relative::Hours(-10)),
169 ("10 hours ago", Relative::Hours(-10)),
170 ("-10 hours ago", Relative::Hours(10)),
171 ("- 10 hours ago", Relative::Hours(10)),
172 // Days
173 ("day", Relative::Days(1)),
174 ("days", Relative::Days(1)),
175 ("10 days", Relative::Days(10)),
176 ("+10 days", Relative::Days(10)),
177 ("+ 10 days", Relative::Days(10)),
178 ("-10 days", Relative::Days(-10)),
179 ("- 10 days", Relative::Days(-10)),
180 ("10 days ago", Relative::Days(-10)),
181 ("-10 days ago", Relative::Days(10)),
182 ("- 10 days ago", Relative::Days(10)),
183 // Multiple days
184 ("fortnight", Relative::Days(14)),
185 ("fortnights", Relative::Days(14)),
186 ("2 fortnights ago", Relative::Days(-28)),
187 ("+2 fortnights ago", Relative::Days(-28)),
188 ("+ 2 fortnights ago", Relative::Days(-28)),
189 ("week", Relative::Days(7)),
190 ("weeks", Relative::Days(7)),
191 ("2 weeks ago", Relative::Days(-14)),
192 // Other
193 ("year", Relative::Years(1)),
194 ("years", Relative::Years(1)),
195 ("month", Relative::Months(1)),
196 ("months", Relative::Months(1)),
197 // Special
198 ("yesterday", Relative::Days(-1)),
199 ("tomorrow", Relative::Days(1)),
200 ("today", Relative::Days(0)),
201 ("now", Relative::Days(0)),
202 // This something
203 ("this day", Relative::Days(0)),
204 ("this second", Relative::Seconds(0, 0)),
205 ("this year", Relative::Years(0)),
206 // Weird stuff
207 ("next week ago", Relative::Days(-7)),
208 ("last week ago", Relative::Days(7)),
209 ("this week ago", Relative::Days(0)),
210 ] {
211 let mut t = s;
212 assert_eq!(parse(&mut t).ok(), Some(rel), "Failed string: {s}")
213 }
214 }
215 }