Files
sorsfonalak/crates/geo-tz/src/lib.rs
T

126 lines
4.7 KiB
Rust
Raw Normal View History

//! Offline geography and historical civil time.
//!
//! * [`places`]: country and populated-place lookup from GeoNames dumps.
//! * [`tz`]: IANA time zone database (compiled with `backzone`, so every
//! country keeps its own pre-1970 daylight saving history) and conversion of
//! local civil time to UTC, including DST gaps and folds.
//! * [`Atlas`]: both together, plus time zone selection for a birth place.
pub mod places;
pub mod text;
pub mod tz;
use std::path::Path;
use serde::Serialize;
pub use places::{Country, Place, PlaceIndex, PlaceMatch};
pub use tz::{AmbiguityPolicy, LocalizedTime, TimeZones, TransitionKind};
#[derive(Debug, thiserror::Error)]
pub enum GeoError {
#[error("failed to load {what}: {reason}")]
Data { what: String, reason: String },
#[error("unknown country: {0}")]
UnknownCountry(String),
#[error("no place named '{query}' found in {country}")]
PlaceNotFound { query: String, country: String },
#[error("unknown GeoNames id: {0}")]
UnknownPlaceId(u64),
#[error("place {place} (GeoNames {id}) is in {actual}, not in {expected}")]
PlaceCountryMismatch { id: u64, place: String, actual: String, expected: String },
#[error("unknown time zone: {0}")]
UnknownTimeZone(String),
#[error("no time zone could be determined for {0}")]
NoTimeZone(String),
#[error(
"local time {datetime} occurs twice in {zone} (clocks were turned back): \
offset {earlier} or {later}; set ambiguous_time to \"earlier\" or \"later\""
)]
AmbiguousTime { datetime: String, zone: String, earlier: String, later: String },
#[error(
"local time {datetime} does not exist in {zone} (clocks were turned forward from {earlier} to {later}); \
set ambiguous_time to \"earlier\" or \"later\" to interpret it with the offset before or after the change"
)]
NonexistentTime { datetime: String, zone: String, earlier: String, later: String },
#[error("invalid date/time: {0}")]
InvalidDateTime(String),
}
/// How the time zone of a chart was chosen.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ZoneSource {
/// Given explicitly in the request.
Request,
/// Time zone of the matched GeoNames place.
Place,
/// The country has a single time zone.
Country,
/// Time zone of the nearest populated place in the same country.
NearestPlace,
/// Nearest reference location of the country's zones in `zone.tab`.
ZoneTab,
}
#[derive(Debug, Clone, Serialize)]
pub struct ZoneChoice {
pub zone: String,
pub source: ZoneSource,
}
pub struct Atlas {
pub places: PlaceIndex,
pub zones: TimeZones,
}
impl Atlas {
/// Loads `geonames/` and `zoneinfo/` from the data directory.
pub fn load(data_dir: &Path) -> Result<Self, GeoError> {
let zones = TimeZones::load(&data_dir.join("zoneinfo"))?;
let places = PlaceIndex::load(&data_dir.join("geonames"))?;
Ok(Self { places, zones })
}
/// Chooses the time zone for a birth place.
///
/// Priority: explicit zone > zone of the matched place > the country's only
/// zone > zone of the nearest populated place in the country > nearest
/// `zone.tab` reference point of the country.
pub fn choose_zone(
&self,
country: &Country,
explicit: Option<&str>,
place: Option<&Place>,
coordinates: (f64, f64),
) -> Result<ZoneChoice, GeoError> {
if let Some(zone) = explicit {
self.zones.get(zone)?;
return Ok(ZoneChoice { zone: zone.to_string(), source: ZoneSource::Request });
}
if let Some(p) = place.filter(|p| self.zones.exists(&p.timezone)) {
return Ok(ZoneChoice { zone: p.timezone.clone(), source: ZoneSource::Place });
}
let country_zones = self.zones.zones_of(&country.iso2);
if let [only] = country_zones {
return Ok(ZoneChoice { zone: only.name.clone(), source: ZoneSource::Country });
}
let (lat, lon) = coordinates;
if let Some((nearest, _)) = self.places.nearest(&country.iso2, lat, lon, |p| self.zones.exists(&p.timezone)) {
return Ok(ZoneChoice { zone: nearest.timezone.clone(), source: ZoneSource::NearestPlace });
}
country_zones
.iter()
.min_by(|a, b| {
text::distance_km(lat, lon, a.latitude, a.longitude).total_cmp(&text::distance_km(
lat,
lon,
b.latitude,
b.longitude,
))
})
.map(|z| ZoneChoice { zone: z.name.clone(), source: ZoneSource::ZoneTab })
.ok_or_else(|| GeoError::NoTimeZone(country.name.clone()))
}
}