1use std::collections::HashMap;
10use std::fmt;
11use std::sync::{Arc, OnceLock, RwLock};
12
13use super::abbreviations::{FALLBACKMAP, Row, TIMEZONEMAP};
14use super::tzindex::{INDEX, VERSION};
15
16static DATA: &[u8] = include_bytes!("../../data/timezonedb.bin");
17
18pub fn version() -> &'static str {
20 VERSION
21}
22
23#[derive(Debug, Clone)]
25struct TimeType {
26 offset: i32,
27 isdst: bool,
28 abbr_idx: usize,
29}
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32enum TransKind {
33 JulianNoFeb29,
35 JulianFeb29,
37 Mwd,
39}
40
41#[derive(Debug, Clone)]
42struct TransSpec {
43 kind: TransKind,
44 days: i64,
45 month: i64,
46 week: i64,
47 dow: i64,
48 hour: i64,
49}
50
51#[derive(Debug, Clone)]
53struct Posix {
54 std_offset: i64,
55 dst_offset: i64,
56 dst_end: Option<TransSpec>,
57 dst_begin: Option<TransSpec>,
58 type_index_std: usize,
59 type_index_dst: usize,
60}
61
62#[derive(Debug)]
64pub struct ZoneData {
65 trans: Vec<i64>,
66 trans_idx: Vec<u8>,
67 types: Vec<TimeType>,
68 abbrs: Vec<u8>,
69 posix: Option<Posix>,
70 pub bc: bool,
72 pub country_code: [u8; 2],
74}
75
76#[derive(Clone)]
81pub struct TzInfo {
82 name: Arc<str>,
83 data: Arc<ZoneData>,
84}
85
86impl fmt::Debug for TzInfo {
87 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89 f.debug_tuple("TzInfo").field(&self.name).finish()
90 }
91}
92
93impl PartialEq for TzInfo {
94 fn eq(&self, other: &Self) -> bool {
96 self.name == other.name
97 }
98}
99
100#[derive(Debug, Clone, PartialEq, Eq)]
102pub struct Offset {
103 pub offset: i32,
104 pub is_dst: bool,
105 pub abbr: String,
106 pub transition_time: i64,
107}
108
109impl TzInfo {
110 pub fn get(name: &str) -> Option<TzInfo> {
113 let pos = seek(name.as_bytes())?;
114 static CACHE: OnceLock<RwLock<HashMap<usize, Arc<ZoneData>>>> = OnceLock::new();
115 let cache = CACHE.get_or_init(|| RwLock::new(HashMap::new()));
116 if let Some(data) = cache.read().ok().and_then(|c| c.get(&pos).cloned()) {
117 return Some(TzInfo { name: name.into(), data });
118 }
119 let data = Arc::new(parse_zone(&DATA[INDEX[pos].1 as usize..])?);
120 if let Ok(mut c) = cache.write() {
121 c.insert(pos, data.clone());
122 }
123 Some(TzInfo { name: name.into(), data })
124 }
125
126 pub fn name(&self) -> &str {
128 &self.name
129 }
130
131 pub fn data(&self) -> &ZoneData {
133 &self.data
134 }
135
136 fn fetch(&self, ts: i64) -> Option<(&TimeType, i64)> {
139 let z = &*self.data;
140 if z.trans.is_empty() {
141 if z.posix.is_some() {
142 return self.fetch_posix(ts, false).map(|(t, _)| (t, i64::MIN));
143 }
144 if z.types.len() == 1 {
145 return Some((&z.types[0], i64::MIN));
146 }
147 return None;
148 }
149 if ts < z.trans[0] {
150 return Some((&z.types[0], i64::MIN));
151 }
152 let last = z.trans.len() - 1;
153 if ts >= z.trans[last] {
154 if z.posix.is_some() {
155 return self.fetch_posix(ts, true);
156 }
157 return Some((&z.types[z.trans_idx[last] as usize], z.trans[last]));
158 }
159 let (mut left, mut right) = (0usize, last);
160 while right - left > 1 {
161 let mid = (left + right) >> 1;
162 if ts < z.trans[mid] {
163 right = mid;
164 } else {
165 left = mid;
166 }
167 }
168 Some((&z.types[z.trans_idx[left] as usize], z.trans[left]))
169 }
170
171 fn fetch_posix(&self, ts: i64, with_transition: bool) -> Option<(&TimeType, i64)> {
173 let z = &*self.data;
174 let p = z.posix.as_ref()?;
175 let last_transition = || z.trans.last().copied().unwrap_or(i64::MIN);
176 let (Some(begin), Some(end)) = (&p.dst_begin, &p.dst_end) else {
177 let t = if with_transition { last_transition() } else { i64::MIN };
178 return Some((&z.types[p.type_index_std], t));
179 };
180 let year = super::timelib::unixtime2gmt(ts).y;
181 let mut times = [0i64; 6];
182 let mut types = [0usize; 6];
183 for (k, y) in [year.wrapping_sub(1), year, year.wrapping_add(1)].into_iter().enumerate() {
184 let year_begin = ts_at_start_of_year(y);
185 let trans_begin =
186 year_begin.wrapping_add(calc_transition(begin, y)).wrapping_add(begin.hour).wrapping_sub(p.std_offset);
187 let trans_end =
188 year_begin.wrapping_add(calc_transition(end, y)).wrapping_add(end.hour).wrapping_sub(p.dst_offset);
189 let i = k * 2;
190 if trans_begin < trans_end {
191 times[i] = trans_begin;
192 times[i + 1] = trans_end;
193 types[i] = p.type_index_dst;
194 types[i + 1] = p.type_index_std;
195 } else {
196 times[i + 1] = trans_begin;
197 times[i] = trans_end;
198 types[i + 1] = p.type_index_dst;
199 types[i] = p.type_index_std;
200 }
201 }
202 for i in 1..6 {
203 if ts < times[i] {
204 return Some((&z.types[types[i - 1]], times[i - 1]));
205 }
206 }
207 None
208 }
209
210 pub fn info(&self, ts: i64) -> Offset {
213 match self.fetch(ts) {
214 Some((t, transition_time)) => {
215 Offset { offset: t.offset, is_dst: t.isdst, abbr: self.abbr_at(t.abbr_idx), transition_time }
216 }
217 None => Offset { offset: 0, is_dst: false, abbr: self.abbr_at(0), transition_time: 0 },
218 }
219 }
220
221 pub fn offset_info(&self, ts: i64) -> Option<(i32, i64, bool)> {
224 self.fetch(ts).map(|(t, tt)| (t.offset, tt, t.isdst))
225 }
226
227 fn abbr_at(&self, idx: usize) -> String {
228 let a = &self.data.abbrs;
229 let s = a.get(idx..).unwrap_or(&[]);
230 let end = s.iter().position(|&c| c == 0).unwrap_or(s.len());
231 String::from_utf8_lossy(&s[..end]).into_owned()
232 }
233}
234
235pub fn strcasecmp(a: &[u8], b: &[u8]) -> i32 {
237 for (&x, &y) in a.iter().zip(b) {
238 let (x, y) = (x.to_ascii_lowercase(), y.to_ascii_lowercase());
239 if x != y {
240 return i32::from(x) - i32::from(y);
241 }
242 }
243 a.len() as i32 - b.len() as i32
244}
245
246fn seek(name: &[u8]) -> Option<usize> {
248 let name = &name[..name.iter().position(|&c| c == 0).unwrap_or(name.len())];
250 let (mut left, mut right) = (0i32, INDEX.len() as i32 - 1);
251 loop {
252 let mid = ((left as u32 + right as u32) >> 1) as i32;
253 let cmp = strcasecmp(name, INDEX[mid as usize].0.as_bytes());
254 if cmp < 0 {
255 right = mid - 1;
256 } else if cmp > 0 {
257 left = mid + 1;
258 } else {
259 return Some(mid as usize);
260 }
261 if left > right {
262 return None;
263 }
264 }
265}
266
267pub fn is_valid_id(name: &str) -> bool {
269 seek(name.as_bytes()).is_some()
270}
271
272pub fn identifiers() -> impl Iterator<Item = &'static str> {
274 INDEX.iter().map(|(n, _)| *n)
275}
276
277struct Reader<'a> {
278 s: &'a [u8],
279 pos: usize,
280}
281
282impl Reader<'_> {
283 fn u8(&mut self) -> Option<u8> {
284 let b = *self.s.get(self.pos)?;
285 self.pos += 1;
286 Some(b)
287 }
288
289 fn u32(&mut self) -> Option<u32> {
290 let b = self.s.get(self.pos..self.pos + 4)?;
291 self.pos += 4;
292 Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
293 }
294
295 fn i64(&mut self) -> Option<i64> {
296 let b = self.s.get(self.pos..self.pos + 8)?;
297 self.pos += 8;
298 Some(i64::from_be_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]))
299 }
300
301 fn skip(&mut self, n: usize) {
302 self.pos += n;
303 }
304
305 fn bytes(&mut self, n: usize) -> Option<&[u8]> {
306 let b = self.s.get(self.pos..self.pos + n)?;
307 self.pos += n;
308 Some(b)
309 }
310}
311
312fn parse_zone(s: &[u8]) -> Option<ZoneData> {
314 let mut r = Reader { s, pos: 0 };
315 if s.get(0..3)? != b"PHP" {
317 return None;
318 }
319 let version = s.get(3)?.wrapping_sub(b'0');
320 if !(2..=4).contains(&version) {
321 return None;
322 }
323 r.skip(4);
324 let bc = r.u8()? == 1;
325 let cc = r.bytes(2)?;
326 let country_code = [cc[0], cc[1]];
327 r.skip(13);
328 let h32: Vec<u32> = (0..6).map(|_| r.u32()).collect::<Option<_>>()?;
330 let (isgmt, isstd, leap, time, typ, chr) = (h32[0], h32[1], h32[2], h32[3], h32[4], h32[5]);
331 r.skip(time as usize * 5);
332 r.skip(typ as usize * 6 + chr as usize + leap as usize * 8 + isstd as usize + isgmt as usize);
333 let magic = r.bytes(5)?;
335 if !(magic == b"TZif2" || magic == b"TZif3" || magic == b"TZif4") {
336 return None;
337 }
338 r.skip(15);
339 let h64: Vec<u32> = (0..6).map(|_| r.u32()).collect::<Option<_>>()?;
340 let (isgmt, isstd, leap, time, typ, chr) = (h64[0], h64[1], h64[2], h64[3], h64[4], h64[5]);
341 let trans: Vec<i64> = (0..time).map(|_| r.i64()).collect::<Option<_>>()?;
342 let trans_idx = r.bytes(time as usize)?.to_vec();
343 let mut types = Vec::with_capacity(typ as usize + 2);
344 for _ in 0..typ {
345 let b = r.bytes(6)?;
346 types.push(TimeType {
347 offset: i32::from_be_bytes([b[0], b[1], b[2], b[3]]),
348 isdst: b[4] != 0,
349 abbr_idx: b[5] as usize,
350 });
351 }
352 let mut abbrs = r.bytes(chr as usize)?.to_vec();
353 r.skip(leap as usize * 12 + isstd as usize + isgmt as usize);
354 r.skip(1);
356 let rest = &s[r.pos..];
357 let end = rest.iter().position(|&c| c == b'\n')?;
358 let posix_string = &rest[..end];
359 let posix = if posix_string.is_empty() { None } else { integrate_posix(posix_string, &mut types, &mut abbrs) };
360 Some(ZoneData { trans, trans_idx, types, abbrs, posix, bc, country_code })
361}
362
363fn integrate_posix(s: &[u8], types: &mut Vec<TimeType>, abbrs: &mut Vec<u8>) -> Option<Posix> {
365 let parsed = parse_posix(s)?;
366 let find = |types: &[TimeType], abbrs: &[u8], offset: i64, isdst: bool, abbr: &[u8]| {
367 types.iter().position(|t| {
368 let a = &abbrs[t.abbr_idx.min(abbrs.len())..];
369 let a = &a[..a.iter().position(|&c| c == 0).unwrap_or(a.len())];
370 i64::from(t.offset) == offset && t.isdst == isdst && a == abbr
371 })
372 };
373 let add = |types: &mut Vec<TimeType>, abbrs: &mut Vec<u8>, offset: i64, isdst: bool, abbr: &[u8]| {
374 let idx = abbrs.len();
375 abbrs.extend_from_slice(abbr);
376 abbrs.push(0);
377 types.push(TimeType { offset: offset as i32, isdst, abbr_idx: idx });
378 types.len() - 1
379 };
380 let std = match find(types, abbrs, parsed.posix.std_offset, false, &parsed.std) {
381 Some(i) => i,
382 None => {
383 let i = add(types, abbrs, parsed.posix.std_offset, false, &parsed.std);
384 return Some(Posix { type_index_std: i, type_index_dst: 0, ..parsed.posix });
385 }
386 };
387 let Some(dst_name) = &parsed.dst else {
388 return Some(Posix { type_index_std: std, type_index_dst: 0, ..parsed.posix });
389 };
390 let dst = match find(types, abbrs, parsed.posix.dst_offset, true, dst_name) {
391 Some(i) => i,
392 None => add(types, abbrs, parsed.posix.dst_offset, true, dst_name),
393 };
394 Some(Posix { type_index_std: std, type_index_dst: dst, ..parsed.posix })
395}
396
397struct ParsedPosix {
398 std: Vec<u8>,
399 dst: Option<Vec<u8>>,
400 posix: Posix,
401}
402
403fn parse_posix(s: &[u8]) -> Option<ParsedPosix> {
405 let mut p = 0usize;
406 let at = |p: usize| s.get(p).copied().unwrap_or(0);
407 let description = |p: &mut usize| -> Option<Vec<u8>> {
408 if at(*p) == b'<' {
409 *p += 1;
410 let begin = *p;
411 while at(*p) != 0 && at(*p) != b'>' {
412 *p += 1;
413 }
414 if at(*p) == 0 {
415 return None;
416 }
417 let end = *p;
418 *p += 1;
419 if end - begin < 1 {
420 return None;
421 }
422 Some(s[begin..end].to_vec())
423 } else {
424 let begin = *p;
425 while at(*p).is_ascii_alphabetic() {
426 *p += 1;
427 }
428 if *p - begin < 1 {
429 return None;
430 }
431 Some(s[begin..*p].to_vec())
432 }
433 };
434 let number = |p: &mut usize| -> Option<i64> {
435 let begin = *p;
436 while at(*p) == b'0' {
437 *p += 1;
438 }
439 let mut acc: i32 = 0;
440 while at(*p).is_ascii_digit() {
441 acc = acc.wrapping_mul(10).wrapping_add(i32::from(at(*p) - b'0'));
442 *p += 1;
443 }
444 if begin == *p { None } else { Some(i64::from(acc)) }
445 };
446 let offset = |p: &mut usize| -> Option<i64> {
447 let mut bias = 1;
448 if at(*p) == b'+' {
449 *p += 1;
450 } else if at(*p) == b'-' {
451 bias = -1;
452 *p += 1;
453 }
454 let begin = *p;
455 let hours = number(p)?;
456 let mut minutes = 0;
457 let mut seconds = 0;
458 if at(*p) == b':' {
459 *p += 1;
460 minutes = number(p)?;
461 }
462 if at(*p) == b':' {
463 *p += 1;
464 seconds = number(p)?;
465 }
466 if begin == *p {
467 return None;
468 }
469 Some(-bias * (hours * 3600 + minutes * 60 + seconds))
470 };
471 let transition = |p: &mut usize| -> Option<TransSpec> {
472 let mut spec = TransSpec { kind: TransKind::JulianFeb29, days: 0, month: 0, week: 0, dow: 0, hour: 7200 };
473 if at(*p) == b'M' {
474 *p += 1;
475 spec.kind = TransKind::Mwd;
476 spec.month = number(p)?;
477 if at(*p) != b'.' {
478 return None;
479 }
480 *p += 1;
481 spec.week = number(p)?;
482 if at(*p) != b'.' {
483 return None;
484 }
485 *p += 1;
486 spec.dow = number(p)?;
487 } else {
488 if at(*p) == b'J' {
489 spec.kind = TransKind::JulianNoFeb29;
490 *p += 1;
491 }
492 spec.days = number(p)?;
493 }
494 if at(*p) == b'/' {
495 *p += 1;
496 spec.hour = -offset(p)?;
497 }
498 Some(spec)
499 };
500
501 let std = description(&mut p)?;
502 let std_offset = offset(&mut p)?;
503 let mut posix =
504 Posix { std_offset, dst_offset: 0, dst_begin: None, dst_end: None, type_index_std: 0, type_index_dst: 0 };
505 if at(p) == 0 {
506 return Some(ParsedPosix { std, dst: None, posix });
507 }
508 posix.dst_offset = std_offset + 3600;
509 let dst = description(&mut p)?;
510 if at(p) != b',' && at(p) != 0 {
511 posix.dst_offset = offset(&mut p)?;
512 }
513 if at(p) != b',' {
514 return None;
515 }
516 p += 1;
517 posix.dst_begin = Some(transition(&mut p)?);
518 if at(p) != b',' {
519 return None;
520 }
521 p += 1;
522 posix.dst_end = Some(transition(&mut p)?);
523 if at(p) != 0 {
524 return None;
525 }
526 Some(ParsedPosix { std, dst: Some(dst), posix })
527}
528
529const MONTH_LENGTHS: [[i32; 12]; 2] =
530 [[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]];
531
532fn calc_transition(spec: &TransSpec, year: i64) -> i64 {
534 let leap = usize::from(super::timelib::is_leap(year));
535 match spec.kind {
536 TransKind::JulianNoFeb29 => {
537 let mut value = spec.days - 1;
538 if leap == 1 && spec.days >= 60 {
539 value += 1;
540 }
541 value * 86400
542 }
543 TransKind::JulianFeb29 => spec.days * 86400,
544 TransKind::Mwd => {
545 let month = spec.month as i32;
546 let m1 = (month + 9) % 12 + 1;
547 let yy0 = if month <= 2 { year.wrapping_sub(1) as i32 } else { year as i32 };
548 let yy1 = yy0 / 100;
549 let yy2 = yy0 % 100;
550 let mut dow = ((26 * m1 - 2) / 10 + 1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
551 if dow < 0 {
552 dow += 7;
553 }
554 let mut d = spec.dow as i32 - dow;
555 if d < 0 {
556 d += 7;
557 }
558 let ml = |m: i32| MONTH_LENGTHS[leap].get((m - 1) as usize).copied().unwrap_or(0);
559 let mut i = 1;
560 while i64::from(i) < spec.week {
561 if d + 7 >= ml(month) {
562 break;
563 }
564 d += 7;
565 i += 1;
566 }
567 let mut value = i64::from(d) * 86400;
568 for m in 0..(month - 1).max(0) {
569 value += i64::from(MONTH_LENGTHS[leap][m as usize]) * 86400;
570 }
571 value
572 }
573 }
574}
575
576fn ts_at_start_of_year(year: i64) -> i64 {
578 let count = |y: i64| {
579 let y = y - 1;
580 y / 4 - y / 100 + y / 400
581 };
582 86400i64
583 .wrapping_mul((year.wrapping_sub(1970)).wrapping_mul(365).wrapping_add(count(year)).wrapping_sub(count(1970)))
584}
585
586#[derive(Debug, Clone, Copy, PartialEq, Eq)]
588pub struct Abbreviation {
589 pub name: &'static str,
591 pub dst: bool,
593 pub gmtoffset: i32,
595 pub full_tz_name: Option<&'static str>,
597}
598
599fn row(r: &Row) -> Abbreviation {
600 Abbreviation { name: r.0, dst: r.1 != 0, gmtoffset: r.2, full_tz_name: r.3 }
601}
602
603pub fn abbr_search(word: &[u8], gmtoffset: i64, isdst: i32) -> Option<Abbreviation> {
607 if strcasecmp(b"utc", word) == 0 || strcasecmp(b"gmt", word) == 0 {
608 return Some(Abbreviation { name: "utc", dst: false, gmtoffset: 0, full_tz_name: Some("UTC") });
609 }
610 let mut first = None;
611 for r in TIMEZONEMAP.iter() {
612 if strcasecmp(word, r.0.as_bytes()) == 0 {
613 if first.is_none() {
614 first = Some(row(r));
615 if gmtoffset == -1 {
616 return first;
617 }
618 }
619 if i64::from(r.2) == gmtoffset {
620 return Some(row(r));
621 }
622 }
623 }
624 if first.is_some() {
625 return first;
626 }
627 FALLBACKMAP.iter().find(|r| i64::from(r.2) == gmtoffset && r.1 == isdst).map(row)
628}
629
630pub fn abbreviations() -> impl Iterator<Item = Abbreviation> {
632 TIMEZONEMAP.iter().map(row)
633}
634
635#[cfg(test)]
636mod tests {
637 use super::*;
638
639 #[test]
640 fn zones_resolve_like_php() {
641 let paris = TzInfo::get("europe/paris").unwrap();
642 assert_eq!(paris.name(), "europe/paris");
643 let i = paris.info(1719835200);
645 assert_eq!((i.offset, i.is_dst, i.abbr.as_str()), (7200, true, "CEST"));
646 let i = paris.info(1704110400);
647 assert_eq!((i.offset, i.is_dst, i.abbr.as_str()), (3600, false, "CET"));
648 assert!(TzInfo::get("Europe/Pariss").is_none());
649 let utc = TzInfo::get("UTC").unwrap();
650 assert_eq!(utc.info(0).abbr, "UTC");
651 assert_eq!(version(), "2026.5");
652 }
653
654 #[test]
655 fn abbreviations_like_timelib() {
656 let est = abbr_search(b"EST", -1, 0).unwrap();
657 assert_eq!((est.gmtoffset, est.dst), (-18000, false));
658 assert_eq!(abbr_search(b"utc", -1, 0).unwrap().full_tz_name, Some("UTC"));
659 assert!(abbr_search(b"xyz", -1, 0).is_none());
660 }
661}