1use crate::error::TzError;
4use crate::error::parse::TzFileError;
5use crate::parse::tz_string::parse_posix_tz;
6use crate::parse::utils::{Cursor, read_chunk_exact, read_exact};
7use crate::timezone::{LeapSecond, LocalTimeType, TimeZone, Transition, TransitionRule};
8
9use alloc::vec::Vec;
10use core::iter;
11use core::str;
12
13#[derive(Debug, Copy, Clone, Eq, PartialEq)]
15enum Version {
16 V1,
18 V2,
20 V3,
22}
23
24#[derive(Debug)]
26struct Header {
27 version: Version,
29 ut_local_count: usize,
31 std_wall_count: usize,
33 leap_count: usize,
35 transition_count: usize,
37 type_count: usize,
39 char_count: usize,
41}
42
43fn parse_header(cursor: &mut Cursor<'_>) -> Result<Header, TzFileError> {
45 let magic = read_exact(cursor, 4)?;
46 if magic != *b"TZif" {
47 return Err(TzFileError::InvalidMagicNumber);
48 }
49
50 let version = match read_exact(cursor, 1)? {
51 [0x00] => Version::V1,
52 [0x32] => Version::V2,
53 [0x33] => Version::V3,
54 _ => return Err(TzFileError::UnsupportedTzFileVersion),
55 };
56
57 read_exact(cursor, 15)?;
58
59 let ut_local_count = u32::from_be_bytes(*read_chunk_exact(cursor)?);
60 let std_wall_count = u32::from_be_bytes(*read_chunk_exact(cursor)?);
61 let leap_count = u32::from_be_bytes(*read_chunk_exact(cursor)?);
62 let transition_count = u32::from_be_bytes(*read_chunk_exact(cursor)?);
63 let type_count = u32::from_be_bytes(*read_chunk_exact(cursor)?);
64 let char_count = u32::from_be_bytes(*read_chunk_exact(cursor)?);
65
66 if !(type_count != 0 && char_count != 0 && (ut_local_count == 0 || ut_local_count == type_count) && (std_wall_count == 0 || std_wall_count == type_count)) {
67 return Err(TzFileError::InvalidHeader);
68 }
69
70 Ok(Header {
71 version,
72 ut_local_count: ut_local_count as usize,
73 std_wall_count: std_wall_count as usize,
74 leap_count: leap_count as usize,
75 transition_count: transition_count as usize,
76 type_count: type_count as usize,
77 char_count: char_count as usize,
78 })
79}
80
81fn parse_footer(footer: &[u8], use_string_extensions: bool) -> Result<Option<TransitionRule>, TzError> {
83 let footer = str::from_utf8(footer).map_err(TzFileError::from)?;
84 if !(footer.starts_with('\n') && footer.ends_with('\n')) {
85 return Err(TzError::TzFile(TzFileError::InvalidFooter));
86 }
87
88 let tz_string = footer.trim_matches(|c: char| c.is_ascii_whitespace());
89 if tz_string.starts_with(':') || tz_string.contains('\0') {
90 return Err(TzError::TzFile(TzFileError::InvalidFooter));
91 }
92
93 if !tz_string.is_empty() { Ok(Some(parse_posix_tz(tz_string.as_bytes(), use_string_extensions)).transpose()?) } else { Ok(None) }
94}
95
96struct DataBlocks<'a, const TIME_SIZE: usize> {
98 transition_times: &'a [u8],
100 transition_types: &'a [u8],
102 local_time_types: &'a [u8],
104 time_zone_designations: &'a [u8],
106 leap_seconds: &'a [u8],
108 std_walls: &'a [u8],
110 ut_locals: &'a [u8],
112}
113
114fn read_data_blocks<'a, const TIME_SIZE: usize>(cursor: &mut Cursor<'a>, header: &Header) -> Result<DataBlocks<'a, TIME_SIZE>, TzFileError> {
116 Ok(DataBlocks {
117 transition_times: read_exact(cursor, header.transition_count * TIME_SIZE)?,
118 transition_types: read_exact(cursor, header.transition_count)?,
119 local_time_types: read_exact(cursor, header.type_count * 6)?,
120 time_zone_designations: read_exact(cursor, header.char_count)?,
121 leap_seconds: read_exact(cursor, header.leap_count * (TIME_SIZE + 4))?,
122 std_walls: read_exact(cursor, header.std_wall_count)?,
123 ut_locals: read_exact(cursor, header.ut_local_count)?,
124 })
125}
126
127trait ParseTime {
128 type TimeData;
129
130 fn parse_time(&self, data: &Self::TimeData) -> i64;
131}
132
133impl ParseTime for DataBlocks<'_, 4> {
134 type TimeData = [u8; 4];
135
136 fn parse_time(&self, data: &Self::TimeData) -> i64 {
137 i32::from_be_bytes(*data).into()
138 }
139}
140
141impl ParseTime for DataBlocks<'_, 8> {
142 type TimeData = [u8; 8];
143
144 fn parse_time(&self, data: &Self::TimeData) -> i64 {
145 i64::from_be_bytes(*data)
146 }
147}
148
149impl<'a, const TIME_SIZE: usize> DataBlocks<'a, TIME_SIZE>
150where
151 DataBlocks<'a, TIME_SIZE>: ParseTime<TimeData = [u8; TIME_SIZE]>,
152{
153 fn parse(&self, header: &Header, footer: Option<&[u8]>) -> Result<TimeZone, TzError> {
155 let mut transitions = Vec::with_capacity(header.transition_count);
156 for (time_data, &local_time_type_index) in self.transition_times.chunks_exact(TIME_SIZE).zip(self.transition_types) {
157 let time_data = time_data.first_chunk::<TIME_SIZE>().unwrap();
158
159 let unix_leap_time = self.parse_time(time_data);
160 let local_time_type_index = local_time_type_index as usize;
161 transitions.push(Transition::new(unix_leap_time, local_time_type_index));
162 }
163
164 let mut local_time_types = Vec::with_capacity(header.type_count);
165 for data in self.local_time_types.chunks_exact(6) {
166 let [d0, d1, d2, d3, d4, d5] = <[u8; 6]>::try_from(data).unwrap();
167
168 let ut_offset = i32::from_be_bytes([d0, d1, d2, d3]);
169
170 let is_dst = match d4 {
171 0 => false,
172 1 => true,
173 _ => return Err(TzError::TzFile(TzFileError::InvalidDstIndicator)),
174 };
175
176 let char_index = d5 as usize;
177 if char_index >= header.char_count {
178 return Err(TzError::TzFile(TzFileError::InvalidTimeZoneDesignationCharIndex));
179 }
180
181 let time_zone_designation = match self.time_zone_designations[char_index..].iter().position(|&c| c == b'\0') {
182 None => return Err(TzError::TzFile(TzFileError::InvalidTimeZoneDesignationCharIndex)),
183 Some(position) => {
184 let time_zone_designation = &self.time_zone_designations[char_index..char_index + position];
185
186 if !time_zone_designation.is_empty() { Some(time_zone_designation) } else { None }
187 }
188 };
189
190 local_time_types.push(LocalTimeType::new(ut_offset, is_dst, time_zone_designation)?);
191 }
192
193 let mut leap_seconds = Vec::with_capacity(header.leap_count);
194 for data in self.leap_seconds.chunks_exact(TIME_SIZE + 4) {
195 let (time_data, tail) = data.split_first_chunk::<TIME_SIZE>().unwrap();
196 let correction_data = tail.first_chunk::<4>().unwrap();
197
198 let unix_leap_time = self.parse_time(time_data);
199 let correction = i32::from_be_bytes(*correction_data);
200 leap_seconds.push(LeapSecond::new(unix_leap_time, correction));
201 }
202
203 let std_walls_iter = self.std_walls.iter().copied().chain(iter::repeat(0));
204 let ut_locals_iter = self.ut_locals.iter().copied().chain(iter::repeat(0));
205 for (std_wall, ut_local) in std_walls_iter.zip(ut_locals_iter).take(header.type_count) {
206 if !matches!((std_wall, ut_local), (0, 0) | (1, 0) | (1, 1)) {
207 return Err(TzError::TzFile(TzFileError::InvalidStdWallUtLocal));
208 }
209 }
210
211 let extra_rule = footer.and_then(|footer| parse_footer(footer, header.version == Version::V3).transpose()).transpose()?;
212
213 TimeZone::new(transitions, local_time_types, leap_seconds, extra_rule)
214 }
215}
216
217pub(crate) fn parse_tz_file(bytes: &[u8]) -> Result<TimeZone, TzError> {
219 let mut cursor = bytes;
220
221 let header = parse_header(&mut cursor)?;
222
223 match header.version {
224 Version::V1 => {
225 let data_blocks = read_data_blocks::<4>(&mut cursor, &header)?;
226
227 if !cursor.is_empty() {
228 return Err(TzError::TzFile(TzFileError::RemainingDataV1));
229 }
230
231 Ok(data_blocks.parse(&header, None)?)
232 }
233 Version::V2 | Version::V3 => {
234 read_data_blocks::<4>(&mut cursor, &header)?;
236
237 let header = parse_header(&mut cursor)?;
238 let data_blocks = read_data_blocks::<8>(&mut cursor, &header)?;
239 let footer = cursor;
240
241 Ok(data_blocks.parse(&header, Some(footer))?)
242 }
243 }
244}
245
246#[cfg(test)]
247mod tests {
248 use super::*;
249 use crate::timezone::{AlternateTime, MonthWeekDay, RuleDay, TimeZone};
250
251 use alloc::vec;
252
253 #[test]
254 fn test_v1_file_with_leap_seconds() -> Result<(), TzError> {
255 let bytes = b"TZif\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01\0\0\0\x01\0\0\0\x1b\0\0\0\0\0\0\0\x01\0\0\0\x04\0\0\0\0\0\0UTC\0\x04\xb2\x58\0\0\0\0\x01\x05\xa4\xec\x01\0\0\0\x02\x07\x86\x1f\x82\0\0\0\x03\x09\x67\x53\x03\0\0\0\x04\x0b\x48\x86\x84\0\0\0\x05\x0d\x2b\x0b\x85\0\0\0\x06\x0f\x0c\x3f\x06\0\0\0\x07\x10\xed\x72\x87\0\0\0\x08\x12\xce\xa6\x08\0\0\0\x09\x15\x9f\xca\x89\0\0\0\x0a\x17\x80\xfe\x0a\0\0\0\x0b\x19\x62\x31\x8b\0\0\0\x0c\x1d\x25\xea\x0c\0\0\0\x0d\x21\xda\xe5\x0d\0\0\0\x0e\x25\x9e\x9d\x8e\0\0\0\x0f\x27\x7f\xd1\x0f\0\0\0\x10\x2a\x50\xf5\x90\0\0\0\x11\x2c\x32\x29\x11\0\0\0\x12\x2e\x13\x5c\x92\0\0\0\x13\x30\xe7\x24\x13\0\0\0\x14\x33\xb8\x48\x94\0\0\0\x15\x36\x8c\x10\x15\0\0\0\x16\x43\xb7\x1b\x96\0\0\0\x17\x49\x5c\x07\x97\0\0\0\x18\x4f\xef\x93\x18\0\0\0\x19\x55\x93\x2d\x99\0\0\0\x1a\x58\x68\x46\x9a\0\0\0\x1b\0\0";
256
257 let time_zone = parse_tz_file(bytes)?;
258
259 let time_zone_result = TimeZone::new(
260 vec![],
261 vec![LocalTimeType::new(0, false, Some(b"UTC"))?],
262 vec![
263 LeapSecond::new(78796800, 1),
264 LeapSecond::new(94694401, 2),
265 LeapSecond::new(126230402, 3),
266 LeapSecond::new(157766403, 4),
267 LeapSecond::new(189302404, 5),
268 LeapSecond::new(220924805, 6),
269 LeapSecond::new(252460806, 7),
270 LeapSecond::new(283996807, 8),
271 LeapSecond::new(315532808, 9),
272 LeapSecond::new(362793609, 10),
273 LeapSecond::new(394329610, 11),
274 LeapSecond::new(425865611, 12),
275 LeapSecond::new(489024012, 13),
276 LeapSecond::new(567993613, 14),
277 LeapSecond::new(631152014, 15),
278 LeapSecond::new(662688015, 16),
279 LeapSecond::new(709948816, 17),
280 LeapSecond::new(741484817, 18),
281 LeapSecond::new(773020818, 19),
282 LeapSecond::new(820454419, 20),
283 LeapSecond::new(867715220, 21),
284 LeapSecond::new(915148821, 22),
285 LeapSecond::new(1136073622, 23),
286 LeapSecond::new(1230768023, 24),
287 LeapSecond::new(1341100824, 25),
288 LeapSecond::new(1435708825, 26),
289 LeapSecond::new(1483228826, 27),
290 ],
291 None,
292 )?;
293
294 assert_eq!(time_zone, time_zone_result);
295
296 Ok(())
297 }
298
299 #[test]
300 fn test_v2_file() -> Result<(), TzError> {
301 let bytes = b"TZif2\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x06\0\0\0\x06\0\0\0\0\0\0\0\x07\0\0\0\x06\0\0\0\x14\x80\0\0\0\xbb\x05\x43\x48\xbb\x21\x71\x58\xcb\x89\x3d\xc8\xd2\x23\xf4\x70\xd2\x61\x49\x38\xd5\x8d\x73\x48\x01\x02\x01\x03\x04\x01\x05\xff\xff\x6c\x02\0\0\xff\xff\x6c\x58\0\x04\xff\xff\x7a\x68\x01\x08\xff\xff\x7a\x68\x01\x0c\xff\xff\x7a\x68\x01\x10\xff\xff\x73\x60\0\x04LMT\0HST\0HDT\0HWT\0HPT\0\0\0\0\0\x01\0\0\0\0\0\x01\0TZif2\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x06\0\0\0\x06\0\0\0\0\0\0\0\x07\0\0\0\x06\0\0\0\x14\xff\xff\xff\xff\x74\xe0\x70\xbe\xff\xff\xff\xff\xbb\x05\x43\x48\xff\xff\xff\xff\xbb\x21\x71\x58\xff\xff\xff\xff\xcb\x89\x3d\xc8\xff\xff\xff\xff\xd2\x23\xf4\x70\xff\xff\xff\xff\xd2\x61\x49\x38\xff\xff\xff\xff\xd5\x8d\x73\x48\x01\x02\x01\x03\x04\x01\x05\xff\xff\x6c\x02\0\0\xff\xff\x6c\x58\0\x04\xff\xff\x7a\x68\x01\x08\xff\xff\x7a\x68\x01\x0c\xff\xff\x7a\x68\x01\x10\xff\xff\x73\x60\0\x04LMT\0HST\0HDT\0HWT\0HPT\0\0\0\0\0\x01\0\0\0\0\0\x01\0\x0aHST10\x0a";
302
303 let time_zone = parse_tz_file(bytes)?;
304
305 let time_zone_result = TimeZone::new(
306 vec![
307 Transition::new(-2334101314, 1),
308 Transition::new(-1157283000, 2),
309 Transition::new(-1155436200, 1),
310 Transition::new(-880198200, 3),
311 Transition::new(-769395600, 4),
312 Transition::new(-765376200, 1),
313 Transition::new(-712150200, 5),
314 ],
315 vec![
316 LocalTimeType::new(-37886, false, Some(b"LMT"))?,
317 LocalTimeType::new(-37800, false, Some(b"HST"))?,
318 LocalTimeType::new(-34200, true, Some(b"HDT"))?,
319 LocalTimeType::new(-34200, true, Some(b"HWT"))?,
320 LocalTimeType::new(-34200, true, Some(b"HPT"))?,
321 LocalTimeType::new(-36000, false, Some(b"HST"))?,
322 ],
323 vec![],
324 Some(TransitionRule::Fixed(LocalTimeType::new(-36000, false, Some(b"HST"))?)),
325 )?;
326
327 assert_eq!(time_zone, time_zone_result);
328
329 assert_eq!(*time_zone.find_local_time_type(-1156939200)?, LocalTimeType::new(-34200, true, Some(b"HDT"))?);
330 assert_eq!(*time_zone.find_local_time_type(1546300800)?, LocalTimeType::new(-36000, false, Some(b"HST"))?);
331
332 Ok(())
333 }
334
335 #[test]
336 fn test_v3_file() -> Result<(), TzError> {
337 let bytes = b"TZif3\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01\0\0\0\x04\0\0\x1c\x20\0\0IST\0TZif3\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01\0\0\0\x01\0\0\0\0\0\0\0\x01\0\0\0\x01\0\0\0\x04\0\0\0\0\x7f\xe8\x17\x80\0\0\0\x1c\x20\0\0IST\0\x01\x01\x0aIST-2IDT,M3.4.4/26,M10.5.0\x0a";
338
339 let time_zone = parse_tz_file(bytes)?;
340
341 let time_zone_result = TimeZone::new(
342 vec![Transition::new(2145916800, 0)],
343 vec![LocalTimeType::new(7200, false, Some(b"IST"))?],
344 vec![],
345 Some(TransitionRule::Alternate(AlternateTime::new(
346 LocalTimeType::new(7200, false, Some(b"IST"))?,
347 LocalTimeType::new(10800, true, Some(b"IDT"))?,
348 RuleDay::MonthWeekDay(MonthWeekDay::new(3, 4, 4)?),
349 93600,
350 RuleDay::MonthWeekDay(MonthWeekDay::new(10, 5, 0)?),
351 7200,
352 )?)),
353 )?;
354
355 assert_eq!(time_zone, time_zone_result);
356
357 Ok(())
358 }
359}