Debian Codegraph @

debian/rust-vendor/parse_datetime/src/items/offset.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 an offset item.
5 //!
6 //! From the GNU docs:
7 //!
8 //! > A “time zone item” specifies an international time zone, indicated by a
9 //! > small set of letters, e.g., ‘UTC’ or ‘Z’ for Coordinated Universal Time.
10 //! > Any included periods are ignored. By following a non-daylight-saving
11 //! > time zone by the string ‘DST’ in a separate word (that is, separated by
12 //! > some white space), the corresponding daylight saving time zone may be
13 //! > specified. Alternatively, a non-daylight-saving time zone can be
14 //! > followed by a time zone correction, to add the two values. This is
15 //! > normally done only for ‘UTC’; for example, ‘UTC+05:30’ is equivalent to
16 //! > ‘+05:30’.
17 //! >
18 //! > Time zone items other than ‘UTC’ and ‘Z’ are obsolescent and are not
19 //! > recommended, because they are ambiguous; for example, ‘EST’ has a
20 //! > different meaning in Australia than in the United States, and ‘A’ has
21 //! > different meaning as a military time zone than as an obsolete RFC 822
22 //! > time zone. Instead, it's better to use unambiguous numeric time zone
23 //! > corrections like ‘-0500’, as described in the previous section.
24 //! >
25 //! > If neither a time zone item nor a time zone correction is supplied,
26 //! > timestamps are interpreted using the rules of the default time zone.
27
28 use std::fmt::Display;
29
30 use winnow::{
31 combinator::{alt, peek},
32 error::{ContextError, ErrMode},
33 stream::{AsChar, Stream},
34 token::take_while,
35 ModalResult, Parser,
36 };
37
38 use super::{
39 primitive::{colon, ctx_err, dec_uint, dec_uint_str, plus_or_minus, s},
40 relative,
41 };
42
43 /// Represents a time zone offset from UTC.
44 ///
45 /// This struct is used to represent a time zone offset in hours and minutes,
46 /// with a boolean indicating whether the offset is negative (i.e., west of
47 /// UTC).
48 #[derive(PartialEq, Debug, Clone, Default)]
49 pub(super) struct Offset {
50 negative: bool,
51 hours: u8,
52 minutes: u8,
53 }
54
55 impl Offset {
56 /// Merge two timezone offsets.
57 ///
58 /// Note: when parsing an offset from a string (e.g., "+08:00"), the hours
59 /// and minutes are validated to ensure they fall within valid bounds. In
60 /// contrast, merging two offsets does not perform such validation. This
61 /// behavior is intentional to match GNU date.
62 fn merge(self, offset: Offset) -> Offset {
63 fn combine(a: u16, neg_a: bool, b: u16, neg_b: bool) -> (u16, bool) {
64 if neg_a == neg_b {
65 (a + b, neg_a)
66 } else if a > b {
67 (a - b, neg_a)
68 } else {
69 (b - a, neg_b)
70 }
71 }
72 let (total_minutes, negative) = combine(
73 (self.hours as u16) * 60 + (self.minutes as u16),
74 self.negative,
75 (offset.hours as u16) * 60 + (offset.minutes as u16),
76 offset.negative,
77 );
78 let hours = (total_minutes / 60) as u8;
79 let minutes = (total_minutes % 60) as u8;
80
81 Offset {
82 negative,
83 hours,
84 minutes,
85 }
86 }
87
88 /// Normalize the offset so that the hour field is within the accepted range.
89 ///
90 /// - If the hour field is less than 24, or exactly 24 with a zero minute,
91 /// the offset is already normalized, and the function returns the offset
92 /// itself along with a zero hour adjustment.
93 /// - Otherwise, the hour field is reduced to 23 while preserving the minute
94 /// field, and the function returns the normalized offset along with the
95 /// hour adjustment needed to reach the original offset.
96 pub(super) fn normalize(self) -> (Offset, i8) {
97 if self.hours < 24 || (self.hours == 24 && self.minutes == 0) {
98 return (self, 0);
99 }
100
101 let hour_adjustment = (self.hours as i8 - 23) * if self.negative { 1 } else { -1 };
102 (
103 Offset {
104 negative: self.negative,
105 hours: 23,
106 minutes: self.minutes,
107 },
108 hour_adjustment,
109 )
110 }
111
112 pub(super) fn total_seconds(&self) -> i32 {
113 let secs = (self.hours as i32) * 3600 + (self.minutes as i32) * 60;
114 if self.negative {
115 -secs
116 } else {
117 secs
118 }
119 }
120 }
121
122 impl TryFrom<(bool, u8, u8)> for Offset {
123 type Error = &'static str;
124
125 fn try_from((negative, hours, minutes): (bool, u8, u8)) -> Result<Self, Self::Error> {
126 if hours > 24 {
127 return Err("timezone hour must be between 0 and 24");
128 }
129 if minutes > 60 || (hours == 24 && minutes != 0) {
130 return Err("timezone minute must be between 0 and 60");
131 }
132
133 Ok(Offset {
134 negative,
135 hours,
136 minutes,
137 })
138 }
139 }
140
141 impl TryFrom<&Offset> for jiff::tz::TimeZone {
142 type Error = &'static str;
143
144 fn try_from(
145 Offset {
146 negative,
147 hours,
148 minutes,
149 }: &Offset,
150 ) -> Result<Self, Self::Error> {
151 let secs = (*hours as i32) * 3600 + (*minutes as i32) * 60;
152 let secs = if *negative { -secs } else { secs };
153
154 let offset = jiff::tz::Offset::from_seconds(secs).map_err(|_| "offset is invalid")?;
155 Ok(jiff::tz::TimeZone::fixed(offset))
156 }
157 }
158
159 impl Display for Offset {
160 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
161 write!(
162 fmt,
163 "{}{:02}:{:02}",
164 if self.negative { "-" } else { "+" },
165 self.hours,
166 self.minutes
167 )
168 }
169 }
170
171 /// Timezone abbreviations are assumed to be no longer than 6 characters.
172 const MAX_TZ_SIZE: usize = 6;
173
174 pub(super) fn parse(input: &mut &str) -> ModalResult<Offset> {
175 timezone_name_offset.parse_next(input)
176 }
177
178 /// Parse the military timezone letter `j`.
179 ///
180 /// Every other military letter denotes a fixed offset from UTC, but GNU `date`
181 /// defines `j` as local time, which cannot be expressed as an [`Offset`] at
182 /// all. It is therefore reported to the builder as its own item.
183 ///
184 /// The whole alphabetic word is consumed before comparing, so `jan` is left to
185 /// the date parser rather than being read as `j` followed by `an`, and `jj` is
186 /// rejected rather than matching a `j` prefix.
187 pub(super) fn parse_local(input: &mut &str) -> ModalResult<()> {
188 s(take_while(1..=MAX_TZ_SIZE, AsChar::is_alpha))
189 .verify(|word: &str| word.eq_ignore_ascii_case("j"))
190 .void()
191 .parse_next(input)
192 }
193
194 /// Parse a timezone starting with `+` or `-`.
195 pub(super) fn timezone_offset(input: &mut &str) -> ModalResult<Offset> {
196 // Strings like "+8 years" are ambiguous, they can either be parsed as a
197 // timezone offset "+8" and a relative time "years", or just a relative time
198 // "+8 years". GNU date parses them the second way, so we do the same here.
199 //
200 // Return early if the input can be parsed as a relative time.
201 if peek(relative::parse).parse_next(input).is_ok() {
202 return Err(ErrMode::Backtrack(ContextError::new()));
203 }
204
205 alt((timezone_offset_colon, timezone_offset_colonless)).parse_next(input)
206 }
207
208 /// Parse a timezone by name, with an optional numeric offset appended.
209 fn timezone_name_offset(input: &mut &str) -> ModalResult<Offset> {
210 let nextword = s(take_while(1..=MAX_TZ_SIZE, AsChar::is_alpha)).parse_next(input)?;
211 let tz = timezone_name_to_offset(nextword)?;
212
213 // Strings like "UTC +8 years" are ambiguous, they can either be parsed as
214 // "UTC+8" and "years", or "UTC" and "+8 years". GNU date parses them the
215 // second way, so we do the same here.
216 //
217 // Only process if the input cannot be parsed as a relative time.
218 if peek(relative::parse).parse_next(input).is_err() {
219 let start = input.checkpoint();
220 if let Ok(other_tz) = timezone_offset.parse_next(input) {
221 let new_tz = tz.merge(other_tz);
222
223 return Ok(new_tz);
224 };
225 input.reset(&start);
226 }
227
228 Ok(tz)
229 }
230
231 /// Parse a timezone offset with a colon separating hours and minutes, e.g.,
232 /// `+08:00`, `+8:00`, `+8:0`.
233 fn timezone_offset_colon(input: &mut &str) -> ModalResult<Offset> {
234 (plus_or_minus, s(dec_uint), s(colon), s(dec_uint))
235 .parse_next(input)
236 .and_then(|(sign, hours, _, minutes)| {
237 (sign == '-', hours, minutes)
238 .try_into()
239 .map_err(|e| ErrMode::Cut(ctx_err(e)))
240 })
241 }
242
243 /// Parse a timezone offset without colon, e.g., `+0800`, `+800`, `+08`, `+8`.
244 fn timezone_offset_colonless(input: &mut &str) -> ModalResult<Offset> {
245 (plus_or_minus, s(dec_uint_str))
246 .verify_map(|(sign, s)| {
247 // GNU date accepts numeric offset strings with leading zeroes. For
248 // example, `+000000110` is valid. In such cases, the string is
249 // truncated to the last four characters. Thus, `+000000110` becomes
250 // `+0110` (note that one leading zero is kept).
251 let s = if s.len() > 4 && s.trim_start_matches('0').len() <= 4 {
252 &s[s.len() - 4..]
253 } else {
254 s
255 };
256
257 // Hour and minute values are dependent on the length of the string.
258 // For example:
259 //
260 // - "5" -> 05:00
261 // - "05" -> 05:00
262 // - "530" -> 05:30 (the minute is the last two characters here)
263 // - "0530"-> 05:30
264 // - "0000530" -> 05:30
265 let (h_str, m_str) = match s.len() {
266 1 | 2 => (s, "0"),
267 3 => s.split_at(1),
268 4 => s.split_at(2),
269 _ => return None,
270 };
271
272 let hours = h_str.parse::<u8>().ok()?;
273 let minutes = m_str.parse::<u8>().ok()?;
274 Some((sign, hours, minutes))
275 })
276 .parse_next(input)
277 .and_then(|(sign, hours, minutes)| {
278 (sign == '-', hours, minutes)
279 .try_into()
280 .map_err(|e| ErrMode::Cut(ctx_err(e)))
281 })
282 }
283
284 /// Named timezone list.
285 ///
286 /// The full list of timezones can be extracted from
287 /// https://www.timeanddate.com/time/zones/. GNU date only supports a subset of
288 /// these. We support the same subset as GNU date.
289 fn timezone_name_to_offset(input: &str) -> ModalResult<Offset> {
290 let mut offset_str = match input {
291 "z" => Ok("+0"),
292 "y" => Ok("-12"),
293 "x" => Ok("-11"),
294 "wet" => Ok("+0"),
295 "west" => Ok("+1"),
296 "wat" => Ok("+1"),
297 "w" => Ok("-10"),
298 "v" => Ok("-9"),
299 "utc" => Ok("+0"),
300 "ut" => Ok("+0"),
301 "u" => Ok("-8"),
302 "t" => Ok("-7"),
303 "sst" => Ok("-11"),
304 "sgt" => Ok("+8"),
305 "sast" => Ok("+2"),
306 "s" => Ok("-6"),
307 "r" => Ok("-5"),
308 "q" => Ok("-4"),
309 "pst" => Ok("-8"),
310 "pdt" => Ok("-7"),
311 "p" => Ok("-3"),
312 "o" => Ok("-2"),
313 "nzst" => Ok("+12"),
314 "nzdt" => Ok("+13"),
315 "nst" => Ok("-3:30"),
316 "ndt" => Ok("-2:30"),
317 "n" => Ok("-1"),
318 "mst" => Ok("-7"),
319 "msk" => Ok("+3"),
320 "msd" => Ok("+4"),
321 "mez" => Ok("+1"),
322 "mesz" => Ok("+2"),
323 "mest" => Ok("+2"),
324 "mdt" => Ok("-6"),
325 "m" => Ok("+12"),
326 "l" => Ok("+11"),
327 "kst" => Ok("+9"),
328 "k" => Ok("+10"),
329 "jst" => Ok("+9"),
330 "ist" => Ok("+5:30"),
331 "i" => Ok("+9"),
332 "hst" => Ok("-10"),
333 "h" => Ok("+8"),
334 "gst" => Ok("+4"),
335 "gmt" => Ok("+0"),
336 "g" => Ok("+7"),
337 "f" => Ok("+6"),
338 "est" => Ok("-5"),
339 "eet" => Ok("+2"),
340 "eest" => Ok("+3"),
341 "edt" => Ok("-4"),
342 "eat" => Ok("+3"),
343 "e" => Ok("+5"),
344 "d" => Ok("+4"),
345 "cst" => Ok("-6"),
346 "clt" => Ok("-4"),
347 "clst" => Ok("-3"),
348 "cet" => Ok("+1"),
349 "cest" => Ok("+2"),
350 "cdt" => Ok("-5"),
351 "cat" => Ok("+2"),
352 "c" => Ok("+3"),
353 "bst" => Ok("+6"),
354 "brt" => Ok("-3"),
355 "brst" => Ok("-2"),
356 "b" => Ok("+2"),
357 "ast" => Ok("-3"),
358 "art" => Ok("-3"),
359 "akst" => Ok("-9"),
360 "akdt" => Ok("-8"),
361 "adt" => Ok("+4"),
362 "a" => Ok("+1"),
363 _ => Err(ErrMode::Backtrack(ContextError::new())),
364 }?;
365
366 timezone_offset(&mut offset_str)
367 }
368
369 #[cfg(test)]
370 mod tests {
371 use super::*;
372
373 fn off(negative: bool, hours: u8, minutes: u8) -> Offset {
374 Offset {
375 negative,
376 hours,
377 minutes,
378 }
379 }
380
381 #[test]
382 fn timezone_offset_with_colon() {
383 for (input, expected) in [
384 ("+00:00", off(false, 0, 0)), // UTC
385 ("-00:00", off(true, 0, 0)), // UTC
386 ("+01:00", off(false, 1, 0)), // positive offset
387 ("-06:00", off(true, 6, 0)), // negative offset
388 ("+05:30", off(false, 5, 30)), // positive offset with non-zero minutes
389 ("-03:30", off(true, 3, 30)), // negative offset with non-zero minutes
390 ("- 06:00", off(true, 6, 0)), // space after sign
391 ("- 06 : 00", off(true, 6, 0)), // space around colon
392 ("+5:3", off(false, 5, 3)), // single-digit hours and single-digit minutes
393 ("+5:03", off(false, 5, 3)), // single-digit hours
394 ("+05:3", off(false, 5, 3)), // single-digit minutes
395 ("+00005:00030", off(false, 5, 30)), // leading zeroes in hours and minutes
396 ("+00:00abc", off(false, 0, 0)), // space separator can be ignored if immediately followed by alphas (GNU date behavior)
397 ] {
398 let mut s = input;
399 assert_eq!(timezone_offset(&mut s).unwrap(), expected, "{input}");
400 }
401
402 for input in [
403 "+25:00", // invalid: hours > 24
404 "-23:61", // invalid: minutes > 60
405 "+24:01", // invalid: minutes > 0 when hours == 24
406 ] {
407 let mut s = input;
408 assert!(timezone_offset(&mut s).is_err(), "{input}");
409 }
410 }
411
412 #[test]
413 fn timezone_offset_without_colon() {
414 for (input, expected) in [
415 ("+0000", off(false, 0, 0)), // UTC
416 ("-0000", off(true, 0, 0)), // UTC
417 ("+0100", off(false, 1, 0)), // positive offset
418 ("-0600", off(true, 6, 0)), // negative offset
419 ("+0530", off(false, 5, 30)), // positive offset with non-zero minutes
420 ("-0330", off(true, 3, 30)), // negative offset with non-zero minutes
421 ("- 0330", off(true, 3, 30)), // space after sign
422 ("+530", off(false, 5, 30)), // single-digit hours
423 ("+05", off(false, 5, 0)), // double-digit hours and no minutes
424 ("+5", off(false, 5, 0)), // single-digit hours and no minutes
425 ("+00000530", off(false, 5, 30)), // leading zeroes
426 ("+0000abc", off(false, 0, 0)), // space separator can be ignored if immediately followed by alphas (GNU date behavior)
427 ] {
428 let mut s = input;
429 assert_eq!(timezone_offset(&mut s).unwrap(), expected, "{input}");
430 }
431
432 for input in [
433 "+2500", // invalid: hours > 24
434 "-2361", // invalid: minutes > 60
435 "+2401", // invalid: minutes > 0 when hours == 24
436 "+23 days", // invalid: ambiguous with relative time parsing
437 ] {
438 let mut s = input;
439 assert!(timezone_offset(&mut s).is_err(), "{input}");
440 }
441 }
442
443 #[test]
444 fn timezone_name_without_offset() {
445 for (input, expected) in [
446 ("utc", off(false, 0, 0)), // UTC
447 ("ut", off(false, 0, 0)), // Universal Time = UTC (issue #280)
448 ("gmt", off(false, 0, 0)), // UTC
449 ("z", off(false, 0, 0)), // UTC
450 ("west", off(false, 1, 0)), // positive offset
451 ("cst", off(true, 6, 0)), // negative offset
452 ("ist", off(false, 5, 30)), // positive offset with non-zero minutes
453 ("nst", off(true, 3, 30)), // negative offset with non-zero minutes
454 // Accepted by GNU date but previously missing here, which made
455 // `date -d "2024-01-15 12:00 MEZ"` fail (uutils/coreutils#13865).
456 ("mez", off(false, 1, 0)),
457 ("mesz", off(false, 2, 0)),
458 ("mest", off(false, 2, 0)),
459 ("kst", off(false, 9, 0)),
460 ("z123", off(false, 0, 0)), // space separator can be ignored if immediately followed by digits (GNU date behavior)
461 ] {
462 let mut s = input;
463 assert_eq!(timezone_name_offset(&mut s).unwrap(), expected, "{input}");
464 }
465
466 for input in [
467 "abc", // invalid: non-existent timezone
468 "utcabc", // invalid: non-existent timezone
469 ] {
470 let mut s = input;
471 assert!(timezone_name_offset(&mut s).is_err(), "{input}");
472 }
473 }
474
475 #[test]
476 fn timezone_name_with_offset() {
477 for (input, expected) in [
478 ("utc+5:30", off(false, 5, 30)), // UTC with possitive offset
479 ("utc-5:30", off(true, 5, 30)), // UTC with negative offset
480 ("utc +5:30", off(false, 5, 30)), // space after timezone name
481 ("utc + 5 : 30", off(false, 5, 30)), // spaces
482 ("a+5:30", off(false, 6, 30)), // merge two positive offsets (a=+1)
483 ("a-5:30", off(true, 4, 30)), // merge positive and negative offsets (a=+1)
484 ("n-5:30", off(true, 6, 30)), // merge two negative offsets (n=-1)
485 ("n+5:30", off(false, 4, 30)), // merge negative and positive offsets (n=-1)
486 ("m+24", off(false, 36, 0)), // maximum possible positive offset (m=+12)
487 ("y-24", off(true, 36, 0)), // maximum possible negative offset (y=-12)
488 ] {
489 let mut s = input;
490 assert_eq!(timezone_name_offset(&mut s).unwrap(), expected, "{input}");
491 }
492
493 for input in [
494 "abc+08:00", // invalid: non-existent timezone
495 "utc+25", // invalid: invalid offset
496 "utc+23 days", // invalid: ambiguous with relative time parsing
497 ] {
498 let mut s = input;
499 assert!(
500 timezone_name_offset(&mut s).is_err() || !s.is_empty(),
501 "{input}"
502 );
503 }
504 }
505
506 #[test]
507 fn total_seconds() {
508 assert_eq!(off(false, 0, 0).total_seconds(), 0);
509 assert_eq!(off(false, 5, 30).total_seconds(), 19_800);
510 assert_eq!(off(true, 5, 30).total_seconds(), -19_800);
511 assert_eq!(off(false, 24, 0).total_seconds(), 86_400);
512 }
513 /// `j` is the one military letter that is not an offset, so it is parsed
514 /// separately. The whole alphabetic word must be consumed before matching,
515 /// otherwise `jan` would be read as `j` followed by `an`.
516 #[test]
517 fn military_letter_j_local() {
518 for input in ["j", "J", " j"] {
519 let mut s = input;
520 assert!(
521 parse_local(&mut s).is_ok(),
522 "`{input}` should parse as local time"
523 );
524 assert!(s.is_empty(), "`{input}` should be fully consumed");
525 }
526
527 for input in ["jj", "jan", "jst", "z", "a", ""] {
528 let mut s = input;
529 assert!(
530 parse_local(&mut s).is_err(),
531 "`{input}` should not parse as local time"
532 );
533 }
534
535 // `j` is absent from the offset table, so the offset parser must not
536 // claim it.
537 let mut s = "j";
538 assert!(timezone_name_offset(&mut s).is_err());
539 }
540 }