1use alloc::{string::String, vec, vec::Vec};
2
3use crate::{
4 tz::{Abbreviation, Dst, Offset, posix},
5 util::{MaybeStaticSlice, crc32},
6};
7
8use super::{
9 DateTime, Indicator, LocalTimeType, TimeZone, Timestamp, TransitionInfo,
10 TransitionKind, Transitions,
11};
12
13const TIMESTAMP_MIN: i64 = Timestamp::MIN.as_second();
18const TIMESTAMP_MAX: i64 = Timestamp::MAX.as_second();
19
20const OFFSET_MIN: i32 = Offset::MIN.seconds();
23const OFFSET_MAX: i32 = Offset::MAX.seconds();
24
25const FATTEN_UP_TO_YEAR: i16 = 2038;
28
29const FATTEN_MAX_TRANSITIONS: usize = 300;
32
33impl TimeZone {
34 pub fn parse(bytes: &[u8]) -> Result<TimeZone, ParseError> {
47 ParsedTimeZone::parse(bytes)
48 }
49}
50
51struct ParsedTimeZone {
58 fixed: ParsedFixed,
59 types: Vec<LocalTimeType>,
60 transitions: ParsedTransitions,
61}
62
63struct ParsedFixed {
64 version: u8,
65 checksum: u32,
66 designations: Vec<Abbreviation>,
67 posix_tz: Option<posix::TimeZone>,
68}
69
70struct ParsedTransitions {
71 timestamps: Vec<Timestamp>,
72 civil_starts: Vec<DateTime>,
73 civil_ends: Vec<DateTime>,
74 infos: Vec<TransitionInfo>,
75}
76
77impl ParsedTimeZone {
78 fn parse(bytes: &[u8]) -> Result<TimeZone, ParseError> {
79 let original = bytes;
80 let (header32, rest) =
81 Header::parse(4, bytes).map_err(ParseErrorKind::Header32)?;
82 let (mut tzif, rest) = if header32.version == 0 {
83 ParsedTimeZone::parse32(header32, rest)?
84 } else {
85 ParsedTimeZone::parse64(header32, rest)?
86 };
87 tzif.fatten();
88 tzif.add_civil_datetimes_to_transitions();
91 tzif.verify_posix_time_zone_consistency()?;
92
93 let tzif_raw_len = original.len() - rest.len();
97 tzif.fixed.checksum = crc32::sum(&original[..tzif_raw_len]);
98
99 tzif.finish()
100 }
101
102 fn new(version: u8) -> ParsedTimeZone {
103 ParsedTimeZone {
104 fixed: ParsedFixed {
105 version,
106 checksum: 0,
107 designations: ::alloc::vec::Vec::new()vec![],
108 posix_tz: None,
109 },
110 types: ::alloc::vec::Vec::new()vec![],
111 transitions: ParsedTransitions {
112 timestamps: ::alloc::vec::Vec::new()vec![],
113 civil_starts: ::alloc::vec::Vec::new()vec![],
114 civil_ends: ::alloc::vec::Vec::new()vec![],
115 infos: ::alloc::vec::Vec::new()vec![],
116 },
117 }
118 }
119
120 fn finish(self) -> Result<TimeZone, ParseError> {
121 Ok(TimeZone {
122 version: self.fixed.version,
123 checksum: self.fixed.checksum,
124 designations: MaybeStaticSlice::heap(
125 self.fixed.designations.into_boxed_slice(),
126 ),
127 posix_tz: self.fixed.posix_tz,
128 types: MaybeStaticSlice::heap(self.types.into_boxed_slice()),
129 transitions: Transitions {
130 timestamps: MaybeStaticSlice::heap(
131 self.transitions.timestamps.into_boxed_slice(),
132 ),
133 civil_starts: MaybeStaticSlice::heap(
134 self.transitions.civil_starts.into_boxed_slice(),
135 ),
136 civil_ends: MaybeStaticSlice::heap(
137 self.transitions.civil_ends.into_boxed_slice(),
138 ),
139 infos: MaybeStaticSlice::heap(
140 self.transitions.infos.into_boxed_slice(),
141 ),
142 },
143 })
144 }
145
146 fn parse32<'b>(
147 header32: Header,
148 bytes: &'b [u8],
149 ) -> Result<(ParsedTimeZone, &'b [u8]), ParseError> {
150 let mut tzif = ParsedTimeZone::new(header32.version);
151 let rest = tzif.parse_transitions(&header32, bytes)?;
152 let rest = tzif.parse_transition_types(&header32, rest)?;
153 let rest = tzif.parse_local_time_types(&header32, rest)?;
154 let rest = tzif.parse_time_zone_designations(&header32, rest)?;
155 let rest = tzif.parse_leap_seconds(&header32, rest)?;
156 let rest = tzif.parse_indicators(&header32, rest)?;
157 Ok((tzif, rest))
158 }
159
160 fn parse64<'b>(
161 header32: Header,
162 bytes: &'b [u8],
163 ) -> Result<(ParsedTimeZone, &'b [u8]), ParseError> {
164 let (_, rest) =
165 try_split_at(SplitAtError::V1, bytes, header32.data_block_len()?)?;
166 let (header64, rest) =
167 Header::parse(8, rest).map_err(ParseErrorKind::Header64)?;
168 let mut tzif = ParsedTimeZone::new(header64.version);
169 let rest = tzif.parse_transitions(&header64, rest)?;
170 let rest = tzif.parse_transition_types(&header64, rest)?;
171 let rest = tzif.parse_local_time_types(&header64, rest)?;
172 let rest = tzif.parse_time_zone_designations(&header64, rest)?;
173 let rest = tzif.parse_leap_seconds(&header64, rest)?;
174 let rest = tzif.parse_indicators(&header64, rest)?;
175 let rest = tzif.parse_footer(&header64, rest)?;
176 Ok((tzif, rest))
180 }
181
182 fn parse_transitions<'b>(
183 &mut self,
184 header: &Header,
185 bytes: &'b [u8],
186 ) -> Result<&'b [u8], ParseError> {
187 let (bytes, rest) = try_split_at(
188 SplitAtError::TransitionTimes,
189 bytes,
190 header.transition_times_len()?,
191 )?;
192 let mut it = bytes.chunks_exact(header.time_size);
193 self.transitions.add_with_type_index(Timestamp::MIN, 0);
206 for chunk in &mut it {
207 let unix_timestamp = if header.is_32bit() {
208 i64::from(from_be_bytes_i32(chunk))
209 } else {
210 from_be_bytes_i64(chunk)
211 };
212 let timestamp = match Timestamp::from_second(unix_timestamp) {
213 Ok(timestamp) => timestamp,
214 Err(_) => {
215 let clamped =
227 if unix_timestamp < Timestamp::MIN.as_second() {
228 Timestamp::MIN
229 } else {
230 Timestamp::MAX
231 };
232 warn!(
233 "found Unix timestamp `{unix_timestamp}` that is \
234 outside Jiff's supported range, \
235 clamping to `{clamped:?}`",
236 );
237 clamped
238 }
239 };
240 self.transitions.add(timestamp);
241 }
242 if !it.remainder().is_empty() {
::core::panicking::panic("assertion failed: it.remainder().is_empty()")
};assert!(it.remainder().is_empty());
243 Ok(rest)
244 }
245
246 fn parse_transition_types<'b>(
247 &mut self,
248 header: &Header,
249 bytes: &'b [u8],
250 ) -> Result<&'b [u8], TransitionTypeError> {
251 let (bytes, rest) = try_split_at(
252 SplitAtError::TransitionTypes,
253 bytes,
254 header.transition_types_len(),
255 )?;
256 for (transition_index, &type_index) in (1..).zip(bytes) {
259 if usize::from(type_index) >= header.tzh_typecnt {
260 return Err(TransitionTypeError::ExceedsLocalTimeTypes);
261 }
262 self.transitions.infos[transition_index].type_index = type_index;
263 }
264 Ok(rest)
265 }
266
267 fn parse_local_time_types<'b>(
268 &mut self,
269 header: &Header,
270 bytes: &'b [u8],
271 ) -> Result<&'b [u8], ParseError> {
272 let (bytes, rest) = try_split_at(
273 SplitAtError::LocalTimeTypes,
274 bytes,
275 header.local_time_types_len()?,
276 )?;
277 let mut it = bytes.chunks_exact(6);
278 for chunk in &mut it {
279 let offset_seconds = from_be_bytes_i32(&chunk[..4]);
280 let offset =
281 Offset::from_seconds(offset_seconds).map_err(|_| {
282 LocalTimeTypeError::InvalidOffset {
283 offset: offset_seconds,
284 }
285 })?;
286 let dst = Dst::from(chunk[4] == 1);
287 let designation = chunk[5];
288 self.types.push(LocalTimeType {
289 offset,
290 dst,
291 designation,
292 indicator: Indicator::LocalWall,
293 });
294 }
295 if !it.remainder().is_empty() {
::core::panicking::panic("assertion failed: it.remainder().is_empty()")
};assert!(it.remainder().is_empty());
296 Ok(rest)
297 }
298
299 fn parse_time_zone_designations<'b>(
300 &mut self,
301 header: &Header,
302 bytes: &'b [u8],
303 ) -> Result<&'b [u8], TimeZoneDesignatorError> {
304 let (bytes, rest) = try_split_at(
305 SplitAtError::TimeZoneDesignations,
306 bytes,
307 header.time_zone_designations_len(),
308 )?;
309 let designations = String::from_utf8(bytes.to_vec())
310 .map_err(|_| TimeZoneDesignatorError::InvalidUtf8)?;
311 for type_index in 0..self.types.len() {
312 let start = usize::from(self.types[type_index].designation);
313 let suffix = designations
314 .get(start..)
315 .ok_or(TimeZoneDesignatorError::InvalidStart)?;
316 let len = suffix
317 .find('\x00')
318 .ok_or(TimeZoneDesignatorError::MissingNul)?;
319 let end = start
320 .checked_add(len)
321 .ok_or(TimeZoneDesignatorError::InvalidLength)?;
322 u8::try_from(end)
323 .map_err(|_| TimeZoneDesignatorError::InvalidEnd)?;
324 let abbreviation = &designations[start..end];
325 let designation = self
329 .find_or_create_designation(abbreviation)
330 .expect("there are at most 256 local time types");
331 self.types[type_index].designation = designation;
332 }
333 Ok(rest)
334 }
335
336 fn parse_leap_seconds<'b>(
341 &mut self,
342 header: &Header,
343 bytes: &'b [u8],
344 ) -> Result<&'b [u8], ParseError> {
345 let (bytes, rest) = try_split_at(
346 SplitAtError::LeapSeconds,
347 bytes,
348 header.leap_second_len()?,
349 )?;
350 let chunk_len = header.time_size.wrapping_add(4);
352 let mut it = bytes.chunks_exact(chunk_len);
353 for chunk in &mut it {
354 let (occur_bytes, _corr_bytes) = chunk.split_at(header.time_size);
355 let occur = if header.is_32bit() {
356 i64::from(from_be_bytes_i32(occur_bytes))
357 } else {
358 from_be_bytes_i64(occur_bytes)
359 };
360 if !(TIMESTAMP_MIN <= occur && occur <= TIMESTAMP_MAX) {
361 warn!(
362 "leap second occurrence `{occur}` is \
363 not in Jiff's supported range"
364 )
365 }
366 }
367 if !it.remainder().is_empty() {
::core::panicking::panic("assertion failed: it.remainder().is_empty()")
};assert!(it.remainder().is_empty());
368 Ok(rest)
369 }
370
371 fn parse_indicators<'b>(
372 &mut self,
373 header: &Header,
374 bytes: &'b [u8],
375 ) -> Result<&'b [u8], IndicatorError> {
376 let (std_wall_bytes, rest) = try_split_at(
377 SplitAtError::StandardWallIndicators,
378 bytes,
379 header.standard_wall_len(),
380 )?;
381 let (ut_local_bytes, rest) = try_split_at(
382 SplitAtError::UTLocalIndicators,
383 rest,
384 header.ut_local_len(),
385 )?;
386 if std_wall_bytes.is_empty() && !ut_local_bytes.is_empty() {
387 if ut_local_bytes.iter().any(|&byte| byte != 0) {
388 return Err(IndicatorError::UtLocalNonZero);
389 }
390 } else if !std_wall_bytes.is_empty() && ut_local_bytes.is_empty() {
391 for (i, &byte) in std_wall_bytes.iter().enumerate() {
392 self.types[i].indicator = if byte == 0 {
393 Indicator::LocalWall
394 } else if byte == 1 {
395 Indicator::LocalStandard
396 } else {
397 return Err(IndicatorError::InvalidStdWallIndicator);
398 };
399 }
400 } else if !std_wall_bytes.is_empty() && !ut_local_bytes.is_empty() {
401 {
match (&std_wall_bytes.len(), &ut_local_bytes.len()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(std_wall_bytes.len(), ut_local_bytes.len());
402 let it = std_wall_bytes.iter().zip(ut_local_bytes);
403 for (i, (&stdwall, &utlocal)) in it.enumerate() {
404 self.types[i].indicator = match (stdwall, utlocal) {
405 (0, 0) => Indicator::LocalWall,
406 (1, 0) => Indicator::LocalStandard,
407 (1, 1) => Indicator::UTStandard,
408 (0, 1) => {
409 return Err(IndicatorError::InvalidUtWallCombination);
410 }
411 _ => return Err(IndicatorError::InvalidCombination),
412 };
413 }
414 } else {
415 if true {
if !std_wall_bytes.is_empty() {
::core::panicking::panic("assertion failed: std_wall_bytes.is_empty()")
};
};debug_assert!(std_wall_bytes.is_empty());
416 if true {
if !ut_local_bytes.is_empty() {
::core::panicking::panic("assertion failed: ut_local_bytes.is_empty()")
};
};debug_assert!(ut_local_bytes.is_empty());
417 }
418 Ok(rest)
419 }
420
421 fn parse_footer<'b>(
422 &mut self,
423 _header: &Header,
424 bytes: &'b [u8],
425 ) -> Result<&'b [u8], FooterError> {
426 if bytes.is_empty() {
427 return Err(FooterError::UnexpectedEnd);
428 }
429 if bytes[0] != b'\n' {
430 return Err(FooterError::MismatchEnd);
431 }
432 let bytes = &bytes[1..];
433 let toscan = &bytes[..bytes.len().min(1024)];
436 let nlat = toscan
437 .iter()
438 .position(|&b| b == b'\n')
439 .ok_or(FooterError::TerminatorNotFound)?;
440 let (bytes, rest) = bytes.split_at(nlat);
441 if !bytes.is_empty() {
442 let posix_tz = posix::TimeZone::parse(bytes)
449 .map_err(FooterError::InvalidPosixTz)?;
450 self.fixed.posix_tz = Some(posix_tz);
451 }
452 Ok(&rest[1..])
453 }
454
455 fn verify_posix_time_zone_consistency(
458 &self,
459 ) -> Result<(), InconsistentPosixTimeZoneError> {
460 if self.transitions.timestamps.len() <= 1 {
461 return Ok(());
462 }
463 let Some(ref tz) = self.fixed.posix_tz else {
464 return Ok(());
465 };
466 let last = self
467 .transitions
468 .timestamps
469 .last()
470 .expect("last transition timestamp");
471 let type_index = self
472 .transitions
473 .infos
474 .last()
475 .expect("last transition info")
476 .type_index;
477 let typ = &self.types[usize::from(type_index)];
478 let timestamp = crate::Timestamp::from_second(last.as_second())
479 .expect("TZif timestamps are in range");
480 let info = tz.to_offset_info(timestamp);
481 if info.offset() != typ.offset {
482 return Err(InconsistentPosixTimeZoneError::Offset);
483 }
484 if info.dst() != typ.dst {
485 return Err(InconsistentPosixTimeZoneError::Dst);
486 }
487 if info.abbreviation().as_ref() != self.designation(typ) {
488 return Err(InconsistentPosixTimeZoneError::Designation);
489 }
490 Ok(())
491 }
492
493 fn add_civil_datetimes_to_transitions(&mut self) {
497 let trans = &mut self.transitions;
498 trans.infos[0].kind = TransitionKind::Unambiguous;
499 trans.civil_starts[0] = DateTime::MIN;
500 trans.civil_ends[0] = DateTime::MIN;
501 for i in 1..trans.timestamps.len() {
502 let timestamp = trans.timestamps[i];
503 let offset = {
504 let type_index = trans.infos[i].type_index;
505 self.types[usize::from(type_index)].offset
506 };
507 let prev_offset = {
508 let type_index = trans.infos[i.saturating_sub(1)].type_index;
509 self.types[usize::from(type_index)].offset
510 };
511
512 if prev_offset == offset {
513 let start = timestamp.to_datetime(prev_offset);
514 trans.infos[i].kind = TransitionKind::Unambiguous;
515 trans.civil_starts[i] = start;
516 trans.civil_ends[i] = start;
517 } else if prev_offset < offset {
518 trans.infos[i].kind = TransitionKind::Gap;
519 trans.civil_starts[i] = timestamp.to_datetime(prev_offset);
520 trans.civil_ends[i] = timestamp.to_datetime(offset);
521 } else {
522 if true {
if !(prev_offset > offset) {
::core::panicking::panic("assertion failed: prev_offset > offset")
};
};debug_assert!(prev_offset > offset);
523 trans.infos[i].kind = TransitionKind::Fold;
524 trans.civil_starts[i] = timestamp.to_datetime(offset);
525 trans.civil_ends[i] = timestamp.to_datetime(prev_offset);
526 }
527 }
528 }
529
530 fn fatten(&mut self) {
533 if !falsecfg!(feature = "tz-fat") {
535 return;
536 }
537 let Some(posix_tz) = self.fixed.posix_tz.clone() else {
538 return;
539 };
540 let Some(&last) = self.transitions.timestamps.last() else { return };
541 let mut i = 0;
542 let mut next = last;
543 loop {
544 if i > FATTEN_MAX_TRANSITIONS {
545 warn!(
546 "fattening TZif data for somehow generated more than \
547 {max} transitions, so giving up to avoid \
548 doing too much work",
549 max = FATTEN_MAX_TRANSITIONS,
550 );
551 return;
552 }
553 i += 1;
554 next = match self.fatten_add_transition(&posix_tz, next) {
555 None => break,
556 Some(next) => next,
557 };
558 }
559 }
560
561 fn fatten_add_transition(
562 &mut self,
563 posix_tz: &posix::TimeZone,
564 prev: Timestamp,
565 ) -> Option<Timestamp> {
566 let prev = crate::Timestamp::from_second(prev.as_second()).ok()?;
567 let trans = posix_tz.next_transition(prev)?;
568 if trans.timestamp().to_datetime(Offset::UTC).date().year()
569 >= FATTEN_UP_TO_YEAR
570 {
571 return None;
572 }
573 let type_index = self.find_or_create_local_time_type(
574 trans.offset(),
575 trans.abbreviation().as_ref(),
576 trans.dst(),
577 )?;
578 self.transitions.add_with_type_index(
579 Timestamp::new(trans.timestamp()),
580 type_index,
581 );
582 Some(Timestamp::new(trans.timestamp()))
583 }
584
585 fn find_or_create_local_time_type(
586 &mut self,
587 offset: Offset,
588 abbrev: &str,
589 dst: Dst,
590 ) -> Option<u8> {
591 for (i, typ) in self.types.iter().enumerate() {
592 if offset == typ.offset
593 && abbrev == self.designation(typ)
594 && dst == typ.dst
595 {
596 return u8::try_from(i).ok();
597 }
598 }
599 let i = u8::try_from(self.types.len()).ok()?;
600 let designation = self.find_or_create_designation(abbrev)?;
601 self.types.push(LocalTimeType {
602 offset,
603 dst,
604 designation,
605 indicator: Indicator::LocalWall,
606 });
607 Some(i)
608 }
609
610 fn find_or_create_designation(&mut self, needle: &str) -> Option<u8> {
623 if let Some(i) =
624 self.fixed.designations.iter().position(|abbrev| abbrev == needle)
625 {
626 return u8::try_from(i).ok();
627 }
628 let i = u8::try_from(self.fixed.designations.len()).ok()?;
629 self.fixed.designations.push(Abbreviation::new_or_heap(needle));
630 Some(i)
631 }
632
633 fn designation(&self, typ: &LocalTimeType) -> &str {
634 &self.fixed.designations[usize::from(typ.designation)]
635 }
636}
637
638impl ParsedTransitions {
639 fn add(&mut self, timestamp: Timestamp) {
640 self.add_with_type_index(timestamp, 0);
641 }
642
643 fn add_with_type_index(&mut self, timestamp: Timestamp, type_index: u8) {
644 self.timestamps.push(timestamp);
645 self.civil_starts.push(DateTime::MIN);
646 self.civil_ends.push(DateTime::MIN);
647 self.infos.push(TransitionInfo {
648 type_index,
649 kind: TransitionKind::Unambiguous,
650 });
651 }
652}
653
654#[derive(#[automatically_derived]impl ::core::fmt::Debug for Header {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_fields_finish(f,
"Header time_size version tzh_ttisutcnt tzh_ttisstdcnt tzh_leapcnt tzh_timecnt tzh_typecnt tzh_charcnt",
&[&self.time_size, &self.version, &self.tzh_ttisutcnt,
&self.tzh_ttisstdcnt, &self.tzh_leapcnt, &self.tzh_timecnt,
&self.tzh_typecnt, &&self.tzh_charcnt])
}
}Debug)]
660struct Header {
661 time_size: usize,
662 version: u8,
663 tzh_ttisutcnt: usize,
664 tzh_ttisstdcnt: usize,
665 tzh_leapcnt: usize,
666 tzh_timecnt: usize,
667 tzh_typecnt: usize,
668 tzh_charcnt: usize,
669}
670
671impl Header {
672 fn parse(
673 time_size: usize,
674 bytes: &[u8],
675 ) -> Result<(Header, &[u8]), HeaderError> {
676 if !(time_size == 4 || time_size == 8) {
{
::core::panicking::panic_fmt(format_args!("time size must be 4 or 8"));
}
};assert!(time_size == 4 || time_size == 8, "time size must be 4 or 8");
677 if bytes.len() < 44 {
678 return Err(HeaderError::TooShort);
679 }
680 let (magic, rest) = bytes.split_at(4);
681 if magic != b"TZif" {
682 return Err(HeaderError::MismatchMagic);
683 }
684 let (version, rest) = rest.split_at(1);
685 let (_reserved, rest) = rest.split_at(15);
686
687 let (tzh_ttisutcnt_bytes, rest) = rest.split_at(4);
688 let (tzh_ttisstdcnt_bytes, rest) = rest.split_at(4);
689 let (tzh_leapcnt_bytes, rest) = rest.split_at(4);
690 let (tzh_timecnt_bytes, rest) = rest.split_at(4);
691 let (tzh_typecnt_bytes, rest) = rest.split_at(4);
692 let (tzh_charcnt_bytes, rest) = rest.split_at(4);
693
694 let tzh_ttisutcnt =
695 from_be_bytes_u32_to_usize(tzh_ttisutcnt_bytes).map_err(|e| {
696 HeaderError::ParseCount { kind: CountKind::Ut, convert: e }
697 })?;
698 let tzh_ttisstdcnt =
699 from_be_bytes_u32_to_usize(tzh_ttisstdcnt_bytes).map_err(|e| {
700 HeaderError::ParseCount { kind: CountKind::Std, convert: e }
701 })?;
702 let tzh_leapcnt =
703 from_be_bytes_u32_to_usize(tzh_leapcnt_bytes).map_err(|e| {
704 HeaderError::ParseCount { kind: CountKind::Leap, convert: e }
705 })?;
706 let tzh_timecnt =
707 from_be_bytes_u32_to_usize(tzh_timecnt_bytes).map_err(|e| {
708 HeaderError::ParseCount { kind: CountKind::Time, convert: e }
709 })?;
710 let tzh_typecnt =
711 from_be_bytes_u32_to_usize(tzh_typecnt_bytes).map_err(|e| {
712 HeaderError::ParseCount { kind: CountKind::Type, convert: e }
713 })?;
714 let tzh_charcnt =
715 from_be_bytes_u32_to_usize(tzh_charcnt_bytes).map_err(|e| {
716 HeaderError::ParseCount { kind: CountKind::Char, convert: e }
717 })?;
718
719 if tzh_ttisutcnt != 0 && tzh_ttisutcnt != tzh_typecnt {
720 return Err(HeaderError::MismatchUtType);
721 }
722 if tzh_ttisstdcnt != 0 && tzh_ttisstdcnt != tzh_typecnt {
723 return Err(HeaderError::MismatchStdType);
724 }
725 if tzh_typecnt < 1 {
726 return Err(HeaderError::ZeroType);
727 }
728 if tzh_charcnt < 1 {
729 return Err(HeaderError::ZeroChar);
730 }
731
732 let header = Header {
733 time_size,
734 version: version[0],
735 tzh_ttisutcnt,
736 tzh_ttisstdcnt,
737 tzh_leapcnt,
738 tzh_timecnt,
739 tzh_typecnt,
740 tzh_charcnt,
741 };
742 Ok((header, rest))
743 }
744
745 fn is_32bit(&self) -> bool {
746 self.time_size == 4
747 }
748
749 fn data_block_len(&self) -> Result<usize, HeaderError> {
750 let a = self.transition_times_len()?;
751 let b = self.transition_types_len();
752 let c = self.local_time_types_len()?;
753 let d = self.time_zone_designations_len();
754 let e = self.leap_second_len()?;
755 let f = self.standard_wall_len();
756 let g = self.ut_local_len();
757 a.checked_add(b)
758 .and_then(|z| z.checked_add(c))
759 .and_then(|z| z.checked_add(d))
760 .and_then(|z| z.checked_add(e))
761 .and_then(|z| z.checked_add(f))
762 .and_then(|z| z.checked_add(g))
763 .ok_or(HeaderError::InvalidDataBlock { version: self.version })
764 }
765
766 fn transition_times_len(&self) -> Result<usize, HeaderError> {
767 self.tzh_timecnt
768 .checked_mul(self.time_size)
769 .ok_or(HeaderError::InvalidTimeCount)
770 }
771
772 fn transition_types_len(&self) -> usize {
773 self.tzh_timecnt
774 }
775
776 fn local_time_types_len(&self) -> Result<usize, HeaderError> {
777 self.tzh_typecnt.checked_mul(6).ok_or(HeaderError::InvalidTypeCount)
778 }
779
780 fn time_zone_designations_len(&self) -> usize {
781 self.tzh_charcnt
782 }
783
784 fn leap_second_len(&self) -> Result<usize, HeaderError> {
785 let record_len = self
786 .time_size
787 .checked_add(4)
788 .expect("4-or-8 plus 4 always fits in usize");
789 self.tzh_leapcnt
790 .checked_mul(record_len)
791 .ok_or(HeaderError::InvalidLeapSecondCount)
792 }
793
794 fn standard_wall_len(&self) -> usize {
795 self.tzh_ttisstdcnt
796 }
797
798 fn ut_local_len(&self) -> usize {
799 self.tzh_ttisutcnt
800 }
801}
802
803#[derive(#[automatically_derived]impl ::core::clone::Clone for ParseError {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
ParseError { kind: ::core::clone::Clone::clone(&self.kind) }
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for ParseError {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"ParseError kind", &&self.kind)
}
}Debug, #[automatically_derived]impl ::core::cmp::Eq for ParseError {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<ParseErrorKind>;
}
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
ParseError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ParseError {
#[inline]
fn eq(&self, other: &Self) -> bool { self.kind == other.kind }
}PartialEq)]
808#[cfg_attr(feature = "defmt", derive(defmt::Format))]
809pub struct ParseError {
810 kind: ParseErrorKind,
811}
812
813#[derive(#[automatically_derived]impl ::core::clone::Clone for ParseErrorKind {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
match self {
Self::Footer(__self_0) =>
ParseErrorKind::Footer(::core::clone::Clone::clone(__self_0)),
Self::Header(__self_0) =>
ParseErrorKind::Header(::core::clone::Clone::clone(__self_0)),
Self::Header32(__self_0) =>
ParseErrorKind::Header32(::core::clone::Clone::clone(__self_0)),
Self::Header64(__self_0) =>
ParseErrorKind::Header64(::core::clone::Clone::clone(__self_0)),
Self::InconsistentPosixTimeZone(__self_0) =>
ParseErrorKind::InconsistentPosixTimeZone(::core::clone::Clone::clone(__self_0)),
Self::Indicator(__self_0) =>
ParseErrorKind::Indicator(::core::clone::Clone::clone(__self_0)),
Self::LocalTimeType(__self_0) =>
ParseErrorKind::LocalTimeType(::core::clone::Clone::clone(__self_0)),
Self::SplitAt(__self_0) =>
ParseErrorKind::SplitAt(::core::clone::Clone::clone(__self_0)),
Self::TimeZoneDesignator(__self_0) =>
ParseErrorKind::TimeZoneDesignator(::core::clone::Clone::clone(__self_0)),
Self::TransitionType(__self_0) =>
ParseErrorKind::TransitionType(::core::clone::Clone::clone(__self_0)),
}
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for ParseErrorKind {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Footer(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Footer", &__self_0),
Self::Header(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Header", &__self_0),
Self::Header32(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Header32", &__self_0),
Self::Header64(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Header64", &__self_0),
Self::InconsistentPosixTimeZone(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"InconsistentPosixTimeZone", &__self_0),
Self::Indicator(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Indicator", &__self_0),
Self::LocalTimeType(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"LocalTimeType", &__self_0),
Self::SplitAt(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"SplitAt", &__self_0),
Self::TimeZoneDesignator(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"TimeZoneDesignator", &__self_0),
Self::TransitionType(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"TransitionType", &__self_0),
}
}
}Debug, #[automatically_derived]impl ::core::cmp::Eq for ParseErrorKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<FooterError>;
let _: ::core::cmp::AssertParamIsEq<HeaderError>;
let _: ::core::cmp::AssertParamIsEq<InconsistentPosixTimeZoneError>;
let _: ::core::cmp::AssertParamIsEq<IndicatorError>;
let _: ::core::cmp::AssertParamIsEq<LocalTimeTypeError>;
let _: ::core::cmp::AssertParamIsEq<SplitAtError>;
let _: ::core::cmp::AssertParamIsEq<TimeZoneDesignatorError>;
let _: ::core::cmp::AssertParamIsEq<TransitionTypeError>;
}
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
ParseErrorKind {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ParseErrorKind {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Footer(__self_0), Self::Footer(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::Header(__self_0), Self::Header(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::Header32(__self_0), Self::Header32(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::Header64(__self_0), Self::Header64(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::InconsistentPosixTimeZone(__self_0),
Self::InconsistentPosixTimeZone(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::Indicator(__self_0), Self::Indicator(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::LocalTimeType(__self_0), Self::LocalTimeType(__arg1_0))
=> __self_0 == __arg1_0,
(Self::SplitAt(__self_0), Self::SplitAt(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::TimeZoneDesignator(__self_0),
Self::TimeZoneDesignator(__arg1_0)) => __self_0 == __arg1_0,
(Self::TransitionType(__self_0),
Self::TransitionType(__arg1_0)) => __self_0 == __arg1_0,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq)]
814#[cfg_attr(feature = "defmt", derive(defmt::Format))]
815enum ParseErrorKind {
816 Footer(FooterError),
817 Header(HeaderError),
818 Header32(HeaderError),
819 Header64(HeaderError),
820 InconsistentPosixTimeZone(InconsistentPosixTimeZoneError),
821 Indicator(IndicatorError),
822 LocalTimeType(LocalTimeTypeError),
823 SplitAt(SplitAtError),
824 TimeZoneDesignator(TimeZoneDesignatorError),
825 TransitionType(TransitionTypeError),
826}
827
828impl core::error::Error for ParseError {}
829
830impl core::fmt::Display for ParseError {
831 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
832 use self::ParseErrorKind::*;
833 match self.kind {
834 Footer(ref err) => {
835 f.write_str("invalid TZif footer: ")?;
836 err.fmt(f)
837 }
838 Header(ref err) => {
839 f.write_str("invalid TZif header: ")?;
840 err.fmt(f)
841 }
842 Header32(ref err) => {
843 f.write_str("invalid 32-bit TZif header: ")?;
844 err.fmt(f)
845 }
846 Header64(ref err) => {
847 f.write_str("invalid 64-bit TZif header: ")?;
848 err.fmt(f)
849 }
850 InconsistentPosixTimeZone(ref err) => {
851 f.write_str(
852 "found inconsistency with POSIX time zone transition \
853 rule in TZif file footer: ",
854 )?;
855 err.fmt(f)
856 }
857 Indicator(ref err) => {
858 f.write_str("failed to parse indicators: ")?;
859 err.fmt(f)
860 }
861 LocalTimeType(ref err) => {
862 f.write_str("failed to parse local time types: ")?;
863 err.fmt(f)
864 }
865 SplitAt(ref err) => err.fmt(f),
866 TimeZoneDesignator(ref err) => {
867 f.write_str("failed to parse time zone designators: ")?;
868 err.fmt(f)
869 }
870 TransitionType(ref err) => {
871 f.write_str("failed to parse time zone transition types: ")?;
872 err.fmt(f)
873 }
874 }
875 }
876}
877
878impl From<ParseErrorKind> for ParseError {
879 fn from(kind: ParseErrorKind) -> ParseError {
880 ParseError { kind }
881 }
882}
883
884impl From<HeaderError> for ParseError {
885 fn from(err: HeaderError) -> ParseError {
886 ParseErrorKind::Header(err).into()
887 }
888}
889
890impl From<FooterError> for ParseError {
891 fn from(err: FooterError) -> ParseError {
892 ParseErrorKind::Footer(err).into()
893 }
894}
895
896impl From<InconsistentPosixTimeZoneError> for ParseError {
897 fn from(err: InconsistentPosixTimeZoneError) -> ParseError {
898 ParseErrorKind::InconsistentPosixTimeZone(err).into()
899 }
900}
901
902impl From<IndicatorError> for ParseError {
903 fn from(err: IndicatorError) -> ParseError {
904 ParseErrorKind::Indicator(err).into()
905 }
906}
907
908impl From<LocalTimeTypeError> for ParseError {
909 fn from(err: LocalTimeTypeError) -> ParseError {
910 ParseErrorKind::LocalTimeType(err).into()
911 }
912}
913
914impl From<SplitAtError> for ParseError {
915 fn from(err: SplitAtError) -> ParseError {
916 ParseErrorKind::SplitAt(err).into()
917 }
918}
919
920impl From<TimeZoneDesignatorError> for ParseError {
921 fn from(err: TimeZoneDesignatorError) -> ParseError {
922 ParseErrorKind::TimeZoneDesignator(err).into()
923 }
924}
925
926impl From<TransitionTypeError> for ParseError {
927 fn from(err: TransitionTypeError) -> ParseError {
928 ParseErrorKind::TransitionType(err).into()
929 }
930}
931
932#[derive(#[automatically_derived]impl ::core::clone::Clone for TransitionTypeError {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
match self {
Self::ExceedsLocalTimeTypes =>
TransitionTypeError::ExceedsLocalTimeTypes,
Self::Split(__self_0) =>
TransitionTypeError::Split(::core::clone::Clone::clone(__self_0)),
}
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for TransitionTypeError {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::ExceedsLocalTimeTypes =>
::core::fmt::Formatter::write_str(f, "ExceedsLocalTimeTypes"),
Self::Split(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Split",
&__self_0),
}
}
}Debug, #[automatically_derived]impl ::core::cmp::Eq for TransitionTypeError {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<SplitAtError>;
}
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
TransitionTypeError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for TransitionTypeError {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Split(__self_0), Self::Split(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq)]
933#[cfg_attr(feature = "defmt", derive(defmt::Format))]
934enum TransitionTypeError {
935 ExceedsLocalTimeTypes,
936 Split(SplitAtError),
937}
938
939impl From<SplitAtError> for TransitionTypeError {
940 fn from(err: SplitAtError) -> TransitionTypeError {
941 TransitionTypeError::Split(err)
942 }
943}
944
945impl core::fmt::Display for TransitionTypeError {
946 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
947 use self::TransitionTypeError::*;
948 match *self {
949 ExceedsLocalTimeTypes => f.write_str(
950 "found time zone transition type index that exceeds the \
951 number of local time types",
952 ),
953 Split(ref err) => err.fmt(f),
954 }
955 }
956}
957
958#[derive(#[automatically_derived]impl ::core::clone::Clone for LocalTimeTypeError {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
match self {
Self::InvalidOffset { offset: __self_0 } =>
LocalTimeTypeError::InvalidOffset {
offset: ::core::clone::Clone::clone(__self_0),
},
}
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for LocalTimeTypeError {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::InvalidOffset { offset: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"InvalidOffset offset", &__self_0),
}
}
}Debug, #[automatically_derived]impl ::core::cmp::Eq for LocalTimeTypeError {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<i32>;
}
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
LocalTimeTypeError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for LocalTimeTypeError {
#[inline]
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::InvalidOffset { offset: __self_0 }, Self::InvalidOffset {
offset: __arg1_0 }) => __self_0 == __arg1_0,
}
}
}PartialEq)]
959#[cfg_attr(feature = "defmt", derive(defmt::Format))]
960enum LocalTimeTypeError {
961 InvalidOffset { offset: i32 },
962}
963
964impl core::fmt::Display for LocalTimeTypeError {
965 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
966 use self::LocalTimeTypeError::*;
967 match *self {
968 InvalidOffset { offset } => f.write_fmt(format_args!("found local time type with out-of-bounds time zone offset: {0}, Jiff\'s allowed range is `{1}..={2}`",
offset, OFFSET_MIN, OFFSET_MAX))write!(
969 f,
970 "found local time type with out-of-bounds time zone offset: \
971 {offset}, Jiff's allowed range is \
972 `{OFFSET_MIN}..={OFFSET_MAX}`"
973 ),
974 }
975 }
976}
977
978#[derive(#[automatically_derived]impl ::core::clone::Clone for TimeZoneDesignatorError
{
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
match self {
Self::InvalidEnd => TimeZoneDesignatorError::InvalidEnd,
Self::InvalidLength => TimeZoneDesignatorError::InvalidLength,
Self::InvalidStart => TimeZoneDesignatorError::InvalidStart,
Self::InvalidUtf8 => TimeZoneDesignatorError::InvalidUtf8,
Self::MissingNul => TimeZoneDesignatorError::MissingNul,
Self::Split(__self_0) =>
TimeZoneDesignatorError::Split(::core::clone::Clone::clone(__self_0)),
}
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for TimeZoneDesignatorError {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::InvalidEnd =>
::core::fmt::Formatter::write_str(f, "InvalidEnd"),
Self::InvalidLength =>
::core::fmt::Formatter::write_str(f, "InvalidLength"),
Self::InvalidStart =>
::core::fmt::Formatter::write_str(f, "InvalidStart"),
Self::InvalidUtf8 =>
::core::fmt::Formatter::write_str(f, "InvalidUtf8"),
Self::MissingNul =>
::core::fmt::Formatter::write_str(f, "MissingNul"),
Self::Split(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Split",
&__self_0),
}
}
}Debug, #[automatically_derived]impl ::core::cmp::Eq for TimeZoneDesignatorError {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<SplitAtError>;
}
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
TimeZoneDesignatorError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for
TimeZoneDesignatorError {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Split(__self_0), Self::Split(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq)]
979#[cfg_attr(feature = "defmt", derive(defmt::Format))]
980enum TimeZoneDesignatorError {
981 InvalidEnd,
982 InvalidLength,
983 InvalidStart,
984 InvalidUtf8,
985 MissingNul,
986 Split(SplitAtError),
987}
988
989impl From<SplitAtError> for TimeZoneDesignatorError {
990 fn from(err: SplitAtError) -> TimeZoneDesignatorError {
991 TimeZoneDesignatorError::Split(err)
992 }
993}
994
995impl core::fmt::Display for TimeZoneDesignatorError {
996 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
997 use self::TimeZoneDesignatorError::*;
998 match *self {
999 InvalidEnd => f.write_str(
1000 "found invalid end of time zone designator for local time type",
1001 ),
1002 InvalidLength => f.write_str(
1003 "found invalid length of time zone designator for local time \
1004 type",
1005 ),
1006 InvalidStart => f.write_str(
1007 "found invalid start of time zone designator for local time \
1008 type",
1009 ),
1010 InvalidUtf8 => {
1011 f.write_str("found invalid UTF-8 in time zone designators")
1012 }
1013 MissingNul => f.write_str(
1014 "could not find NUL terminator for time zone designator",
1015 ),
1016 Split(ref err) => err.fmt(f),
1017 }
1018 }
1019}
1020
1021#[derive(#[automatically_derived]impl ::core::clone::Clone for IndicatorError {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
match self {
Self::InvalidCombination => IndicatorError::InvalidCombination,
Self::InvalidStdWallIndicator =>
IndicatorError::InvalidStdWallIndicator,
Self::InvalidUtWallCombination =>
IndicatorError::InvalidUtWallCombination,
Self::Split(__self_0) =>
IndicatorError::Split(::core::clone::Clone::clone(__self_0)),
Self::UtLocalNonZero => IndicatorError::UtLocalNonZero,
}
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for IndicatorError {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::InvalidCombination =>
::core::fmt::Formatter::write_str(f, "InvalidCombination"),
Self::InvalidStdWallIndicator =>
::core::fmt::Formatter::write_str(f,
"InvalidStdWallIndicator"),
Self::InvalidUtWallCombination =>
::core::fmt::Formatter::write_str(f,
"InvalidUtWallCombination"),
Self::Split(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Split",
&__self_0),
Self::UtLocalNonZero =>
::core::fmt::Formatter::write_str(f, "UtLocalNonZero"),
}
}
}Debug, #[automatically_derived]impl ::core::cmp::Eq for IndicatorError {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<SplitAtError>;
}
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
IndicatorError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for IndicatorError {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Split(__self_0), Self::Split(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq)]
1022#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1023enum IndicatorError {
1024 InvalidCombination,
1025 InvalidStdWallIndicator,
1026 InvalidUtWallCombination,
1027 Split(SplitAtError),
1028 UtLocalNonZero,
1029}
1030
1031impl From<SplitAtError> for IndicatorError {
1032 fn from(err: SplitAtError) -> IndicatorError {
1033 IndicatorError::Split(err)
1034 }
1035}
1036
1037impl core::fmt::Display for IndicatorError {
1038 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1039 use self::IndicatorError::*;
1040 match *self {
1041 InvalidCombination => f.write_str(
1042 "found invalid std/wall or UT/local value for local time type, \
1043 each must be 0 or 1",
1044 ),
1045 InvalidStdWallIndicator => f.write_str(
1046 "found invalid std/wall indicator, expected it to be 0 or 1",
1047 ),
1048 InvalidUtWallCombination => f.write_str(
1049 "found invalid UT-wall combination for local time type, only \
1050 local-wall, local-standard and UT-standard are allowed",
1051 ),
1052 Split(ref err) => err.fmt(f),
1053 UtLocalNonZero => f.write_str(
1054 "found non-zero UT/local indicator, but all such indicators \
1055 should be zero",
1056 ),
1057 }
1058 }
1059}
1060
1061#[derive(#[automatically_derived]impl ::core::clone::Clone for
InconsistentPosixTimeZoneError {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
match self {
Self::Designation => InconsistentPosixTimeZoneError::Designation,
Self::Dst => InconsistentPosixTimeZoneError::Dst,
Self::Offset => InconsistentPosixTimeZoneError::Offset,
}
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for
InconsistentPosixTimeZoneError {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
InconsistentPosixTimeZoneError::Designation => "Designation",
InconsistentPosixTimeZoneError::Dst => "Dst",
InconsistentPosixTimeZoneError::Offset => "Offset",
})
}
}Debug, #[automatically_derived]impl ::core::cmp::Eq for
InconsistentPosixTimeZoneError {
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
InconsistentPosixTimeZoneError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for
InconsistentPosixTimeZoneError {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq)]
1062#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1063enum InconsistentPosixTimeZoneError {
1064 Designation,
1065 Dst,
1066 Offset,
1067}
1068
1069impl core::fmt::Display for InconsistentPosixTimeZoneError {
1070 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1071 use self::InconsistentPosixTimeZoneError::*;
1072 match *self {
1073 Designation => f.write_str(
1074 "expected last transition in TZif file to have a time zone \
1075 abbreviation matching the abbreviation derived from the POSIX \
1076 time zone transition rule",
1077 ),
1078 Dst => f.write_str(
1079 "expected last transition in TZif file to have a DST status \
1080 matching the status derived from the POSIX time zone \
1081 transition rule",
1082 ),
1083 Offset => f.write_str(
1084 "expected last transition in TZif file to have DST offset \
1085 matching the offset derived from the POSIX time zone \
1086 transition rule",
1087 ),
1088 }
1089 }
1090}
1091
1092#[derive(#[automatically_derived]impl ::core::clone::Clone for FooterError {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
match self {
Self::InvalidPosixTz(__self_0) =>
FooterError::InvalidPosixTz(::core::clone::Clone::clone(__self_0)),
Self::MismatchEnd => FooterError::MismatchEnd,
Self::TerminatorNotFound => FooterError::TerminatorNotFound,
Self::UnexpectedEnd => FooterError::UnexpectedEnd,
}
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for FooterError {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::InvalidPosixTz(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"InvalidPosixTz", &__self_0),
Self::MismatchEnd =>
::core::fmt::Formatter::write_str(f, "MismatchEnd"),
Self::TerminatorNotFound =>
::core::fmt::Formatter::write_str(f, "TerminatorNotFound"),
Self::UnexpectedEnd =>
::core::fmt::Formatter::write_str(f, "UnexpectedEnd"),
}
}
}Debug, #[automatically_derived]impl ::core::cmp::Eq for FooterError {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<posix::ParseError>;
}
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
FooterError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for FooterError {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::InvalidPosixTz(__self_0),
Self::InvalidPosixTz(__arg1_0)) => __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq)]
1093#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1094enum FooterError {
1095 InvalidPosixTz(posix::ParseError),
1096 MismatchEnd,
1097 TerminatorNotFound,
1098 UnexpectedEnd,
1099}
1100
1101impl core::fmt::Display for FooterError {
1102 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1103 use self::FooterError::*;
1104 match *self {
1105 InvalidPosixTz(ref err) => {
1106 f.write_str("invalid POSIX time zone transition rule")?;
1107 core::fmt::Display::fmt(err, f)
1108 }
1109 MismatchEnd => f.write_str(
1110 "expected to find `\\n` at the beginning of the TZif file \
1111 footer, but found something else instead",
1112 ),
1113 TerminatorNotFound => f.write_str(
1114 "expected to find `\\n` terminating the TZif file footer, but \
1115 no line terminator could be found",
1116 ),
1117 UnexpectedEnd => f.write_str(
1118 "expected to find `\\n` at the beginning of the TZif file \
1119 footer, but found unexpected end of data",
1120 ),
1121 }
1122 }
1123}
1124
1125#[derive(#[automatically_derived]impl ::core::clone::Clone for HeaderError {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
match self {
Self::InvalidDataBlock { version: __self_0 } =>
HeaderError::InvalidDataBlock {
version: ::core::clone::Clone::clone(__self_0),
},
Self::InvalidLeapSecondCount =>
HeaderError::InvalidLeapSecondCount,
Self::InvalidTimeCount => HeaderError::InvalidTimeCount,
Self::InvalidTypeCount => HeaderError::InvalidTypeCount,
Self::MismatchMagic => HeaderError::MismatchMagic,
Self::MismatchStdType => HeaderError::MismatchStdType,
Self::MismatchUtType => HeaderError::MismatchUtType,
Self::ParseCount { kind: __self_0, convert: __self_1 } =>
HeaderError::ParseCount {
kind: ::core::clone::Clone::clone(__self_0),
convert: ::core::clone::Clone::clone(__self_1),
},
Self::TooShort => HeaderError::TooShort,
Self::ZeroChar => HeaderError::ZeroChar,
Self::ZeroType => HeaderError::ZeroType,
}
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for HeaderError {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::InvalidDataBlock { version: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"InvalidDataBlock version", &__self_0),
Self::InvalidLeapSecondCount =>
::core::fmt::Formatter::write_str(f,
"InvalidLeapSecondCount"),
Self::InvalidTimeCount =>
::core::fmt::Formatter::write_str(f, "InvalidTimeCount"),
Self::InvalidTypeCount =>
::core::fmt::Formatter::write_str(f, "InvalidTypeCount"),
Self::MismatchMagic =>
::core::fmt::Formatter::write_str(f, "MismatchMagic"),
Self::MismatchStdType =>
::core::fmt::Formatter::write_str(f, "MismatchStdType"),
Self::MismatchUtType =>
::core::fmt::Formatter::write_str(f, "MismatchUtType"),
Self::ParseCount { kind: __self_0, convert: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"ParseCount kind convert", __self_0, &__self_1),
Self::TooShort =>
::core::fmt::Formatter::write_str(f, "TooShort"),
Self::ZeroChar =>
::core::fmt::Formatter::write_str(f, "ZeroChar"),
Self::ZeroType =>
::core::fmt::Formatter::write_str(f, "ZeroType"),
}
}
}Debug, #[automatically_derived]impl ::core::cmp::Eq for HeaderError {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<u8>;
let _: ::core::cmp::AssertParamIsEq<CountKind>;
let _: ::core::cmp::AssertParamIsEq<U32UsizeError>;
}
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
HeaderError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for HeaderError {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::InvalidDataBlock { version: __self_0 },
Self::InvalidDataBlock { version: __arg1_0 }) =>
__self_0 == __arg1_0,
(Self::ParseCount { kind: __self_0, convert: __self_1 },
Self::ParseCount { kind: __arg1_0, convert: __arg1_1 }) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1,
_ => true,
}
}
}PartialEq)]
1126#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1127enum HeaderError {
1128 InvalidDataBlock { version: u8 },
1129 InvalidLeapSecondCount,
1130 InvalidTimeCount,
1131 InvalidTypeCount,
1132 MismatchMagic,
1133 MismatchStdType,
1134 MismatchUtType,
1135 ParseCount { kind: CountKind, convert: U32UsizeError },
1136 TooShort,
1137 ZeroChar,
1138 ZeroType,
1139}
1140
1141impl core::fmt::Display for HeaderError {
1142 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1143 use self::HeaderError::*;
1144 match *self {
1145 InvalidDataBlock { version } => f.write_fmt(format_args!("length of data block in V{0} TZif file is too big",
version))write!(
1146 f,
1147 "length of data block in V{version} TZif file is too big",
1148 ),
1149 InvalidLeapSecondCount => {
1150 f.write_str("number of leap seconds is too big")
1151 }
1152 InvalidTimeCount => {
1153 f.write_str("number of transition times is too big")
1154 }
1155 InvalidTypeCount => {
1156 f.write_str("number of local time types is too big")
1157 }
1158 MismatchMagic => f.write_str("magic bytes mismatch"),
1159 MismatchStdType => f.write_str(
1160 "expected number of standard/wall indicators to be zero or \
1161 equal to the number of local time types",
1162 ),
1163 MismatchUtType => f.write_str(
1164 "expected number of UT/local indicators to be zero or equal \
1165 to the number of local time types",
1166 ),
1167 ParseCount { ref kind, ref convert } => {
1168 f.write_fmt(format_args!("failed to parse `{0}`: {1}", kind, convert))write!(f, "failed to parse `{kind}`: {convert}")
1169 }
1170 TooShort => f.write_str("too short"),
1171 ZeroChar => f.write_str(
1172 "expected number of time zone abbreviations to be at least 1",
1173 ),
1174 ZeroType => f.write_str(
1175 "expected number of local time types to be at least 1",
1176 ),
1177 }
1178 }
1179}
1180
1181#[derive(#[automatically_derived]impl ::core::clone::Clone for CountKind {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
match self {
Self::Ut => CountKind::Ut,
Self::Std => CountKind::Std,
Self::Leap => CountKind::Leap,
Self::Time => CountKind::Time,
Self::Type => CountKind::Type,
Self::Char => CountKind::Char,
}
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for CountKind {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_c_like_enum_write_str(f,
"Ut Std Leap Time Type Char",
match self {
CountKind::Ut => 0usize,
CountKind::Std => 3usize,
CountKind::Leap => 7usize,
CountKind::Time => 12usize,
CountKind::Type => 17usize,
CountKind::Char => 22usize,
})
}
}Debug, #[automatically_derived]impl ::core::cmp::Eq for CountKind { }Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for CountKind
{
}
#[automatically_derived]impl ::core::cmp::PartialEq for CountKind {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq)]
1182#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1183enum CountKind {
1184 Ut,
1185 Std,
1186 Leap,
1187 Time,
1188 Type,
1189 Char,
1190}
1191
1192impl core::fmt::Display for CountKind {
1193 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1194 use self::CountKind::*;
1195 match *self {
1196 Ut => f.write_str("tzh_ttisutcnt"),
1197 Std => f.write_str("tzh_ttisstdcnt"),
1198 Leap => f.write_str("tzh_leapcnt"),
1199 Time => f.write_str("tzh_timecnt"),
1200 Type => f.write_str("tzh_typecnt"),
1201 Char => f.write_str("tzh_charcnt"),
1202 }
1203 }
1204}
1205
1206#[derive(#[automatically_derived]impl ::core::clone::Clone for SplitAtError {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
match self {
Self::V1 => SplitAtError::V1,
Self::LeapSeconds => SplitAtError::LeapSeconds,
Self::LocalTimeTypes => SplitAtError::LocalTimeTypes,
Self::StandardWallIndicators =>
SplitAtError::StandardWallIndicators,
Self::TimeZoneDesignations => SplitAtError::TimeZoneDesignations,
Self::TransitionTimes => SplitAtError::TransitionTimes,
Self::TransitionTypes => SplitAtError::TransitionTypes,
Self::UTLocalIndicators => SplitAtError::UTLocalIndicators,
}
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for SplitAtError {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_c_like_enum_write_str(f,
"V1 LeapSeconds LocalTimeTypes StandardWallIndicators TimeZoneDesignations TransitionTimes TransitionTypes UTLocalIndicators",
match self {
SplitAtError::V1 => 0usize,
SplitAtError::LeapSeconds => 3usize,
SplitAtError::LocalTimeTypes => 15usize,
SplitAtError::StandardWallIndicators => 30usize,
SplitAtError::TimeZoneDesignations => 53usize,
SplitAtError::TransitionTimes => 74usize,
SplitAtError::TransitionTypes => 90usize,
SplitAtError::UTLocalIndicators => 106usize,
})
}
}Debug, #[automatically_derived]impl ::core::cmp::Eq for SplitAtError { }Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
SplitAtError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for SplitAtError {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq)]
1207#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1208enum SplitAtError {
1209 V1,
1210 LeapSeconds,
1211 LocalTimeTypes,
1212 StandardWallIndicators,
1213 TimeZoneDesignations,
1214 TransitionTimes,
1215 TransitionTypes,
1216 UTLocalIndicators,
1217}
1218
1219impl core::fmt::Display for SplitAtError {
1220 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1221 use self::SplitAtError::*;
1222 f.write_str("expected bytes for '")?;
1223 f.write_str(match *self {
1224 V1 => "v1 TZif",
1225 LeapSeconds => "leap seconds",
1226 LocalTimeTypes => "local time types",
1227 StandardWallIndicators => "standard/wall indicators",
1228 TimeZoneDesignations => "time zone designations",
1229 TransitionTimes => "transition times",
1230 TransitionTypes => "transition types",
1231 UTLocalIndicators => "UT/local indicators",
1232 })?;
1233 f.write_str("data block', but did not find enough bytes")?;
1234 Ok(())
1235 }
1236}
1237
1238#[derive(#[automatically_derived]impl ::core::clone::Clone for U32UsizeError {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { U32UsizeError }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for U32UsizeError {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f, "U32UsizeError")
}
}Debug, #[automatically_derived]impl ::core::cmp::Eq for U32UsizeError { }Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
U32UsizeError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for U32UsizeError {
#[inline]
fn eq(&self, other: &Self) -> bool { true }
}PartialEq)]
1239#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1240struct U32UsizeError;
1241
1242impl core::fmt::Display for U32UsizeError {
1243 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1244 f.write_fmt(format_args!("failed to parse integer because it is bigger than `{0}`",
usize::MAX))write!(
1245 f,
1246 "failed to parse integer because it is bigger than `{max}`",
1247 max = usize::MAX,
1248 )
1249 }
1250}
1251
1252fn try_split_at<'b>(
1253 what: SplitAtError,
1254 bytes: &'b [u8],
1255 at: usize,
1256) -> Result<(&'b [u8], &'b [u8]), SplitAtError> {
1257 if at > bytes.len() { Err(what) } else { Ok(bytes.split_at(at)) }
1258}
1259
1260fn from_be_bytes_u32_to_usize(bytes: &[u8]) -> Result<usize, U32UsizeError> {
1261 let n = from_be_bytes_u32(bytes);
1262 usize::try_from(n).map_err(|_| U32UsizeError)
1263}
1264
1265fn from_be_bytes_u32(bytes: &[u8]) -> u32 {
1266 u32::from_be_bytes(bytes.try_into().unwrap())
1267}
1268
1269fn from_be_bytes_i32(bytes: &[u8]) -> i32 {
1270 i32::from_be_bytes(bytes.try_into().unwrap())
1271}
1272
1273fn from_be_bytes_i64(bytes: &[u8]) -> i64 {
1274 i64::from_be_bytes(bytes.try_into().unwrap())
1275}
1276
1277#[cfg(test)]
1280mod tests {
1281 use alloc::vec::Vec;
1282
1283 use super::*;
1284
1285 fn push_u32(bytes: &mut Vec<u8>, n: u32) {
1286 bytes.extend_from_slice(&n.to_be_bytes());
1287 }
1288
1289 fn push_header(bytes: &mut Vec<u8>, version: u8) {
1290 bytes.extend_from_slice(b"TZif");
1291 bytes.push(version);
1292 bytes.extend_from_slice(&[0; 15]);
1293 push_u32(bytes, 0); push_u32(bytes, 0); push_u32(bytes, 0); push_u32(bytes, 0); push_u32(bytes, 1); push_u32(bytes, 4); }
1300
1301 fn push_utc_type_and_designation(bytes: &mut Vec<u8>) {
1302 bytes.extend_from_slice(&0i32.to_be_bytes());
1303 bytes.push(0); bytes.push(0); bytes.extend_from_slice(b"UTC\0");
1306 }
1307
1308 fn minimal_v1() -> Vec<u8> {
1309 let mut bytes = vec![];
1310 push_header(&mut bytes, 0);
1311 push_utc_type_and_designation(&mut bytes);
1312 bytes
1313 }
1314
1315 fn minimal_v2(footer: &[u8]) -> Vec<u8> {
1316 let mut bytes = vec![];
1317 push_header(&mut bytes, b'2');
1318 push_utc_type_and_designation(&mut bytes);
1319 push_header(&mut bytes, b'2');
1320 push_utc_type_and_designation(&mut bytes);
1321 bytes.push(b'\n');
1322 bytes.extend_from_slice(footer);
1323 bytes.push(b'\n');
1324 bytes
1325 }
1326
1327 #[test]
1328 fn parse_minimal_v1() {
1329 let tzif = TimeZone::parse(&minimal_v1()).unwrap();
1330 assert_eq!(tzif.version, 0);
1331 assert_eq!(tzif.designations.as_ref(), &[Abbreviation::array("UTC")]);
1332 assert_eq!(tzif.types.len(), 1);
1333 assert_eq!(tzif.types[0].offset, Offset::UTC);
1334 assert_eq!(tzif.transitions.timestamps.len(), 1);
1335 assert_eq!(tzif.transitions.timestamps[0], Timestamp::MIN);
1336 assert_eq!(tzif.transitions.civil_starts[0], DateTime::MIN);
1337 }
1338
1339 #[test]
1340 fn parse_minimal_v2() {
1341 let tzif = TimeZone::parse(&minimal_v2(b"UTC0")).unwrap();
1342 assert_eq!(tzif.version, b'2');
1343 assert!(tzif.posix_tz.is_some());
1344 assert_eq!(tzif.designations.as_ref(), &[Abbreviation::array("UTC")]);
1345 assert_eq!(tzif.types.len(), 1);
1346 assert_eq!(tzif.transitions.timestamps.len(), 1);
1347 }
1348
1349 #[test]
1350 fn parse_minimal_v2_with_and_without_tz_fat() {
1351 let bytes = minimal_v2(b"EST5EDT,M3.2.0,M11.1.0");
1352 let tzif = TimeZone::parse(&bytes).unwrap();
1353 let expected = if cfg!(feature = "tz-fat") { 302 } else { 1 };
1354 assert_eq!(tzif.transitions.timestamps.len(), expected);
1355 }
1356}