//! IANA time zone database access and local-time resolution. //! //! The zoneinfo directory is compiled by `scripts/fetch-deps.sh` with //! `PACKRATDATA=backzone PACKRATLIST=zone.tab`: every zone listed in //! `zone.tab` keeps its own history before 1970 instead of being linked to //! a zone that merely agrees since 1970 (e.g. Europe/Oslo is not folded into //! Europe/Berlin, so Norway's 1959-1965 summer time is preserved). use std::collections::HashMap; use std::fs; use std::path::Path; use jiff::Timestamp; use jiff::civil::DateTime; use jiff::tz::{AmbiguousOffset, Offset, TimeZone, TimeZoneDatabase}; use serde::{Deserialize, Serialize}; use crate::GeoError; /// What to do when a local time is ambiguous (clocks turned back, the hour /// happens twice) or does not exist (clocks turned forward). #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum AmbiguityPolicy { /// Return an error that explains both possibilities. #[default] Reject, /// Use the offset in effect before the transition (usually summer time in autumn). Earlier, /// Use the offset in effect after the transition. Later, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] pub enum TransitionKind { /// The local time did not exist (clocks turned forward). Gap, /// The local time happened twice (clocks turned back). Fold, } #[derive(Debug, Clone, Serialize)] pub struct Transition { pub kind: TransitionKind, pub offset_before: String, pub offset_after: String, pub resolved_with: AmbiguityPolicy, } #[derive(Debug, Clone, Serialize)] pub struct LocalizedTime { /// IANA zone name; `None` for a fixed offset given in the request. pub zone: Option, /// Local civil time as given. pub local: String, /// The same instant in UTC (RFC 3339). pub utc: String, #[serde(skip)] pub timestamp: Timestamp, pub utc_offset: String, pub utc_offset_seconds: i32, /// Daylight saving (summer) time was in effect. pub dst: bool, /// Zone abbreviation, e.g. CET, CEST, LMT. pub abbreviation: String, #[serde(skip_serializing_if = "Option::is_none")] pub transition: Option, } #[derive(Debug, Clone, Serialize)] pub struct ZoneTabEntry { pub name: String, /// Reference location of the zone (its principal city). pub latitude: f64, pub longitude: f64, #[serde(skip_serializing_if = "Option::is_none")] pub comment: Option, } pub struct TimeZones { db: TimeZoneDatabase, pub version: String, zone_tab: HashMap>, } impl TimeZones { pub fn load(dir: &Path) -> Result { let err = |reason: String| GeoError::Data { what: dir.display().to_string(), reason }; let zone_tab_path = dir.join("zone.tab"); let content = fs::read_to_string(&zone_tab_path).map_err(|e| err(format!("zone.tab: {e}")))?; let mut zone_tab: HashMap> = HashMap::new(); for line in content.lines().filter(|l| !l.starts_with('#') && !l.trim().is_empty()) { let f: Vec<&str> = line.split('\t').collect(); if f.len() < 3 { continue; } let Some((latitude, longitude)) = parse_iso6709(f[1]) else { continue }; zone_tab.entry(f[0].to_string()).or_default().push(ZoneTabEntry { name: f[2].to_string(), latitude, longitude, comment: f.get(3).map(|c| c.to_string()), }); } let db = TimeZoneDatabase::from_dir(dir).map_err(|e| err(e.to_string()))?; let version = fs::read_to_string(dir.join("VERSION")).map(|s| s.trim().to_string()).unwrap_or_default(); let tz = Self { db, version, zone_tab }; // Fail fast on an empty or broken directory. tz.get("Europe/Budapest").map_err(|e| err(e.to_string()))?; Ok(tz) } pub fn get(&self, name: &str) -> Result { self.db.get(name).map_err(|_| GeoError::UnknownTimeZone(name.to_string())) } pub fn exists(&self, name: &str) -> bool { !name.is_empty() && self.db.get(name).is_ok() } /// Zones of a country according to `zone.tab`. pub fn zones_of(&self, iso2: &str) -> &[ZoneTabEntry] { self.zone_tab.get(iso2).map(Vec::as_slice).unwrap_or_default() } /// Converts local civil time in `zone` to an instant. pub fn localize(&self, zone: &str, local: DateTime, policy: AmbiguityPolicy) -> Result { let tz = self.get(zone)?; let ambiguous = tz.to_ambiguous_timestamp(local); let (timestamp, transition) = match ambiguous.offset() { AmbiguousOffset::Unambiguous { offset } => (to_timestamp(local, offset)?, None), AmbiguousOffset::Gap { before, after } | AmbiguousOffset::Fold { before, after } => { let kind = if matches!(ambiguous.offset(), AmbiguousOffset::Gap { .. }) { TransitionKind::Gap } else { TransitionKind::Fold }; let offset = match policy { AmbiguityPolicy::Earlier => before, AmbiguityPolicy::Later => after, AmbiguityPolicy::Reject => { let (datetime, zone) = (local.to_string(), zone.to_string()); let (earlier, later) = (format_offset(before), format_offset(after)); return Err(match kind { TransitionKind::Fold => GeoError::AmbiguousTime { datetime, zone, earlier, later }, TransitionKind::Gap => GeoError::NonexistentTime { datetime, zone, earlier, later }, }); } }; let transition = Transition { kind, offset_before: format_offset(before), offset_after: format_offset(after), resolved_with: policy, }; (to_timestamp(local, offset)?, Some(transition)) } }; let info = tz.to_offset_info(timestamp); let offset = info.offset(); Ok(LocalizedTime { zone: Some(zone.to_string()), local: local.to_string(), utc: timestamp.to_string(), timestamp, utc_offset: format_offset(offset), utc_offset_seconds: offset.seconds(), dst: info.dst().is_dst(), abbreviation: info.abbreviation().to_string(), transition, }) } /// Converts local civil time with an explicitly given UTC offset. pub fn localize_fixed(&self, local: DateTime, offset_seconds: i32) -> Result { let offset = Offset::from_seconds(offset_seconds).map_err(|e| GeoError::InvalidDateTime(e.to_string()))?; let timestamp = to_timestamp(local, offset)?; Ok(LocalizedTime { zone: None, local: local.to_string(), utc: timestamp.to_string(), timestamp, utc_offset: format_offset(offset), utc_offset_seconds: offset_seconds, dst: false, abbreviation: format_offset(offset), transition: None, }) } } fn to_timestamp(local: DateTime, offset: Offset) -> Result { offset.to_timestamp(local).map_err(|e| GeoError::InvalidDateTime(e.to_string())) } /// `+02:00`, or `+01:16:20` when the offset has seconds (local mean time). pub fn format_offset(offset: Offset) -> String { let total = offset.seconds(); let sign = if total < 0 { '-' } else { '+' }; let abs = total.unsigned_abs(); let (h, m, s) = (abs / 3600, (abs / 60) % 60, abs % 60); if s == 0 { format!("{sign}{h:02}:{m:02}") } else { format!("{sign}{h:02}:{m:02}:{s:02}") } } /// Parses an offset like `+02:00`, `-05:30`, `+01:16:20`, `+0200` or `Z`. pub fn parse_offset(text: &str) -> Option { let t = text.trim(); if t.eq_ignore_ascii_case("z") || t.eq_ignore_ascii_case("utc") { return Some(0); } let (sign, rest) = match t.as_bytes().first()? { b'+' => (1, &t[1..]), b'-' => (-1, &t[1..]), _ => return None, }; let parts: Vec<&str> = if rest.contains(':') { rest.split(':').collect() } else if rest.len() == 4 && rest.chars().all(|c| c.is_ascii_digit()) { vec![&rest[..2], &rest[2..]] } else { vec![rest] }; let nums: Vec = parts.iter().map(|p| p.parse::().ok()).collect::>()?; let (h, m, s) = match nums.as_slice() { [h] => (*h, 0, 0), [h, m] => (*h, *m, 0), [h, m, s] => (*h, *m, *s), _ => return None, }; if !(0..=18).contains(&h) || !(0..60).contains(&m) || !(0..60).contains(&s) { return None; } Some(sign * (h * 3600 + m * 60 + s)) } /// Parses ISO 6709 coordinates as used in zone.tab: `+4730+01905` or /// `+404251-0740023`. fn parse_iso6709(s: &str) -> Option<(f64, f64)> { let split = s[1..].find(['+', '-'])? + 1; let (lat, lon) = s.split_at(split); Some((parse_dms(lat, 2)?, parse_dms(lon, 3)?)) } fn parse_dms(s: &str, degree_digits: usize) -> Option { let sign = if s.starts_with('-') { -1.0 } else { 1.0 }; let digits = &s[1..]; let num = |r: std::ops::Range| digits.get(r).and_then(|d| d.parse::().ok()); let d = num(0..degree_digits)?; let m = num(degree_digits..degree_digits + 2)?; let sec = if digits.len() > degree_digits + 2 { num(degree_digits + 2..degree_digits + 4)? } else { 0.0 }; Some(sign * (d + m / 60.0 + sec / 3600.0)) } #[cfg(test)] mod tests { use super::*; #[test] fn iso6709() { let (lat, lon) = parse_iso6709("+4730+01905").unwrap(); assert!((lat - 47.5).abs() < 1e-9 && (lon - (19.0 + 5.0 / 60.0)).abs() < 1e-9); let (lat, lon) = parse_iso6709("+404251-0740023").unwrap(); assert!((lat - 40.714_166).abs() < 1e-5 && (lon + 74.006_388).abs() < 1e-5); } #[test] fn offsets() { assert_eq!(parse_offset("+02:00"), Some(7200)); assert_eq!(parse_offset("-05:30"), Some(-19800)); assert_eq!(parse_offset("+01:16:20"), Some(4580)); assert_eq!(parse_offset("+0100"), Some(3600)); assert_eq!(parse_offset("Z"), Some(0)); assert_eq!(parse_offset("2"), None); assert_eq!(parse_offset("+25:00"), None); assert_eq!(format_offset(Offset::from_seconds(4580).unwrap()), "+01:16:20"); assert_eq!(format_offset(Offset::from_seconds(-12600).unwrap()), "-03:30"); } }