tzf_rs/lib.rs
1//! Fast timezone finder for Rust: convert (longitude, latitude) coordinates
2//! to timezone names, offline.
3//!
4//! Version 2 is protobuf-free: the data source is the TZF embedded binary
5//! format (`.tzb`) shipped by [tzf-dist], and two finder mechanisms consume
6//! it:
7//!
8//! - [`DefaultFinder`] — the recommended general-purpose finder. Expands the
9//! file's geometry into materialized polygons at load time and answers most
10//! queries from the FUZZY preindex tiles, falling back to exact
11//! point-in-polygon for boundary cases.
12//! - [`EmbeddedFinder`] — the low-memory finder. Queries the `.tzb` bytes in
13//! place (no expansion; roughly the file size plus a small open-time index
14//! of chunk skip blocks and per-group latitude stripes, ~100 KB on lite),
15//! with the same FUZZY fast path. Queries are slower than [`DefaultFinder`];
16//! results are identical.
17//!
18//! ```rust
19//! use tzf_rs::DefaultFinder;
20//!
21//! let finder = DefaultFinder::new();
22//! assert_eq!("Asia/Shanghai", finder.get_tz_name(116.3883, 39.9289));
23//! ```
24//!
25//! Creating a finder is expensive — build one and share it (e.g. via
26//! `std::sync::LazyLock`).
27//!
28//! [tzf-dist]: https://github.com/ringsaturn/tzf-dist
29#![cfg_attr(docsrs, feature(doc_cfg))]
30
31/// Compiles and runs every ```` ```rust ```` block in `README.md` as a doctest,
32/// so the README's samples cannot drift from the API. Gated on the features
33/// those samples need; `cargo test --features bundled,export-geojson` (the
34/// `cargo test-all` alias used by `make ci`) covers it.
35#[cfg(all(doctest, feature = "bundled", feature = "export-geojson"))]
36#[doc = include_str!("../README.md")]
37struct ReadmeDoctests;
38
39use std::borrow::Cow;
40use std::f64::consts::PI;
41
42#[cfg(all(feature = "bundled", feature = "full"))]
43compile_error!(
44 "feature `bundled` is mutually exclusive with the git-only data feature \
45 `full`; add `default-features = false` when enabling it"
46);
47
48mod finder;
49mod tzb;
50
51#[cfg(feature = "export-geojson")]
52mod geojson;
53#[cfg(feature = "export-geojson")]
54pub use geojson::{
55 BoundaryFile, FeatureItem, GeometryDefine, MultiPolygonCoordinates, PolygonCoordinates,
56 PropertiesDefine,
57};
58
59pub use tzb::Error;
60
61use finder::{DenseGrid, FuzzyIndex, PolyFinder, assemble_items};
62use tzb::Reader;
63
64#[cfg(feature = "bundled")]
65use tzf_dist::load_lite_tzb;
66#[cfg(all(not(feature = "bundled"), feature = "full"))]
67use tzf_dist_git::load_lite_tzb;
68
69/// The recommended finder: FUZZY preindex fast path over materialized
70/// polygon geometry, loaded from a `.tzb` file.
71///
72/// `get_tz_name` answers from the preindex tile when one covers the point
73/// (the vast majority of queries) and falls back to exact point-in-polygon
74/// otherwise; `get_tz_names` always uses the polygon scan, as the
75/// polygon-exact escape hatch. Files without a FUZZY section get the plain
76/// polygon finder.
77pub struct DefaultFinder {
78 fuzzy: Option<FuzzyIndex>,
79 finder: PolyFinder,
80}
81
82impl DefaultFinder {
83 /// Creates the finder from the bundled tzf-dist lite `.tzb` data.
84 ///
85 /// # Panics
86 ///
87 /// Panics when the embedded dataset is malformed — the release pipeline
88 /// validates it, so this only fires on a broken build.
89 ///
90 /// ```rust
91 /// use tzf_rs::DefaultFinder;
92 /// let finder = DefaultFinder::new();
93 /// assert_eq!("Asia/Shanghai", finder.get_tz_name(116.3883, 39.9289));
94 /// ```
95 #[cfg(any(feature = "bundled", feature = "full"))]
96 #[must_use]
97 pub fn new() -> Self {
98 Self::from_tzb(load_lite_tzb()).expect("tzf-dist lite.tzb is validated at release")
99 }
100
101 /// Creates the finder from the full-precision `.tzb` dataset (~14 MB,
102 /// no topology simplification). Higher fidelity, larger memory footprint.
103 ///
104 /// Requires the `full` feature, which is git-only:
105 /// ```toml
106 /// tzf-rs = { git = "https://github.com/ringsaturn/tzf-rs", features = ["full"], default-features = false }
107 /// ```
108 ///
109 /// # Panics
110 ///
111 /// Panics when the embedded dataset is malformed (release-validated).
112 #[cfg(feature = "full")]
113 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
114 #[must_use]
115 pub fn new_full() -> Self {
116 Self::from_tzb(tzf_dist_git::load_full_tzb())
117 .expect("tzf-dist full.tzb is validated at release")
118 }
119
120 /// Builds a finder from TZF embedded binary (`.tzb`) bytes by expanding
121 /// the geometry into the materialized polygon engine at load time. `data`
122 /// is only read during loading. When the file carries a FUZZY section it
123 /// becomes the `get_tz_name` fast path.
124 ///
125 /// # Errors
126 ///
127 /// Returns [`Error`] when the bytes are not a structurally valid
128 /// E-profile (`.tzb`) file.
129 pub fn from_tzb(data: &[u8]) -> Result<Self, Error> {
130 let reader = Reader::open(Cow::Borrowed(data))?;
131 let fuzzy = FuzzyIndex::from_reader(&reader)?;
132 let grid = DenseGrid::from_reader(&reader);
133 let expanded = reader.expand()?;
134 Ok(Self {
135 fuzzy,
136 finder: PolyFinder {
137 items: assemble_items(expanded.names, expanded.polygons),
138 grid,
139 version: expanded.version,
140 },
141 })
142 }
143
144 /// Returns the first matching timezone name, or `""` when no timezone
145 /// covers the point.
146 ///
147 /// ```rust
148 /// use tzf_rs::DefaultFinder;
149 /// let finder = DefaultFinder::new();
150 /// assert_eq!("Asia/Shanghai", finder.get_tz_name(116.3883, 39.9289));
151 /// ```
152 #[must_use]
153 pub fn get_tz_name(&self, lng: f64, lat: f64) -> &str {
154 self.get_tz_index(lng, lat)
155 .map_or("", |i| self.finder.items[i].name.as_str())
156 }
157
158 /// Returns the position in [`timezonenames`](Self::timezonenames) of the
159 /// timezone [`get_tz_name`](Self::get_tz_name) would return, or `None`
160 /// when no timezone covers the point.
161 ///
162 /// For batch callers: resolving names once and indexing them per point
163 /// avoids handling a string per lookup.
164 ///
165 /// ```rust
166 /// use tzf_rs::DefaultFinder;
167 /// let finder = DefaultFinder::new();
168 /// let names = finder.timezonenames();
169 /// let idx = finder.get_tz_index(116.3883, 39.9289).unwrap();
170 /// assert_eq!("Asia/Shanghai", names[idx]);
171 /// ```
172 #[must_use]
173 pub fn get_tz_index(&self, lng: f64, lat: f64) -> Option<usize> {
174 if let Some(fuzzy) = &self.fuzzy
175 && let Some(idx) = fuzzy.get(lng, lat)
176 {
177 return Some(usize::from(idx));
178 }
179 self.finder.get_index(lng, lat)
180 }
181
182 /// Returns all matching timezone names (overlapping areas produce more
183 /// than one), sorted lexicographically. Always polygon-exact.
184 ///
185 /// ```rust
186 /// use tzf_rs::DefaultFinder;
187 /// let finder = DefaultFinder::new();
188 /// println!("{:?}", finder.get_tz_names(116.3883, 39.9289));
189 /// ```
190 #[must_use]
191 pub fn get_tz_names(&self, lng: f64, lat: f64) -> Vec<&str> {
192 self.finder.get_tz_names(lng, lat)
193 }
194
195 /// Returns all timezone names in the dataset.
196 ///
197 /// ```rust
198 /// use tzf_rs::DefaultFinder;
199 /// let finder = DefaultFinder::new();
200 /// println!("{:?}", finder.timezonenames());
201 /// ```
202 #[must_use]
203 pub fn timezonenames(&self) -> Vec<&str> {
204 self.finder.timezonenames()
205 }
206
207 /// Returns the dataset release this finder was built from (e.g. `2026c`).
208 ///
209 /// ```rust
210 /// use tzf_rs::DefaultFinder;
211 /// let finder = DefaultFinder::new();
212 /// println!("{:?}", finder.data_version());
213 /// ```
214 #[must_use]
215 pub fn data_version(&self) -> &str {
216 &self.finder.version
217 }
218
219 /// Converts all timezone boundaries to a GeoJSON FeatureCollection.
220 #[cfg(feature = "export-geojson")]
221 #[cfg_attr(docsrs, doc(cfg(feature = "export-geojson")))]
222 #[must_use]
223 pub fn to_geojson(&self) -> BoundaryFile {
224 geojson::collection(
225 self.finder
226 .items
227 .iter()
228 .map(geojson::feature_from_item)
229 .collect(),
230 )
231 }
232
233 /// Converts one timezone's boundaries to a GeoJSON FeatureCollection.
234 /// Returns `None` when the dataset does not contain the name.
235 #[cfg(feature = "export-geojson")]
236 #[cfg_attr(docsrs, doc(cfg(feature = "export-geojson")))]
237 #[must_use]
238 pub fn get_tz_geojson(&self, timezone_name: &str) -> Option<BoundaryFile> {
239 let features: Vec<_> = self
240 .finder
241 .items
242 .iter()
243 .filter(|item| item.name == timezone_name)
244 .map(geojson::feature_from_item)
245 .collect();
246 if features.is_empty() {
247 None
248 } else {
249 Some(geojson::collection(features))
250 }
251 }
252
253 /// Converts one timezone's FUZZY preindex tiles to a GeoJSON
254 /// FeatureCollection: one Feature whose MultiPolygon holds each tile's
255 /// bounding rectangle — the area where `get_tz_name` answers from the
256 /// preindex fast path instead of exact point-in-polygon. Tiles are
257 /// ordered coarsest zoom first.
258 ///
259 /// Returns `None` when the file carries no FUZZY section, the dataset
260 /// does not contain the name, or no preindex tile names it.
261 #[cfg(feature = "export-geojson")]
262 #[cfg_attr(docsrs, doc(cfg(feature = "export-geojson")))]
263 #[must_use]
264 pub fn get_tz_preindex_geojson(&self, timezone_name: &str) -> Option<BoundaryFile> {
265 let fuzzy = self.fuzzy.as_ref()?;
266 // The same name may map to more than one directory item; a preindex
267 // tile may name any of them.
268 let indices: Vec<u16> = self
269 .finder
270 .items
271 .iter()
272 .enumerate()
273 .filter(|(_, item)| item.name == timezone_name)
274 .filter_map(|(i, _)| u16::try_from(i).ok())
275 .collect();
276 if indices.is_empty() {
277 return None;
278 }
279 let keys = fuzzy.tile_keys_for(&indices);
280 if keys.is_empty() {
281 return None;
282 }
283 Some(geojson::collection(vec![geojson::feature_from_tile_keys(
284 timezone_name.to_string(),
285 &keys,
286 )]))
287 }
288
289 /// Converts the whole FUZZY preindex to a GeoJSON FeatureCollection: one
290 /// Feature per timezone that owns at least one tile, in dataset order; a
291 /// boundary tile appears in every timezone it names. Returns `None` when
292 /// the file carries no FUZZY section.
293 #[cfg(feature = "export-geojson")]
294 #[cfg_attr(docsrs, doc(cfg(feature = "export-geojson")))]
295 #[must_use]
296 pub fn to_preindex_geojson(&self) -> Option<BoundaryFile> {
297 let fuzzy = self.fuzzy.as_ref()?;
298 let mut grouped = fuzzy.tile_keys_grouped();
299 let features = self
300 .finder
301 .items
302 .iter()
303 .enumerate()
304 .filter_map(|(i, item)| {
305 let keys = grouped.remove(&u16::try_from(i).ok()?)?;
306 Some(geojson::feature_from_tile_keys(item.name.clone(), &keys))
307 })
308 .collect();
309 Some(geojson::collection(features))
310 }
311}
312
313#[cfg(any(feature = "bundled", feature = "full"))]
314impl Default for DefaultFinder {
315 fn default() -> Self {
316 Self::new()
317 }
318}
319
320/// The low-memory finder: queries TZF embedded binary (`.tzb`) bytes in
321/// place, without expanding the geometry. Total footprint is roughly the file
322/// itself (the bundled lite data is ~4 MB) plus the timezone names and a
323/// 16-bytes-per-16-chunks skip table built while validating the file at open
324/// (~6 KB for lite, ~20 KB for full at the encoder's default 256-point
325/// chunks).
326///
327/// `get_tz_name` consults the file's FUZZY preindex first and falls back to
328/// the compressed-geometry scan; results match [`DefaultFinder`] over the
329/// same file, only slower (microseconds instead of hundreds of nanoseconds
330/// on boundary queries).
331pub struct EmbeddedFinder {
332 reader: Reader<'static>,
333 names: Vec<String>,
334}
335
336impl EmbeddedFinder {
337 /// Creates the finder over the bundled tzf-dist lite `.tzb` data,
338 /// borrowed in place from the executable's read-only data segment.
339 ///
340 /// # Panics
341 ///
342 /// Panics when the embedded dataset is malformed (release-validated).
343 #[cfg(any(feature = "bundled", feature = "full"))]
344 #[must_use]
345 pub fn new() -> Self {
346 Self::from_tzb(load_lite_tzb()).expect("tzf-dist lite.tzb is validated at release")
347 }
348
349 /// Builds a finder that queries `data` in place. Accepts borrowed
350 /// `&'static [u8]` (e.g. `include_bytes!`) without copying, or an owned
351 /// `Vec<u8>` (e.g. a file read at startup).
352 ///
353 /// # Errors
354 ///
355 /// Returns [`Error`] when the bytes are not a structurally valid
356 /// E-profile (`.tzb`) file. Memory images (`.tzm`) are rejected with
357 /// [`Error::Profile`] — they exist for the Go runtime and offer no
358 /// benefit here.
359 pub fn from_tzb(data: impl Into<Cow<'static, [u8]>>) -> Result<Self, Error> {
360 let reader = Reader::open(data.into())?;
361 let names = (0..reader.timezone_count())
362 .map(|i| reader.name(i).map(str::to_string))
363 .collect::<Result<Vec<_>, _>>()?;
364 Ok(Self { reader, names })
365 }
366
367 /// Returns the first matching timezone name, or `""` when no timezone
368 /// covers the point.
369 ///
370 /// ```rust
371 /// use tzf_rs::EmbeddedFinder;
372 /// let finder = EmbeddedFinder::new();
373 /// assert_eq!("Asia/Shanghai", finder.get_tz_name(116.3883, 39.9289));
374 /// ```
375 #[must_use]
376 pub fn get_tz_name(&self, lng: f64, lat: f64) -> &str {
377 if self.reader.has_fuzzy()
378 && let Ok(Some(idx)) = self.reader.fuzzy_lookup(lng, lat)
379 {
380 return &self.names[idx as usize];
381 }
382 match self.reader.lookup(lng, lat) {
383 Ok(Some(idx)) => &self.names[idx as usize],
384 _ => "",
385 }
386 }
387
388 /// Returns all matching timezone names, sorted lexicographically. Always
389 /// polygon-exact.
390 #[must_use]
391 pub fn get_tz_names(&self, lng: f64, lat: f64) -> Vec<&str> {
392 let mut indices = Vec::with_capacity(self.reader.lookup_buffer_size());
393 if self.reader.lookup_into(lng, lat, &mut indices).is_err() {
394 return Vec::new();
395 }
396 indices
397 .into_iter()
398 .map(|idx| self.names[idx as usize].as_str())
399 .collect()
400 }
401
402 /// Returns all timezone names in the dataset.
403 #[must_use]
404 pub fn timezonenames(&self) -> Vec<&str> {
405 self.names.iter().map(String::as_str).collect()
406 }
407
408 /// Returns the dataset release this finder was built from (e.g. `2026c`).
409 #[must_use]
410 pub fn data_version(&self) -> &str {
411 self.reader.data_version()
412 }
413
414 /// Converts all timezone boundaries to a GeoJSON FeatureCollection.
415 ///
416 /// Unlike [`DefaultFinder`], which exports polygons it already holds,
417 /// this decodes the whole file's geometry on demand — roughly the cost of
418 /// loading an expanded finder. A timezone that fails to decode is
419 /// omitted; use [`get_tz_geojson`] when the error matters.
420 ///
421 /// [`get_tz_geojson`]: EmbeddedFinder::get_tz_geojson
422 #[cfg(feature = "export-geojson")]
423 #[cfg_attr(docsrs, doc(cfg(feature = "export-geojson")))]
424 #[must_use]
425 pub fn to_geojson(&self) -> BoundaryFile {
426 let features = (0..self.names.len())
427 .filter_map(|i| {
428 let polys = self.reader.expand_timezone(i as u32).ok()?;
429 Some(geojson::feature_from_expanded(
430 self.names[i].clone(),
431 &polys,
432 ))
433 })
434 .collect();
435 geojson::collection(features)
436 }
437
438 /// Converts one timezone's boundaries to a GeoJSON FeatureCollection,
439 /// decoding only that timezone's rings. Returns `None` when the dataset
440 /// does not contain the name or its geometry fails to decode.
441 #[cfg(feature = "export-geojson")]
442 #[cfg_attr(docsrs, doc(cfg(feature = "export-geojson")))]
443 #[must_use]
444 pub fn get_tz_geojson(&self, timezone_name: &str) -> Option<BoundaryFile> {
445 let mut features = Vec::new();
446 for (i, name) in self.names.iter().enumerate() {
447 if name != timezone_name {
448 continue;
449 }
450 let polys = self.reader.expand_timezone(i as u32).ok()?;
451 features.push(geojson::feature_from_expanded(name.clone(), &polys));
452 }
453 if features.is_empty() {
454 None
455 } else {
456 Some(geojson::collection(features))
457 }
458 }
459
460 /// Converts one timezone's FUZZY preindex tiles to a GeoJSON
461 /// FeatureCollection; see [`DefaultFinder::get_tz_preindex_geojson`].
462 /// Results match [`DefaultFinder`] over the same file.
463 #[cfg(feature = "export-geojson")]
464 #[cfg_attr(docsrs, doc(cfg(feature = "export-geojson")))]
465 #[must_use]
466 pub fn get_tz_preindex_geojson(&self, timezone_name: &str) -> Option<BoundaryFile> {
467 if !self.reader.has_fuzzy() {
468 return None;
469 }
470 let indices: Vec<u16> = self
471 .names
472 .iter()
473 .enumerate()
474 .filter(|(_, name)| name.as_str() == timezone_name)
475 .filter_map(|(i, _)| u16::try_from(i).ok())
476 .collect();
477 if indices.is_empty() {
478 return None;
479 }
480 // The FUZZY key array is stored sorted, so the filtered keys keep the
481 // coarsest-zoom-first order DefaultFinder produces by sorting.
482 let entries = self.reader.fuzzy_entries().ok()?;
483 let keys: Vec<u64> = entries
484 .iter()
485 .filter(|(_, idxs)| idxs.iter().any(|i| indices.contains(i)))
486 .map(|(key, _)| *key)
487 .collect();
488 if keys.is_empty() {
489 return None;
490 }
491 Some(geojson::collection(vec![geojson::feature_from_tile_keys(
492 timezone_name.to_string(),
493 &keys,
494 )]))
495 }
496
497 /// Converts the whole FUZZY preindex to a GeoJSON FeatureCollection; see
498 /// [`DefaultFinder::to_preindex_geojson`]. Results match
499 /// [`DefaultFinder`] over the same file.
500 #[cfg(feature = "export-geojson")]
501 #[cfg_attr(docsrs, doc(cfg(feature = "export-geojson")))]
502 #[must_use]
503 pub fn to_preindex_geojson(&self) -> Option<BoundaryFile> {
504 if !self.reader.has_fuzzy() {
505 return None;
506 }
507 let entries = self.reader.fuzzy_entries().ok()?;
508 let mut grouped: std::collections::HashMap<u16, Vec<u64>> =
509 std::collections::HashMap::new();
510 for (key, idxs) in &entries {
511 for &idx in idxs {
512 grouped.entry(idx).or_default().push(*key);
513 }
514 }
515 let features = (0..self.names.len())
516 .filter_map(|i| {
517 let keys = grouped.remove(&u16::try_from(i).ok()?)?;
518 Some(geojson::feature_from_tile_keys(
519 self.names[i].clone(),
520 &keys,
521 ))
522 })
523 .collect();
524 Some(geojson::collection(features))
525 }
526}
527
528#[cfg(any(feature = "bundled", feature = "full"))]
529impl Default for EmbeddedFinder {
530 fn default() -> Self {
531 Self::new()
532 }
533}
534
535/// deg2num is used to convert longitude, latitude to [Slippy map tilenames]
536/// under specific zoom level.
537///
538/// [Slippy map tilenames]: https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
539///
540/// Example:
541///
542/// ```rust
543/// use tzf_rs::deg2num;
544/// let ret = deg2num(116.3883, 39.9289, 7);
545/// assert_eq!((105, 48), ret);
546/// ```
547#[must_use]
548#[allow(
549 clippy::cast_precision_loss,
550 clippy::cast_possible_truncation,
551 clippy::similar_names
552)]
553pub fn deg2num(lng: f64, lat: f64, zoom: i64) -> (i64, i64) {
554 let n = (1i64 << zoom) as f64;
555 let lat_rad = lat.to_radians();
556 let xtile = (lng / 360.0 + 0.5) * n;
557 let ytile = (1.0 - lat_rad.tan().asinh() / PI) / 2.0 * n;
558
559 // Possible precision loss here
560 (xtile as i64, ytile as i64)
561}