Debian Codegraph @

debian/rust-vendor/parse_datetime/src/items/timezone.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 timezone item. The timezone item must be at the beginning of the
5 //! input string and in the `TZ="..."` format.
6 //!
7 //! From the GNU docs:
8 //!
9 //! > Normally, dates are interpreted using the rules of the current time zone,
10 //! > which in turn are specified by the ‘TZ’ environment variable, or by a
11 //! > system default if ‘TZ’ is not set. To specify a different set of default
12 //! > time zone rules that apply just to one date, start the date with a string
13 //! > of the form ‘TZ="RULE"’. The two quote characters (‘"’) must be present in
14 //! > the date, and any quotes or backslashes within RULE must be escaped by a
15 //! > backslash.
16
17 use jiff::tz::{Offset, TimeZone};
18 use winnow::{
19 combinator::{alt, delimited, opt, preceded, repeat},
20 stream::AsChar,
21 token::{one_of, take_while},
22 ModalResult, Parser,
23 };
24
25 use super::primitive::{dec_uint, plus_or_minus};
26
27 pub(super) fn parse(input: &mut &str) -> ModalResult<TimeZone> {
28 delimited("TZ=\"", preceded(opt(':'), alt((posix, iana))), '"').parse_next(input)
29 }
30
31 /// Parse a posix (proleptic) timezone string (e.g., "UTC7", "JST-9").
32 ///
33 /// TODO: This implementation is incomplete. It currently only parses the
34 /// `STDOFFSET` part of the format.
35 ///
36 /// From the GNU docs:
37 ///
38 /// > The proleptic format is:
39 /// >
40 /// > STDOFFSET[DST[OFFSET][,START[/TIME],END[/TIME]]]
41 /// >
42 /// > The STD string specifies the time zone abbreviation, which must be at
43 /// > least three bytes long. ...
44 /// >
45 /// > The OFFSET specifies the time value you must add to the local time to
46 /// > get a UTC value. It has syntax like:
47 /// >
48 /// > [+|-]HH[:MM[:SS]]
49 /// >
50 /// > This is positive if the local time zone is west of the Prime Meridian
51 /// > and negative if it is east; this is opposite from the usual convention
52 /// > that positive time zone offsets are east of the Prime Meridian. The
53 /// > hour HH must be between 0 and 24 and may be a single digit, and the
54 /// > minutes MM and seconds SS, if present, must be between 0 and 59.
55 fn posix(input: &mut &str) -> ModalResult<TimeZone> {
56 (take_while(3.., AsChar::is_alpha), posix_offset)
57 .verify_map(|(_, offset)| Offset::from_seconds(offset).ok().map(|o| o.to_time_zone()))
58 .parse_next(input)
59 }
60
61 /// Parse an IANA (geographical) timezone string (e.g., "Europe/Paris"). If the
62 /// string is not a valid IANA timezone name, the UTC timezone is returned.
63 ///
64 /// Compatibility notes:
65 ///
66 /// - The implementation uses `jiff::tz::TimeZone::get()` to resolve time zones.
67 /// Only canonical/aliased IANA names are accepted. Absolute file paths are
68 /// not supported.
69 /// - GNU `date` resolves time zones from the tzdata files under
70 /// `/usr/share/zoneinfo` (respecting `TZDIR`) and also accepts an absolute
71 /// path when the string starts with `/`.
72 ///
73 /// From the GNU docs:
74 ///
75 /// > If the format's CHARACTERS begin with ‘/’ it is an absolute file
76 /// > name; otherwise the library looks for the file
77 /// > ‘/usr/share/zoneinfo/CHARACTERS’. The ‘zoneinfo’ directory contains
78 /// > data files describing time zone rulesets in many different parts of the
79 /// > world. The names represent major cities, with subdirectories for
80 /// > geographical areas; for example, ‘America/New_York’, ‘Europe/London’,
81 /// > ‘Asia/Tokyo’. These data files are installed by the system
82 /// > administrator, who also sets ‘/etc/localtime’ to point to the data file
83 /// > for the local time zone ruleset.
84 fn iana(input: &mut &str) -> ModalResult<TimeZone> {
85 repeat(
86 0..,
87 alt((
88 preceded('\\', one_of(['\\', '"'])).map(|c: char| c.to_string()),
89 take_while(1, |c| c != '"' && c != '\\').map(str::to_string),
90 )),
91 )
92 .map(|parts: Vec<String>| parts.concat())
93 .map(|s| TimeZone::get(&s).unwrap_or(TimeZone::UTC))
94 .parse_next(input)
95 }
96
97 fn posix_offset(input: &mut &str) -> ModalResult<i32> {
98 let uint = dec_uint::<u32, _>;
99
100 (
101 opt(plus_or_minus),
102 alt((
103 (uint, preceded(':', uint), preceded(':', uint)).map(|(h, m, s)| (h, m, s)),
104 (uint, preceded(':', uint)).map(|(h, m)| (h, m, 0)),
105 uint.map(|h| (h, 0, 0)),
106 )),
107 )
108 .map(|(sign, (h, m, s))| {
109 // The sign is opposite from the usual convention:
110 // - Positive offsets are west of UTC.
111 // - Negative offsets are east of UTC.
112 let sign = if sign == Some('-') { 1 } else { -1 };
113
114 // - If hour is greater than 24, clamp it to 24.
115 // - If minute is greater than 59, clamp it to 59.
116 // - If second is greater than 59, clamp it to 59.
117 let h = h.min(24) as i32;
118 let m = m.min(59) as i32;
119 let s = s.min(59) as i32;
120
121 sign * (h * 3600 + m * 60 + s)
122 })
123 .parse_next(input)
124 }
125
126 #[cfg(test)]
127 mod tests {
128 use super::*;
129
130 #[test]
131 fn tz_rule() {
132 // empty string
133 for (input, expected) in [
134 (r#"TZ="""#, "UTC"),
135 (r#"TZ=":""#, "UTC"),
136 (r#"TZ=" ""#, "UTC"),
137 (r#"TZ=": ""#, "UTC"),
138 ] {
139 let mut s = input;
140 assert_eq!(
141 parse(&mut s).unwrap().iana_name(),
142 Some(expected),
143 "{input}"
144 );
145 }
146
147 // iana
148 for (input, expected) in [
149 (r#"TZ="Etc/Zulu""#, "Etc/Zulu"),
150 (r#"TZ=":Etc/Zulu""#, "Etc/Zulu"),
151 (r#"TZ="America/New_York""#, "America/New_York"),
152 (r#"TZ=":America/New_York""#, "America/New_York"),
153 (r#"TZ="Asia/Tokyo""#, "Asia/Tokyo"),
154 (r#"TZ=":Asia/Tokyo""#, "Asia/Tokyo"),
155 (r#"TZ="Unknown/Timezone""#, "UTC"),
156 (r#"TZ=":Unknown/Timezone""#, "UTC"),
157 ] {
158 let mut s = input;
159 assert_eq!(
160 parse(&mut s).unwrap().iana_name(),
161 Some(expected),
162 "{input}"
163 );
164 }
165
166 // posix
167 for (input, expected) in [
168 (r#"TZ="UTC0""#, 0),
169 (r#"TZ=":UTC0""#, 0),
170 (r#"TZ="UTC+5""#, -5 * 3600),
171 (r#"TZ=":UTC+5""#, -5 * 3600),
172 (r#"TZ="UTC-5""#, 5 * 3600),
173 (r#"TZ=":UTC-5""#, 5 * 3600),
174 (r#"TZ="UTC+5:20""#, -(5 * 3600 + 20 * 60)),
175 (r#"TZ=":UTC+5:20""#, -(5 * 3600 + 20 * 60)),
176 (r#"TZ="UTC-5:20""#, 5 * 3600 + 20 * 60),
177 (r#"TZ=":UTC-5:20""#, 5 * 3600 + 20 * 60),
178 (r#"TZ="UTC+5:20:15""#, -(5 * 3600 + 20 * 60 + 15)),
179 (r#"TZ=":UTC+5:20:15""#, -(5 * 3600 + 20 * 60 + 15)),
180 (r#"TZ="UTC-5:20:15""#, 5 * 3600 + 20 * 60 + 15),
181 (r#"TZ=":UTC-5:20:15""#, 5 * 3600 + 20 * 60 + 15),
182 ] {
183 let mut s = input;
184 assert_eq!(
185 parse(&mut s).unwrap().to_fixed_offset().unwrap().seconds(),
186 expected,
187 "{input}"
188 );
189 }
190
191 // invalid
192 for input in [
193 r#"UTC"#, // missing "TZ="
194 r#"tz="UTC""#, // lowercase "tz"
195 r#"TZ=UTC"#, // missing quotes
196 ] {
197 let mut s = input;
198 assert!(parse(&mut s).is_err(), "{input}");
199 }
200 }
201
202 #[test]
203 fn parse_iana() {
204 for (input, expected) in [
205 ("UTC", "UTC"), // utc timezone
206 ("Etc/Zulu", "Etc/Zulu"), // etc timezone
207 ("America/New_York", "America/New_York"), // named timezone
208 ("Asia/Tokyo", "Asia/Tokyo"), // named timezone
209 ("Unknown/Timezone", "UTC"), // unknown timezone
210 ] {
211 let mut s = input;
212 assert_eq!(iana(&mut s).unwrap().iana_name(), Some(expected), "{input}");
213 }
214 }
215
216 #[test]
217 fn parse_posix() {
218 let to_seconds = |input: &str| {
219 let mut s = input;
220 posix(&mut s).unwrap().to_fixed_offset().unwrap().seconds()
221 };
222
223 // hour
224 for (input, expected) in [
225 ("UTC0", 0),
226 ("UTC+0", 0),
227 ("UTC-0", 0),
228 ("UTC000", 0),
229 ("UTC+5", -5 * 3600),
230 ("UTC-5", 5 * 3600),
231 ("ABC0", 0),
232 ("ABC+5", -5 * 3600),
233 ("ABC-5", 5 * 3600),
234 ] {
235 assert_eq!(to_seconds(input), expected, "{input}");
236 }
237
238 // hour:minute
239 for (input, expected) in [
240 ("UTC0:0", 0),
241 ("UTC+0:0", 0),
242 ("UTC-0:0", 0),
243 ("UTC00:00", 0),
244 ("UTC+5:20", -(5 * 3600 + 20 * 60)),
245 ("UTC-5:20", 5 * 3600 + 20 * 60),
246 ("ABC0:0", 0),
247 ("ABC+5:20", -(5 * 3600 + 20 * 60)),
248 ("ABC-5:20", 5 * 3600 + 20 * 60),
249 ] {
250 assert_eq!(to_seconds(input), expected, "{input}");
251 }
252
253 // hour:minute:second
254 for (input, expected) in [
255 ("UTC0:0:0", 0),
256 ("UTC+0:0:0", 0),
257 ("UTC-0:0:0", 0),
258 ("UTC00:00:00", 0),
259 ("UTC+5:20:15", -(5 * 3600 + 20 * 60 + 15)),
260 ("UTC-5:20:15", 5 * 3600 + 20 * 60 + 15),
261 ("ABC0:0:0", 0),
262 ("ABC+5:20:15", -(5 * 3600 + 20 * 60 + 15)),
263 ("ABC-5:20:15", 5 * 3600 + 20 * 60 + 15),
264 ] {
265 assert_eq!(to_seconds(input), expected, "{input}");
266 }
267
268 // invalid
269 for input in [
270 "AB", // too short
271 "A1C", // not just letters
272 ] {
273 let mut s = input;
274 assert!(posix(&mut s).is_err(), "{input}");
275 }
276 }
277
278 #[test]
279 fn parse_posix_offset() {
280 // hour
281 for (input, expected) in [
282 ("0", 0), // zero hour
283 ("00", 0), // zero hour, two digits
284 ("000", 0), // zero hour, three digits
285 ("+0", 0), // zero hour, explicit plus
286 ("-0", 0), // zero hour, explicit minus
287 ("5", -5 * 3600), // positive hour
288 ("-5", 5 * 3600), // negative hour
289 ("005", -5 * 3600), // positive hour with leading zeros
290 ("-05", 5 * 3600), // negative hour with leading zeros
291 ("25", -24 * 3600), // hour > 24, clamps to 24
292 ("-25", 24 * 3600), // hour > 24, clamps to 24
293 ] {
294 let mut s = input;
295 assert_eq!(posix_offset(&mut s).unwrap(), expected, "{input}");
296 }
297
298 // hour:minute
299 for (input, expected) in [
300 ("0:0", 0), // zero hour and minute
301 ("00:00", 0), // zero hour and minute, two digits
302 ("000:000", 0), // zero hour and minute, three digits
303 ("+0:0", 0), // zero hour and minute, explicit plus
304 ("-0:0", 0), // zero hour and minute, explicit minus
305 ("5:20", -(5 * 3600 + 20 * 60)), // positive hour and minute
306 ("-5:20", 5 * 3600 + 20 * 60), // negative hour and minute
307 ("005:020", -(5 * 3600 + 20 * 60)), // positive hour and minute with leading zeros
308 ("-05:20", 5 * 3600 + 20 * 60), // negative hour and minute with leading zeros
309 ("25:20", -(24 * 3600 + 20 * 60)), // hour > 24, clamps to 24
310 ("-25:20", 24 * 3600 + 20 * 60), // hour > 24, clamps to 24
311 ("5:60", -(5 * 3600 + 59 * 60)), // minute > 59, clamps to 59
312 ("-5:60", 5 * 3600 + 59 * 60), // minute > 59, clamps to 59
313 ] {
314 let mut s = input;
315 assert_eq!(posix_offset(&mut s).unwrap(), expected, "{input}");
316 }
317
318 // hour:minute:second
319 for (input, expected) in [
320 ("0:0:0", 0), // zero hour, minute, and second
321 ("00:00:00", 0), // zero hour, minute, and second, two digits
322 ("000:000:000", 0), // zero hour, minute, and second, three digits
323 ("+0:0:0", 0), // zero hour, minute, and second, explicit plus
324 ("-0:0:0", 0), // zero hour, minute, and second, explicit minus
325 ("5:20:15", -(5 * 3600 + 20 * 60 + 15)), // positive hour, minute, and second
326 ("-5:20:15", 5 * 3600 + 20 * 60 + 15), // negative hour, minute, and second
327 ("005:020:015", -(5 * 3600 + 20 * 60 + 15)), // positive hour, minute, and second with leading zeros
328 ("-05:20:15", 5 * 3600 + 20 * 60 + 15), // negative hour, minute, and second with leading zeros
329 ("25:20:15", -(24 * 3600 + 20 * 60 + 15)), // hour > 24, clamps to 24
330 ("-25:20:15", 24 * 3600 + 20 * 60 + 15), // hour > 24, clamps to 24
331 ("5:60:15", -(5 * 3600 + 59 * 60 + 15)), // minute > 59, clamps to 59
332 ("-5:60:15", 5 * 3600 + 59 * 60 + 15), // minute > 59, clamps to 59
333 ("5:20:60", -(5 * 3600 + 20 * 60 + 59)), // second > 59, clamps to 59
334 ("-5:20:60", 5 * 3600 + 20 * 60 + 59), // second > 59, clamps to 59
335 ] {
336 let mut s = input;
337 assert_eq!(posix_offset(&mut s).unwrap(), expected, "{input}");
338 }
339 }
340 }