Debian Codegraph @

src/shared/tzif.rs

raw symbols SCIP
1 // auto-generated by: jiff-cli generate shared
2
3 use alloc::{string::String, vec};
4
5 use super::{
6 util::{
7 array_str::Abbreviation,
8 error::{err, Error},
9 escape::{Byte, Bytes},
10 itime::{IOffset, ITimestamp},
11 },
12 PosixTimeZone, TzifDateTime, TzifFixed, TzifIndicator, TzifLocalTimeType,
13 TzifOwned, TzifTransitionInfo, TzifTransitionKind, TzifTransitions,
14 TzifTransitionsOwned,
15 };
16
17 // These are Jiff min and max timestamp (in seconds) values.
18 //
19 // The TZif parser will clamp timestamps to this range. It's
20 // not ideal, but Jiff can't handle values outside of this range
21 // and completely refusing to use TZif data with pathological
22 // timestamps in typically irrelevant transitions is bad juju.
23 //
24 // Ref: https://github.com/BurntSushi/jiff/issues/163
25 // Ref: https://github.com/BurntSushi/jiff/pull/164
26 const TIMESTAMP_MIN: i64 = -377705023201;
27 const TIMESTAMP_MAX: i64 = 253402207200;
28
29 // Similarly for offsets, although in this case, if we find
30 // an offset outside of this range, we do actually error. This
31 // is because it could result in true incorrect datetimes for
32 // actual transitions.
33 //
34 // But our supported offset range is `-25:59:59..=+25:59:59`.
35 // There's no real time zone with offsets even close to those
36 // boundaries.
37 //
38 // If there is pathological data that we should ignore, then
39 // we should wait for a real bug report in order to determine
40 // the right way to ignore/clamp it.
41 const OFFSET_MIN: i32 = -93599;
42 const OFFSET_MAX: i32 = 93599;
43
44 // When fattening TZif data, this is the year to go up to.
45 //
46 // This year was chosen because it's what the "fat" TZif data generated
47 // by `zic` uses.
48 const FATTEN_UP_TO_YEAR: i16 = 2038;
49
50 // This is a "sanity" limit on the maximum number of transitions we'll
51 // add to TZif data when fattening them up.
52 //
53 // This is mostly just a defense-in-depth limit to avoid weird cases
54 // where a pathological POSIX time zone could be defined to create
55 // many transitions. It's not clear that this is actually possible,
56 // but I felt a little uneasy doing unbounded work that isn't linearly
57 // proportional to the input data. So, this limit is put into place for
58 // reasons of "good sense."
59 //
60 // For "normal" cases, there should be at most two transitions per
61 // year. So this limit permits 300/2=150 years of transition data.
62 // (Although we won't go above 2036. See above.)
63 const FATTEN_MAX_TRANSITIONS: usize = 300;
64
65 impl TzifOwned {
66 /// Parses the given data as a TZif formatted file.
67 ///
68 /// The name given is attached to the `Tzif` value returned, but is
69 /// otherwise not significant.
70 ///
71 /// If the given data is not recognized to be valid TZif, then an error is
72 /// returned.
73 ///
74 /// In general, callers may assume that it is safe to pass arbitrary or
75 /// even untrusted data to this function and count on it not panicking
76 /// or using resources that aren't limited to a small constant factor of
77 /// the size of the data itself. That is, callers can reliably limit the
78 /// resources used by limiting the size of the data given to this parse
79 /// function.
80 pub(crate) fn parse(
81 name: Option<String>,
82 bytes: &[u8],
83 ) -> Result<TzifOwned, Error> {
84 let original = bytes;
85 let name = name.into();
86 let (header32, rest) = Header::parse(4, bytes)
87 .map_err(|e| err!("failed to parse 32-bit header: {e}"))?;
88 let (mut tzif, rest) = if header32.version == 0 {
89 TzifOwned::parse32(name, header32, rest)?
90 } else {
91 TzifOwned::parse64(name, header32, rest)?
92 };
93 tzif.fatten();
94 // This should come after fattening, because fattening may add new
95 // transitions and we want to add civil datetimes to those.
96 tzif.add_civil_datetimes_to_transitions();
97 tzif.verify_posix_time_zone_consistency()?;
98 // Compute the checksum using the entire contents of the TZif data.
99 let tzif_raw_len = (rest.as_ptr() as usize)
100 .checked_sub(original.as_ptr() as usize)
101 .unwrap();
102 let tzif_raw_bytes = &original[..tzif_raw_len];
103 tzif.fixed.checksum = super::crc32::sum(tzif_raw_bytes);
104
105 // Shrink all of our allocs so we don't keep excess capacity around.
106 tzif.fixed.designations.shrink_to_fit();
107 tzif.types.shrink_to_fit();
108 tzif.transitions.timestamps.shrink_to_fit();
109 tzif.transitions.civil_starts.shrink_to_fit();
110 tzif.transitions.civil_ends.shrink_to_fit();
111 tzif.transitions.infos.shrink_to_fit();
112
113 Ok(tzif)
114 }
115
116 fn parse32<'b>(
117 name: Option<String>,
118 header32: Header,
119 bytes: &'b [u8],
120 ) -> Result<(TzifOwned, &'b [u8]), Error> {
121 let mut tzif = TzifOwned {
122 fixed: TzifFixed {
123 name,
124 version: header32.version,
125 // filled in later
126 checksum: 0,
127 designations: String::new(),
128 posix_tz: None,
129 },
130 types: vec![],
131 transitions: TzifTransitions {
132 timestamps: vec![],
133 civil_starts: vec![],
134 civil_ends: vec![],
135 infos: vec![],
136 },
137 };
138 let rest = tzif.parse_transitions(&header32, bytes)?;
139 let rest = tzif.parse_transition_types(&header32, rest)?;
140 let rest = tzif.parse_local_time_types(&header32, rest)?;
141 let rest = tzif.parse_time_zone_designations(&header32, rest)?;
142 let rest = tzif.parse_leap_seconds(&header32, rest)?;
143 let rest = tzif.parse_indicators(&header32, rest)?;
144 Ok((tzif, rest))
145 }
146
147 fn parse64<'b>(
148 name: Option<String>,
149 header32: Header,
150 bytes: &'b [u8],
151 ) -> Result<(TzifOwned, &'b [u8]), Error> {
152 let (_, rest) = try_split_at(
153 "V1 TZif data block",
154 bytes,
155 header32.data_block_len()?,
156 )?;
157 let (header64, rest) = Header::parse(8, rest)
158 .map_err(|e| err!("failed to parse 64-bit header: {e}"))?;
159 let mut tzif = TzifOwned {
160 fixed: TzifFixed {
161 name,
162 version: header64.version,
163 // filled in later
164 checksum: 0,
165 designations: String::new(),
166 posix_tz: None,
167 },
168 types: vec![],
169 transitions: TzifTransitions {
170 timestamps: vec![],
171 civil_starts: vec![],
172 civil_ends: vec![],
173 infos: vec![],
174 },
175 };
176 let rest = tzif.parse_transitions(&header64, rest)?;
177 let rest = tzif.parse_transition_types(&header64, rest)?;
178 let rest = tzif.parse_local_time_types(&header64, rest)?;
179 let rest = tzif.parse_time_zone_designations(&header64, rest)?;
180 let rest = tzif.parse_leap_seconds(&header64, rest)?;
181 let rest = tzif.parse_indicators(&header64, rest)?;
182 let rest = tzif.parse_footer(&header64, rest)?;
183 // Note that we don't check that the TZif data is fully valid. It is
184 // possible for it to contain superfluous information. For example, a
185 // non-zero local time type that is never referenced by a transition.
186 Ok((tzif, rest))
187 }
188
189 fn parse_transitions<'b>(
190 &mut self,
191 header: &Header,
192 bytes: &'b [u8],
193 ) -> Result<&'b [u8], Error> {
194 let (bytes, rest) = try_split_at(
195 "transition times data block",
196 bytes,
197 header.transition_times_len()?,
198 )?;
199 let mut it = bytes.chunks_exact(header.time_size);
200 // RFC 8536 says: "If there are no transitions, local time for all
201 // timestamps is specified by the TZ string in the footer if present
202 // and nonempty; otherwise, it is specified by time type 0."
203 //
204 // RFC 8536 also says: "Local time for timestamps before the first
205 // transition is specified by the first time type (time type
206 // 0)."
207 //
208 // So if there are no transitions, pushing this dummy one will result
209 // in the desired behavior even when it's the only transition.
210 // Similarly, since this is the minimum timestamp value, it will
211 // trigger for any times before the first transition found in the TZif
212 // data.
213 self.transitions.add_with_type_index(TIMESTAMP_MIN, 0);
214 while let Some(chunk) = it.next() {
215 let mut timestamp = if header.is_32bit() {
216 i64::from(from_be_bytes_i32(chunk))
217 } else {
218 from_be_bytes_i64(chunk)
219 };
220 if !(TIMESTAMP_MIN <= timestamp && timestamp <= TIMESTAMP_MAX) {
221 // We really shouldn't error here just because the Unix
222 // timestamp is outside what Jiff supports. Since what Jiff
223 // supports is _somewhat_ arbitrary. But Jiff's supported
224 // range is good enough for all realistic purposes, so we
225 // just clamp an out-of-range Unix timestamp to the Jiff
226 // min or max value.
227 //
228 // This can't result in the sorting order being wrong, but
229 // it can result in a transition that is duplicative with
230 // the dummy transition we inserted above. This should be
231 // fine.
232 let clamped = timestamp.clamp(TIMESTAMP_MIN, TIMESTAMP_MAX);
233 timestamp = clamped;
234 }
235 self.transitions.add(timestamp);
236 }
237 assert!(it.remainder().is_empty());
238 Ok(rest)
239 }
240
241 fn parse_transition_types<'b>(
242 &mut self,
243 header: &Header,
244 bytes: &'b [u8],
245 ) -> Result<&'b [u8], Error> {
246 let (bytes, rest) = try_split_at(
247 "transition types data block",
248 bytes,
249 header.transition_types_len()?,
250 )?;
251 // We skip the first transition because it is our minimum dummy
252 // transition.
253 for (transition_index, &type_index) in (1..).zip(bytes) {
254 if usize::from(type_index) >= header.tzh_typecnt {
255 return Err(err!(
256 "found transition type index {type_index},
257 but there are only {} local time types",
258 header.tzh_typecnt,
259 ));
260 }
261 self.transitions.infos[transition_index].type_index = type_index;
262 }
263 Ok(rest)
264 }
265
266 fn parse_local_time_types<'b>(
267 &mut self,
268 header: &Header,
269 bytes: &'b [u8],
270 ) -> Result<&'b [u8], Error> {
271 let (bytes, rest) = try_split_at(
272 "local time types data block",
273 bytes,
274 header.local_time_types_len()?,
275 )?;
276 let mut it = bytes.chunks_exact(6);
277 while let Some(chunk) = it.next() {
278 let offset = from_be_bytes_i32(&chunk[..4]);
279 if !(OFFSET_MIN <= offset && offset <= OFFSET_MAX) {
280 return Err(err!(
281 "found local time type with out-of-bounds offset: {offset}"
282 ));
283 }
284 let is_dst = chunk[4] == 1;
285 let designation = (chunk[5], chunk[5]);
286 self.types.push(TzifLocalTimeType {
287 offset,
288 is_dst,
289 designation,
290 indicator: TzifIndicator::LocalWall,
291 });
292 }
293 assert!(it.remainder().is_empty());
294 Ok(rest)
295 }
296
297 fn parse_time_zone_designations<'b>(
298 &mut self,
299 header: &Header,
300 bytes: &'b [u8],
301 ) -> Result<&'b [u8], Error> {
302 let (bytes, rest) = try_split_at(
303 "time zone designations data block",
304 bytes,
305 header.time_zone_designations_len()?,
306 )?;
307 self.fixed.designations =
308 String::from_utf8(bytes.to_vec()).map_err(|_| {
309 err!(
310 "time zone designations are not valid UTF-8: {:?}",
311 Bytes(bytes),
312 )
313 })?;
314 // Holy hell, this is brutal. The boundary conditions are crazy.
315 for (i, typ) in self.types.iter_mut().enumerate() {
316 let start = usize::from(typ.designation.0);
317 let Some(suffix) = self.fixed.designations.get(start..) else {
318 return Err(err!(
319 "local time type {i} has designation index of {start}, \
320 but cannot be more than {}",
321 self.fixed.designations.len(),
322 ));
323 };
324 let Some(len) = suffix.find('\x00') else {
325 return Err(err!(
326 "local time type {i} has designation index of {start}, \
327 but could not find NUL terminator after it in \
328 designations: {:?}",
329 self.fixed.designations,
330 ));
331 };
332 let Some(end) = start.checked_add(len) else {
333 return Err(err!(
334 "local time type {i} has designation index of {start}, \
335 but its length {len} is too big",
336 ));
337 };
338 typ.designation.1 = u8::try_from(end).map_err(|_| {
339 err!(
340 "local time type {i} has designation range of \
341 {start}..{end}, but end is too big",
342 )
343 })?;
344 }
345 Ok(rest)
346 }
347
348 /// This parses the leap second corrections in the TZif data.
349 ///
350 /// Note that we only parse and verify them. We don't actually use them.
351 /// Jiff effectively ignores leap seconds.
352 fn parse_leap_seconds<'b>(
353 &mut self,
354 header: &Header,
355 bytes: &'b [u8],
356 ) -> Result<&'b [u8], Error> {
357 let (bytes, rest) = try_split_at(
358 "leap seconds data block",
359 bytes,
360 header.leap_second_len()?,
361 )?;
362 let chunk_len = header
363 .time_size
364 .checked_add(4)
365 .expect("time_size plus 4 fits in usize");
366 let mut it = bytes.chunks_exact(chunk_len);
367 while let Some(chunk) = it.next() {
368 let (occur_bytes, _corr_bytes) = chunk.split_at(header.time_size);
369 let occur = if header.is_32bit() {
370 i64::from(from_be_bytes_i32(occur_bytes))
371 } else {
372 from_be_bytes_i64(occur_bytes)
373 };
374 if !(TIMESTAMP_MIN <= occur && occur <= TIMESTAMP_MAX) {}
375 }
376 assert!(it.remainder().is_empty());
377 Ok(rest)
378 }
379
380 fn parse_indicators<'b>(
381 &mut self,
382 header: &Header,
383 bytes: &'b [u8],
384 ) -> Result<&'b [u8], Error> {
385 let (std_wall_bytes, rest) = try_split_at(
386 "standard/wall indicators data block",
387 bytes,
388 header.standard_wall_len()?,
389 )?;
390 let (ut_local_bytes, rest) = try_split_at(
391 "UT/local indicators data block",
392 rest,
393 header.ut_local_len()?,
394 )?;
395 if std_wall_bytes.is_empty() && !ut_local_bytes.is_empty() {
396 // This is a weird case, but technically possible only if all
397 // UT/local indicators are 0. If any are 1, then it's an error,
398 // because it would require the corresponding std/wall indicator
399 // to be 1 too. Which it can't be, because there aren't any. So
400 // we just check that they're all zeros.
401 for (i, &byte) in ut_local_bytes.iter().enumerate() {
402 if byte != 0 {
403 return Err(err!(
404 "found UT/local indicator '{byte}' for local time \
405 type {i}, but it must be 0 since all std/wall \
406 indicators are 0",
407 ));
408 }
409 }
410 } else if !std_wall_bytes.is_empty() && ut_local_bytes.is_empty() {
411 for (i, &byte) in std_wall_bytes.iter().enumerate() {
412 // Indexing is OK because Header guarantees that the number of
413 // indicators is 0 or equal to the number of types.
414 self.types[i].indicator = if byte == 0 {
415 TzifIndicator::LocalWall
416 } else if byte == 1 {
417 TzifIndicator::LocalStandard
418 } else {
419 return Err(err!(
420 "found invalid std/wall indicator '{byte}' for \
421 local time type {i}, it must be 0 or 1",
422 ));
423 };
424 }
425 } else if !std_wall_bytes.is_empty() && !ut_local_bytes.is_empty() {
426 assert_eq!(std_wall_bytes.len(), ut_local_bytes.len());
427 let it = std_wall_bytes.iter().zip(ut_local_bytes);
428 for (i, (&stdwall, &utlocal)) in it.enumerate() {
429 // Indexing is OK because Header guarantees that the number of
430 // indicators is 0 or equal to the number of types.
431 self.types[i].indicator = match (stdwall, utlocal) {
432 (0, 0) => TzifIndicator::LocalWall,
433 (1, 0) => TzifIndicator::LocalStandard,
434 (1, 1) => TzifIndicator::UTStandard,
435 (0, 1) => {
436 return Err(err!(
437 "found illegal ut-wall combination for \
438 local time type {i}, only local-wall, \
439 local-standard and ut-standard are allowed",
440 ))
441 }
442 _ => {
443 return Err(err!(
444 "found illegal std/wall or ut/local value for \
445 local time type {i}, each must be 0 or 1",
446 ))
447 }
448 };
449 }
450 } else {
451 // If they're both empty then we don't need to do anything. Every
452 // local time type record already has the correct default for this
453 // case set.
454 debug_assert!(std_wall_bytes.is_empty());
455 debug_assert!(ut_local_bytes.is_empty());
456 }
457 Ok(rest)
458 }
459
460 fn parse_footer<'b>(
461 &mut self,
462 _header: &Header,
463 bytes: &'b [u8],
464 ) -> Result<&'b [u8], Error> {
465 if bytes.is_empty() {
466 return Err(err!(
467 "invalid V2+ TZif footer, expected \\n, \
468 but found unexpected end of data",
469 ));
470 }
471 if bytes[0] != b'\n' {
472 return Err(err!(
473 "invalid V2+ TZif footer, expected {:?}, but found {:?}",
474 Byte(b'\n'),
475 Byte(bytes[0]),
476 ));
477 }
478 let bytes = &bytes[1..];
479 // Only scan up to 1KB for a NUL terminator in case we somehow got
480 // passed a huge block of bytes.
481 let toscan = &bytes[..bytes.len().min(1024)];
482 let Some(nlat) = toscan.iter().position(|&b| b == b'\n') else {
483 return Err(err!(
484 "invalid V2 TZif footer, could not find {:?} \
485 terminator in: {:?}",
486 Byte(b'\n'),
487 Bytes(toscan),
488 ));
489 };
490 let (bytes, rest) = bytes.split_at(nlat);
491 if !bytes.is_empty() {
492 // We could in theory limit TZ strings to their strict POSIX
493 // definition here for TZif V2, but I don't think there is any
494 // harm in allowing the extensions in V2 formatted TZif data. Note
495 // that the GNU tooling allow it via the `TZ` environment variable
496 // even though POSIX doesn't specify it. This all seems okay to me
497 // because the V3+ extension is a strict superset of functionality.
498 let posix_tz =
499 PosixTimeZone::parse(bytes).map_err(|e| err!("{e}"))?;
500 self.fixed.posix_tz = Some(posix_tz);
501 }
502 Ok(&rest[1..])
503 }
504
505 /// Validates that the POSIX TZ string we parsed (if one exists) is
506 /// consistent with the last transition in this time zone. This is
507 /// required by RFC 8536.
508 ///
509 /// RFC 8536 says, "If the string is nonempty and one or more
510 /// transitions appear in the version 2+ data, the string MUST be
511 /// consistent with the last version 2+ transition."
512 fn verify_posix_time_zone_consistency(&self) -> Result<(), Error> {
513 // We need to be a little careful, since we always have at least one
514 // transition (accounting for the dummy `Timestamp::MIN` transition).
515 // So if we only have 1 transition and a POSIX TZ string, then we
516 // should not validate it since it's equivalent to the case of 0
517 // transitions and a POSIX TZ string.
518 if self.transitions.timestamps.len() <= 1 {
519 return Ok(());
520 }
521 let Some(ref tz) = self.fixed.posix_tz else {
522 return Ok(());
523 };
524 let last = self
525 .transitions
526 .timestamps
527 .last()
528 .expect("last transition timestamp");
529 let type_index = self
530 .transitions
531 .infos
532 .last()
533 .expect("last transition info")
534 .type_index;
535 let typ = &self.types[usize::from(type_index)];
536 let (ioff, abbrev, is_dst) =
537 tz.to_offset_info(ITimestamp::from_second(*last));
538 if ioff.second != typ.offset {
539 return Err(err!(
540 "expected last transition to have DST offset \
541 of {expected_offset}, but got {got_offset} \
542 according to POSIX TZ string {tz}",
543 expected_offset = typ.offset,
544 got_offset = ioff.second,
545 tz = tz,
546 ));
547 }
548 if is_dst != typ.is_dst {
549 return Err(err!(
550 "expected last transition to have is_dst={expected_dst}, \
551 but got is_dst={got_dst} according to POSIX TZ \
552 string {tz}",
553 expected_dst = typ.is_dst,
554 got_dst = is_dst,
555 tz = tz,
556 ));
557 }
558 if abbrev != self.designation(&typ) {
559 return Err(err!(
560 "expected last transition to have \
561 designation={expected_abbrev}, \
562 but got designation={got_abbrev} according to POSIX TZ \
563 string {tz}",
564 expected_abbrev = self.designation(&typ),
565 got_abbrev = abbrev,
566 tz = tz,
567 ));
568 }
569 Ok(())
570 }
571
572 /// Add civil datetimes to our transitions.
573 ///
574 /// This isn't strictly necessary, but it speeds up time zone lookups when
575 /// the input is a civil datetime. It lets us do comparisons directly on
576 /// the civil datetime as given, instead of needing to convert the civil
577 /// datetime given to a timestamp first. (Even if we didn't do this, I
578 /// believe we'd still need at least one additional timestamp that is
579 /// offset, because TZ lookups for a civil datetime are done in local time,
580 /// and the timestamps in TZif data are, of course, all in UTC.)
581 fn add_civil_datetimes_to_transitions(&mut self) {
582 fn to_datetime(timestamp: i64, offset: i32) -> TzifDateTime {
583 use crate::shared::util::itime::{IOffset, ITimestamp};
584 let its = ITimestamp { second: timestamp, nanosecond: 0 };
585 let ioff = IOffset { second: offset };
586 let dt = its.to_datetime(ioff);
587 TzifDateTime::new(
588 dt.date.year,
589 dt.date.month,
590 dt.date.day,
591 dt.time.hour,
592 dt.time.minute,
593 dt.time.second,
594 )
595 }
596
597 let trans = &mut self.transitions;
598 for i in 0..trans.timestamps.len() {
599 let timestamp = trans.timestamps[i];
600 let offset = {
601 let type_index = trans.infos[i].type_index;
602 self.types[usize::from(type_index)].offset
603 };
604 let prev_offset = {
605 let type_index = trans.infos[i.saturating_sub(1)].type_index;
606 self.types[usize::from(type_index)].offset
607 };
608
609 if prev_offset == offset {
610 // Equivalent offsets means there can never be any ambiguity.
611 let start = to_datetime(timestamp, prev_offset);
612 trans.infos[i].kind = TzifTransitionKind::Unambiguous;
613 trans.civil_starts[i] = start;
614 } else if prev_offset < offset {
615 // When the offset of the previous transition is less, that
616 // means there is some non-zero amount of time that is
617 // "skipped" when moving to the next transition. Thus, we have
618 // a gap. The start of the gap is the offset which gets us the
619 // earliest time, i.e., the smaller of the two offsets.
620 trans.infos[i].kind = TzifTransitionKind::Gap;
621 trans.civil_starts[i] = to_datetime(timestamp, prev_offset);
622 trans.civil_ends[i] = to_datetime(timestamp, offset);
623 } else {
624 // When the offset of the previous transition is greater, that
625 // means there is some non-zero amount of time that will be
626 // replayed on a wall clock in this time zone. Thus, we have
627 // a fold. The start of the gold is the offset which gets us
628 // the earliest time, i.e., the smaller of the two offsets.
629 assert!(prev_offset > offset);
630 trans.infos[i].kind = TzifTransitionKind::Fold;
631 trans.civil_starts[i] = to_datetime(timestamp, offset);
632 trans.civil_ends[i] = to_datetime(timestamp, prev_offset);
633 }
634 }
635 }
636
637 /// Fatten up this TZif data with additional transitions.
638 ///
639 /// These additional transitions often make time zone lookups faster, and
640 /// they smooth out the performance difference between using "slim" and
641 /// "fat" tzdbs.
642 fn fatten(&mut self) {
643 // Note that this is a crate feature for *both* `jiff` and
644 // `jiff-static`.
645 if !cfg!(feature = "tz-fat") {
646 return;
647 }
648 let Some(posix_tz) = self.fixed.posix_tz.clone() else { return };
649 let last =
650 self.transitions.timestamps.last().expect("last transition");
651 let mut i = 0;
652 let mut prev = ITimestamp::from_second(*last);
653 loop {
654 if i > FATTEN_MAX_TRANSITIONS {
655 return;
656 }
657 i += 1;
658 prev = match self.add_transition(&posix_tz, prev) {
659 None => break,
660 Some(next) => next,
661 };
662 }
663 }
664
665 /// If there's a transition strictly after the given timestamp for the
666 /// given POSIX time zone, then add it to this TZif data.
667 fn add_transition(
668 &mut self,
669 posix_tz: &PosixTimeZone<Abbreviation>,
670 prev: ITimestamp,
671 ) -> Option<ITimestamp> {
672 let (its, ioff, abbrev, is_dst) = posix_tz.next_transition(prev)?;
673 if its.to_datetime(IOffset::UTC).date.year >= FATTEN_UP_TO_YEAR {
674 return None;
675 }
676 let type_index =
677 self.find_or_create_local_time_type(ioff, abbrev, is_dst)?;
678 self.transitions.add_with_type_index(its.second, type_index);
679 Some(its)
680 }
681
682 /// Look for a local time type matching the data given.
683 ///
684 /// If one could not be found, then one is created and its index is
685 /// returned.
686 ///
687 /// If one could not be found and one could not be created (e.g., the index
688 /// would overflow `u8`), then `None` is returned.
689 fn find_or_create_local_time_type(
690 &mut self,
691 offset: IOffset,
692 abbrev: &str,
693 is_dst: bool,
694 ) -> Option<u8> {
695 for (i, typ) in self.types.iter().enumerate() {
696 if offset.second == typ.offset
697 && abbrev == self.designation(typ)
698 && is_dst == typ.is_dst
699 {
700 return u8::try_from(i).ok();
701 }
702 }
703 let i = u8::try_from(self.types.len()).ok()?;
704 let designation = self.find_or_create_designation(abbrev)?;
705 self.types.push(TzifLocalTimeType {
706 offset: offset.second,
707 is_dst,
708 designation,
709 // Not really clear if this is correct, but Jiff
710 // ignores this anyway, so ¯\_(ツ)_/¯.
711 indicator: TzifIndicator::LocalWall,
712 });
713 Some(i)
714 }
715
716 /// Look for a designation (i.e., time zone abbreviation) matching the data
717 /// given, and return its range into `self.fixed.designations`.
718 ///
719 /// If one could not be found, then one is created and its range is
720 /// returned.
721 ///
722 /// If one could not be found and one could not be created (e.g., the range
723 /// would overflow `u8`), then `None` is returned.
724 fn find_or_create_designation(
725 &mut self,
726 needle: &str,
727 ) -> Option<(u8, u8)> {
728 let mut start = 0;
729 while let Some(offset) = self.fixed.designations[start..].find('\0') {
730 let end = start + offset;
731 let abbrev = &self.fixed.designations[start..end];
732 if needle == abbrev {
733 return Some((start.try_into().ok()?, end.try_into().ok()?));
734 }
735 start = end + 1;
736 }
737
738 // Now we need to add a new abbreviation. This
739 // should generally only happen for malformed TZif
740 // data. i.e., TZif data with a POSIX time zone that
741 // contains an TZ abbreviation that isn't found in
742 // the TZif's designation list.
743 //
744 // And since we're guarding against malformed data,
745 // the designation list might not end with NUL. If
746 // not, add one.
747 if !self.fixed.designations.ends_with('\0') {
748 self.fixed.designations.push('\0');
749 }
750 let start = self.fixed.designations.len();
751 self.fixed.designations.push_str(needle);
752 self.fixed.designations.push('\0');
753 let end = self.fixed.designations.len();
754 Some((start.try_into().ok()?, end.try_into().ok()?))
755 }
756
757 fn designation(&self, typ: &TzifLocalTimeType) -> &str {
758 let range =
759 usize::from(typ.designation.0)..usize::from(typ.designation.1);
760 // OK because we verify that the designation range on every local
761 // time type is a valid range into `self.designations`.
762 &self.fixed.designations[range]
763 }
764 }
765
766 impl TzifTransitionsOwned {
767 /// Add a single transition with the given timestamp.
768 ///
769 /// This also fills in the other columns (civil starts, civil ends and
770 /// infos) with sensible default values. It is expected that callers will
771 /// later fill them in.
772 fn add(&mut self, timestamp: i64) {
773 self.add_with_type_index(timestamp, 0);
774 }
775
776 /// Like `TzifTransitionsOwned::add`, but let's the caller provide a type
777 /// index if it is known.
778 fn add_with_type_index(&mut self, timestamp: i64, type_index: u8) {
779 self.timestamps.push(timestamp);
780 self.civil_starts.push(TzifDateTime::ZERO);
781 self.civil_ends.push(TzifDateTime::ZERO);
782 self.infos.push(TzifTransitionInfo {
783 type_index,
784 kind: TzifTransitionKind::Unambiguous,
785 });
786 }
787 }
788
789 /// The header for a TZif formatted file.
790 ///
791 /// V2+ TZif format have two headers: one for V1 data, and then a second
792 /// following the V1 data block that describes another data block which uses
793 /// 64-bit timestamps. The two headers both have the same format and both
794 /// use 32-bit big-endian encoded integers.
795 #[derive(Debug)]
796 struct Header {
797 /// The size of the timestamps encoded in the data block.
798 ///
799 /// This is guaranteed to be either 4 (for V1) or 8 (for the 64-bit header
800 /// block in V2+).
801 time_size: usize,
802 /// The file format version.
803 ///
804 /// Note that this is either a NUL byte (for version 1), or an ASCII byte
805 /// corresponding to the version number. That is, `0x32` for `2`, `0x33`
806 /// for `3` or `0x34` for `4`. Note also that just because zoneinfo might
807 /// have been recently generated does not mean it uses the latest format
808 /// version. It seems like newer versions are only compiled by `zic` when
809 /// they are needed. For example, `America/New_York` on my system (as of
810 /// `2024-03-25`) has version `0x32`, but `Asia/Jerusalem` has version
811 /// `0x33`.
812 version: u8,
813 /// Number of UT/local indicators stored in the file.
814 ///
815 /// This is checked to be either equal to `0` or equal to `tzh_typecnt`.
816 tzh_ttisutcnt: usize,
817 /// The number of standard/wall indicators stored in the file.
818 ///
819 /// This is checked to be either equal to `0` or equal to `tzh_typecnt`.
820 tzh_ttisstdcnt: usize,
821 /// The number of leap seconds for which data entries are stored in the
822 /// file.
823 tzh_leapcnt: usize,
824 /// The number of transition times for which data entries are stored in
825 /// the file.
826 tzh_timecnt: usize,
827 /// The number of local time types for which data entries are stored in the
828 /// file.
829 ///
830 /// This is checked to be at least `1`.
831 tzh_typecnt: usize,
832 /// The number of bytes of time zone abbreviation strings stored in the
833 /// file.
834 ///
835 /// This is checked to be at least `1`.
836 tzh_charcnt: usize,
837 }
838
839 impl Header {
840 /// Parse the header record from the given bytes.
841 ///
842 /// Upon success, return the header and all bytes after the header.
843 ///
844 /// The given `time_size` must be 4 or 8, corresponding to either the
845 /// V1 header block or the V2+ header block, respectively.
846 fn parse(
847 time_size: usize,
848 bytes: &[u8],
849 ) -> Result<(Header, &[u8]), Error> {
850 assert!(time_size == 4 || time_size == 8, "time size must be 4 or 8");
851 if bytes.len() < 44 {
852 return Err(err!("invalid header: too short"));
853 }
854 let (magic, rest) = bytes.split_at(4);
855 if magic != b"TZif" {
856 return Err(err!("invalid header: magic bytes mismatch"));
857 }
858 let (version, rest) = rest.split_at(1);
859 let (_reserved, rest) = rest.split_at(15);
860
861 let (tzh_ttisutcnt_bytes, rest) = rest.split_at(4);
862 let (tzh_ttisstdcnt_bytes, rest) = rest.split_at(4);
863 let (tzh_leapcnt_bytes, rest) = rest.split_at(4);
864 let (tzh_timecnt_bytes, rest) = rest.split_at(4);
865 let (tzh_typecnt_bytes, rest) = rest.split_at(4);
866 let (tzh_charcnt_bytes, rest) = rest.split_at(4);
867
868 let tzh_ttisutcnt = from_be_bytes_u32_to_usize(tzh_ttisutcnt_bytes)
869 .map_err(|e| err!("failed to parse tzh_ttisutcnt: {e}"))?;
870 let tzh_ttisstdcnt = from_be_bytes_u32_to_usize(tzh_ttisstdcnt_bytes)
871 .map_err(|e| err!("failed to parse tzh_ttisstdcnt: {e}"))?;
872 let tzh_leapcnt = from_be_bytes_u32_to_usize(tzh_leapcnt_bytes)
873 .map_err(|e| err!("failed to parse tzh_leapcnt: {e}"))?;
874 let tzh_timecnt = from_be_bytes_u32_to_usize(tzh_timecnt_bytes)
875 .map_err(|e| err!("failed to parse tzh_timecnt: {e}"))?;
876 let tzh_typecnt = from_be_bytes_u32_to_usize(tzh_typecnt_bytes)
877 .map_err(|e| err!("failed to parse tzh_typecnt: {e}"))?;
878 let tzh_charcnt = from_be_bytes_u32_to_usize(tzh_charcnt_bytes)
879 .map_err(|e| err!("failed to parse tzh_charcnt: {e}"))?;
880
881 if tzh_ttisutcnt != 0 && tzh_ttisutcnt != tzh_typecnt {
882 return Err(err!(
883 "expected tzh_ttisutcnt={tzh_ttisutcnt} to be zero \
884 or equal to tzh_typecnt={tzh_typecnt}",
885 ));
886 }
887 if tzh_ttisstdcnt != 0 && tzh_ttisstdcnt != tzh_typecnt {
888 return Err(err!(
889 "expected tzh_ttisstdcnt={tzh_ttisstdcnt} to be zero \
890 or equal to tzh_typecnt={tzh_typecnt}",
891 ));
892 }
893 if tzh_typecnt < 1 {
894 return Err(err!(
895 "expected tzh_typecnt={tzh_typecnt} to be at least 1",
896 ));
897 }
898 if tzh_charcnt < 1 {
899 return Err(err!(
900 "expected tzh_charcnt={tzh_charcnt} to be at least 1",
901 ));
902 }
903
904 let header = Header {
905 time_size,
906 version: version[0],
907 tzh_ttisutcnt,
908 tzh_ttisstdcnt,
909 tzh_leapcnt,
910 tzh_timecnt,
911 tzh_typecnt,
912 tzh_charcnt,
913 };
914 Ok((header, rest))
915 }
916
917 /// Returns true if this header is for a 32-bit data block.
918 ///
919 /// When false, it is guaranteed that this header is for a 64-bit data
920 /// block.
921 fn is_32bit(&self) -> bool {
922 self.time_size == 4
923 }
924
925 /// Returns the size of the data block, in bytes, for this header.
926 ///
927 /// This returns an error if the arithmetic required to compute the
928 /// length would overflow.
929 ///
930 /// This is useful for, e.g., skipping over the 32-bit V1 data block in
931 /// V2+ TZif formatted files.
932 fn data_block_len(&self) -> Result<usize, Error> {
933 let a = self.transition_times_len()?;
934 let b = self.transition_types_len()?;
935 let c = self.local_time_types_len()?;
936 let d = self.time_zone_designations_len()?;
937 let e = self.leap_second_len()?;
938 let f = self.standard_wall_len()?;
939 let g = self.ut_local_len()?;
940 a.checked_add(b)
941 .and_then(|z| z.checked_add(c))
942 .and_then(|z| z.checked_add(d))
943 .and_then(|z| z.checked_add(e))
944 .and_then(|z| z.checked_add(f))
945 .and_then(|z| z.checked_add(g))
946 .ok_or_else(|| {
947 err!(
948 "length of data block in V{} tzfile is too big",
949 self.version
950 )
951 })
952 }
953
954 fn transition_times_len(&self) -> Result<usize, Error> {
955 self.tzh_timecnt.checked_mul(self.time_size).ok_or_else(|| {
956 err!("tzh_timecnt value {} is too big", self.tzh_timecnt)
957 })
958 }
959
960 fn transition_types_len(&self) -> Result<usize, Error> {
961 Ok(self.tzh_timecnt)
962 }
963
964 fn local_time_types_len(&self) -> Result<usize, Error> {
965 self.tzh_typecnt.checked_mul(6).ok_or_else(|| {
966 err!("tzh_typecnt value {} is too big", self.tzh_typecnt)
967 })
968 }
969
970 fn time_zone_designations_len(&self) -> Result<usize, Error> {
971 Ok(self.tzh_charcnt)
972 }
973
974 fn leap_second_len(&self) -> Result<usize, Error> {
975 let record_len = self
976 .time_size
977 .checked_add(4)
978 .expect("4-or-8 plus 4 always fits in usize");
979 self.tzh_leapcnt.checked_mul(record_len).ok_or_else(|| {
980 err!("tzh_leapcnt value {} is too big", self.tzh_leapcnt)
981 })
982 }
983
984 fn standard_wall_len(&self) -> Result<usize, Error> {
985 Ok(self.tzh_ttisstdcnt)
986 }
987
988 fn ut_local_len(&self) -> Result<usize, Error> {
989 Ok(self.tzh_ttisutcnt)
990 }
991 }
992
993 /// Splits the given slice of bytes at the index given.
994 ///
995 /// If the index is out of range (greater than `bytes.len()`) then an error is
996 /// returned. The error message will include the `what` string given, which is
997 /// meant to describe the thing being split.
998 fn try_split_at<'b>(
999 what: &'static str,
1000 bytes: &'b [u8],
1001 at: usize,
1002 ) -> Result<(&'b [u8], &'b [u8]), Error> {
1003 if at > bytes.len() {
1004 Err(err!(
1005 "expected at least {at} bytes for {what}, \
1006 but found only {} bytes",
1007 bytes.len(),
1008 ))
1009 } else {
1010 Ok(bytes.split_at(at))
1011 }
1012 }
1013
1014 /// Interprets the given slice as an unsigned 32-bit big endian integer,
1015 /// attempts to convert it to a `usize` and returns it.
1016 ///
1017 /// # Panics
1018 ///
1019 /// When `bytes.len() != 4`.
1020 ///
1021 /// # Errors
1022 ///
1023 /// This errors if the `u32` parsed from the given bytes cannot fit in a
1024 /// `usize`.
1025 fn from_be_bytes_u32_to_usize(bytes: &[u8]) -> Result<usize, Error> {
1026 let n = from_be_bytes_u32(bytes);
1027 usize::try_from(n).map_err(|_| {
1028 err!(
1029 "failed to parse integer {n} (too big, max allowed is {}",
1030 usize::MAX
1031 )
1032 })
1033 }
1034
1035 /// Interprets the given slice as an unsigned 32-bit big endian integer and
1036 /// returns it.
1037 ///
1038 /// # Panics
1039 ///
1040 /// When `bytes.len() != 4`.
1041 fn from_be_bytes_u32(bytes: &[u8]) -> u32 {
1042 u32::from_be_bytes(bytes.try_into().unwrap())
1043 }
1044
1045 /// Interprets the given slice as a signed 32-bit big endian integer and
1046 /// returns it.
1047 ///
1048 /// # Panics
1049 ///
1050 /// When `bytes.len() != 4`.
1051 fn from_be_bytes_i32(bytes: &[u8]) -> i32 {
1052 i32::from_be_bytes(bytes.try_into().unwrap())
1053 }
1054
1055 /// Interprets the given slice as a signed 64-bit big endian integer and
1056 /// returns it.
1057 ///
1058 /// # Panics
1059 ///
1060 /// When `bytes.len() != 8`.
1061 fn from_be_bytes_i64(bytes: &[u8]) -> i64 {
1062 i64::from_be_bytes(bytes.try_into().unwrap())
1063 }