Rust
The typed engine from Rust: search, reverse, admin, timezones and elevation on an offline pack, with no allocation in a warm query.
teigeodata is written in Rust, and Rust gets the engine itself: typed places, typed IDs and points, and queries that write into buffers you reuse, so a warm query allocates nothing. Every other language reaches the same engine through a generated binding.
Every example on this page ran
The code below is cut from one program, the tour, which CI runs on the released
public pack world-np-lite.tgd (data-2026.11.14.3) and checks line by line against the
output shown here. The output is the same in every language.
Install
[dependencies]
teigeodata-core = { git = "https://github.com/teispace/teigeodata", tag = "v1.0.0" }
teigeodata-engine = { git = "https://github.com/teispace/teigeodata", tag = "v1.0.0" }The minimum Rust version is the one rust-toolchain.toml pins. teigeodata-engine's default
features read packs from files (mmap); teigeodata-sync adds the store (download, verify,
update); the core crates build for no_std targets.
Get a pack
Queries read packs: signed, memory-mapped files of places. This guide uses the world lite pack: the world's countries, first-level units and cities of 5,000 or more, India's districts and statutory towns, and Nepal in full, 172,339 places named in Nepali, Hindi and English (15.6 MB, CC BY 4.0):
curl -LO https://github.com/teispace/teigeodata/releases/download/data-2026.11.14.3/world-np-lite.tgd
shasum -a 256 world-np-lite.tgd # 243ae55509a538b1f61da50994a791cc78e7deb70bb4bf743b9f59d458cbe3f3An app ships a pack inside its bundle, or downloads one when a user needs it. Once the signed catalog is live, the store does that download for you: it verifies every byte and keeps the packs updated.
Read a result
The Rust engine returns typed values, not result blobs: a Place holds its ID, kind, admin
level and point, and the rest (its name, ISO code, elevation, timezone) is read on demand from
the engine, into a buffer you pass. The tour gathers what it prints in one helper:
/// What the tour prints of a place: its name, kind and the rest read on demand.
struct Described {
id: String,
name: String,
kind: &'static str,
level: u8,
lat: f64,
lon: f64,
iso: String,
}
fn describe(engine: &Engine, place: &Place) -> Result<Described, Box<dyn Error>> {
let mut buf = [0u8; 1024];
Ok(Described {
id: place.id.to_string(),
name: engine.name(place, &mut buf)?.unwrap_or_default().to_owned(),
kind: place.kind.map_or("", |k| k.name()),
level: place.admin_level,
lat: place.point.lat_degrees(),
lon: place.point.lon_degrees(),
iso: engine
.iso_code(place)?
.map(|c| c.to_string())
.unwrap_or_default(),
})
}Queries that return several places write into a Vec you own and reuse (hits, near,
places in the tour), with a Scratch for the search's working memory. Points are fixed-point
(Point<E6>, Point<E7>): Point::from_degrees checks the range once, so a query never sees
an invalid coordinate.
If you want the same blobs every binding gets, teigeodata-api wraps this engine with the
binding API (Engine::search returning a result blob).
Open a pack
An Engine holds the packs it answers from, each as a layer. Layer::open maps a pack
file and checks its head; Engine::add adds the layer and returns its LayerId. The engine
answers from every layer at once, and a higher layer wins where two disagree. Opening is cheap:
the head is read and checked, and the block hashes of large sections are proved; each section
is verified against its hash the first time a query reads it.
let mut engine = Engine::new();
engine.add(Layer::open(&pack, LayerOptions::default())?);
println!("layers: {}", engine.layers().len());
// Buffers the queries write into: reuse them, and a warm query allocates nothing.
let mut scratch = Scratch::default();
let (mut hits, mut near, mut places) = (Vec::new(), Vec::new(), Vec::new());layers: 1Layer::from_bytesopens a pack from bytes already in memory (a download, an app asset).Layer::open_rangeopens a pack stored uncompressed inside another file, such as an Android APK.LayerOptionssets the layer'spriority, when sections are verified (Verify::Lazy,EagerorTrusted), whether the file is mapped or read (Load::Map,Load::Read), and which components, languages and outline level to read (installed,installed_parts,outline_level).Engine::removetakes a layer out again by itsLayerId. For an engine that other threads keep querying while layers come and go, seeSharedbelow.
Search by name
Engine::search finds places by name, best first, into a Vec<Hit> you reuse; each Hit
is a Place and its score. It matches every name a place has, in every script, and forgives
spelling: काठमाडौं, Kathmandu and Kathamandu find the same city, and so do typos, missing accents
and abbreviations. Engine::search_with takes SearchOptions too; the tour uses it throughout.
engine.search_with(
"Pokhara",
3,
&SearchOptions::default(),
&mut scratch,
&mut hits,
)?;
for hit in &hits {
let p = describe(&engine, &hit.place)?;
println!(
"{} {} {} {:.4}, {:.4} score {}",
p.id, p.name, p.kind, p.lat, p.lon, hit.score
);
}tgd:np/1xhb Pokhara settlement 28.2669, 83.9680 score 132
tgd:np/1xnr Pokhara admin 28.2094, 83.9818 score 105
tgd:np/15t1 Pokhara settlement 28.0636, 82.3786 score 90The score ranks the hits of one query and means nothing across queries. It adds how well the
name matched to how important the place is, so a city ranks above a village of the same name.
The engine takes any k; the bindings cap limit at 10,000 (LIMIT_MAX in
teigeodata-api).
Narrow a search by its parent
Write the place's parent after a comma, as people do: "Kathmandu, Bagmati". Places
inside a unit of that name rank first; the parent can be any ancestor (a district, a province,
a country) and is matched with the same tolerance as the name.
engine.search_with(
"Kathmandu, Bagmati",
2,
&SearchOptions::default(),
&mut scratch,
&mut hits,
)?;
for hit in &hits {
let p = describe(&engine, &hit.place)?;
println!("{} {} {} {}", p.id, p.name, p.kind, p.level);
}tgd:np/2cn Kathmandu settlement 0
tgd:np/2gm Kathmandu admin 3The city (a settlement, level 0) and the metropolitan municipality (an admin unit at level 3) share the name, and both are in Bagmati.
Rank by distance from a point
Many places share a name. SearchOptions::with_focus takes a Focus { at, scale_m }: a
point (the user's location, or the middle of the map they are looking at) that ranks near
places first. A place at the focus gains 30 points, one scale_m away 15, and the gain keeps
halving with distance.
// Many places share a name; a focus (the user's location) ranks the near ones first.
let focus = Focus {
at: Point::<E6>::from_degrees(28.7, 80.6)?,
scale_m: 30_000.0,
};
let options = SearchOptions::default().with_focus(focus);
engine.search_with("Shivapur", 3, &options, &mut scratch, &mut hits)?;
for hit in &hits {
let p = describe(&engine, &hit.place)?;
println!("{} {} {:.4}, {:.4}", p.id, p.name, p.lat, p.lon);
}tgd:np/2v99 Shivapur 28.5310, 80.8213
tgd:np/2raj Shivapur 28.7141, 80.9869
tgd:np/2rkx Shivapur 28.5061, 81.3032Set SearchOptions::strict to rank by how well the name matched first (exact, loose,
prefix, one edit, substring, two edits, phonetic), then by importance and focus, instead of one
combined score: useful for an autocomplete that must show exact matches on top.
Get a place by its ID
Every place has a stable ID such as tgd:np/1xhb: the country, then a short code; it parses
into a PlaceId. IDs survive rebuilds of the data; when two places are merged, Engine::get
on the retired ID answers with the survivor, so IDs you stored keep working.
let pokhara = engine.get("tgd:np/1xhb".parse()?)?.ok_or("not found")?;
let p = describe(&engine, &pokhara)?;
println!("{} {}", p.name, p.kind);
let elevation = engine.elevation(&pokhara)?.unwrap_or_default();
println!("at {:.6}, {:.6}, {elevation} m", p.lat, p.lon);
let mut buf = [0u8; 256];
let zone = match engine.tz_of(&pokhara)? {
Some(area) => engine.name(&area, &mut buf)?.unwrap_or_default().to_owned(),
None => String::new(),
};
let parent = engine
.parent(&pokhara)?
.map(|p| p.id.to_string())
.unwrap_or_default();
println!("timezone {zone} parent {parent}");Pokhara settlement
at 28.266890, 83.968000, 1006 m
timezone Asia/Kathmandu parent tgd:np/1xnrEngine::elevation is metres above mean sea level (EGM2008), Engine::tz_of the place's
timezone area and Engine::parent the unit that holds it. Each returns an Option: None
where the data has no value.
Walk the admin hierarchy
ancestors lists the units that hold a place, parent first, up to its country; parent
gives the first of them alone and children the units and places one level down.
engine.ancestors(&pokhara, &mut places)?;
for place in &places {
let p = describe(&engine, place)?;
println!(
"{}",
format!("{} {} {} {}", p.kind, p.level, p.name, p.iso).trim_end()
);
}
let kaski = engine.get("tgd:np/295c".parse()?)?.ok_or("not found")?;
engine.children(&kaski, &mut places)?;
println!("Kaski has {} children", places.len());admin 3 Pokhara
admin 2 Kaski
admin 1 Gandaki NP-P4
country 0 Nepal NP
Kaski has 5 childrenlevel is the admin level as each country defines it: 0 is a country (and a settlement,
which is not a unit), 1 a province or state, and so on down to the lowest level the data has.
Each country's ladder is in its profile on the data pages.
Reverse geocode a point
Engine::reverse gives the places nearest a point, nearest first, as Near values: the
place, meters (the great-circle distance) and bearing_deg (degrees clockwise from north,
from the place to the point: "3.2 km at 45° from Pokhara").
let at = Point::<E6>::from_degrees(27.7172, 85.3240)?;
engine.reverse(at, 3, &mut scratch, &mut near)?;
for n in &near {
let p = describe(&engine, &n.place)?;
println!("{} {:.0} m at {:.0}°", p.name, n.meters, n.bearing_deg);
}Narayanhiti Royal Palace 331 m at 116°
Gairidhara 375 m at 220°
Naxal 384 m at 329°For the admin units that hold a point (its district, province and country) use
Engine::admin_at below; reverse answers with what is near it.
Find everything within a radius
within_radius gives the places within a distance of a point, nearest first, with the
same meters and bearing columns, at most limit of them.
engine.within_radius(at, 500.0, 10, &mut scratch, &mut near)?;
let farthest = near.last().map_or(0.0, |n| n.meters);
println!(
"{} places within 500 m; farthest {farthest:.0} m",
near.len()
);3 places within 500 m; farthest 384 mFind places near a place
nearby is reverse geocoding from a place you already have: the places nearest it,
itself left out.
let kathmandu = engine.get("tgd:np/2cn".parse()?)?.ok_or("not found")?;
engine.nearby(&kathmandu, 3, &mut scratch, &mut near)?;
for n in &near {
println!("{} {:.0} m", describe(&engine, &n.place)?.name, n.meters);
}Bhrikuti Mandap 168 m
Bagbazar 354 m
Shahidgate 393 mAdmin units at a point, and ISO 3166 codes
admin_at tests the point against the admin boundaries and gives every unit that holds
it, country first. by_iso finds a country or a subdivision by its ISO 3166 code (NP,
NP-P4, in either case).
engine.admin_at(
Point::<E7>::from_degrees(28.2096, 83.9856)?,
&mut scratch,
&mut places,
)?;
for place in &places {
let p = describe(&engine, place)?;
println!(
"{}",
format!("{} {} {}", p.level, p.name, p.iso).trim_end()
);
}
let state = engine.by_iso("NP-P4".parse()?)?.ok_or("not found")?;
let s = describe(&engine, &state)?;
println!("NP-P4 is {} {}", s.name, s.id);0 Nepal NP
1 Gandaki NP-P4
2 Kaski
3 Pokhara
NP-P4 is Gandaki tgd:np/2922Boundaries are exact polygons, so a point near a border is answered by the side it is on, not by the nearest centre. Disputed boundaries are drawn from one stated perspective; see accuracy.
Timezones: the zone, its offset and local times
Engine::tz_at gives the timezone area at a point as the zone boundaries draw it, a Place
whose name is the IANA zone (Engine::zone_name reads it from the zone rules, when the pack
has them). With the zone, Engine::tz_offset_at gives the UTC offset at an instant (from the
tzdb rules inside the pack, not from the operating system), and
Engine::tz_local_candidates tells whether a wall-clock time exists: Local::Unique,
Local::Gap (skipped by a daylight-saving change) or Local::Overlap (it happens twice),
with the offsets before and after.
let area = engine
.tz_at(Point::<E7>::from_degrees(27.7172, 85.3240)?)?
.ok_or("no zone")?;
let zone = describe(&engine, &area)?.name;
let offset = engine
.tz_offset_at(&zone, 1_700_000_000)?
.ok_or("no rules")?;
println!(
"{zone} {} s east of UTC, {} dst {}",
offset.seconds,
offset.abbr(),
u8::from(offset.is_dst)
);
let civil = teigeodata_engine::Civil {
year: 2026,
month: 3,
day: 8,
hour: 2,
minute: 30,
second: 0,
};
let (kind, before, after) = match engine.tz_local_candidates("America/New_York", civil)? {
Some(teigeodata_engine::Local::Unique(o)) => ("unique", o, o),
Some(teigeodata_engine::Local::Gap { before, after }) => ("gap", before, after),
Some(teigeodata_engine::Local::Overlap { earlier, later }) => ("overlap", earlier, later),
None => return Err("no rules for New York".into()),
};
println!("02:30 on 2026-03-08 in New York: {kind} {before} -> {after}");
println!("tzdb {}", engine.tz_version().unwrap_or_default());Asia/Kathmandu 20700 s east of UTC, +0545 dst 0
02:30 on 2026-03-08 in New York: gap -18000 -> -14400
tzdb 2026fEngine::tz_version names the tzdb release the rules come from, so you can tell when a pack
is older than a rule change; Engine::tz_zones lists every zone the packs hold.
Elevation at any point
elevation_at reads the terrain height at a point from the pack's elevation grid,
interpolated between the four samples around it: meters above EGM2008, the source product,
the grid's resolution_m and the datum. There is no row at sea or outside every grid.
let height = engine
.elevation_at(Point::<E7>::from_degrees(27.7172, 85.3240)?, &mut scratch)?
.ok_or("no terrain")?;
println!(
"{:.1} m above {} ({}, {:.0} m grid)",
height.meters,
height.datum.name(),
height.source.map_or("", |s| s.key()),
height.resolution_m
);1304.2 m above EGM2008 (nasadem, 464 m grid)Every place also has its own elevation column. The world pack carries a coarse grid; a
country's terrain pack adds a finer one, and the engine answers from the finest grid that covers
the point.
Distance and bearing
meters_between is the great-circle distance in metres (haversine on the WGS84 mean
sphere, within about 0.5% of the ellipsoid), and bearing_deg the initial bearing from the
first point to the second, in degrees clockwise from north. Both take degrees and need no
pack; between two places, pass their points.
let meters = meters_between(27.7172, 85.3240, 28.2096, 83.9856);
let heading = bearing_deg(27.7172, 85.3240, 28.2096, 83.9856);
println!(
"Kathmandu to Pokhara: {:.1} km, heading {heading:.0}°",
meters / 1000.0
);
let pokhara = engine.get("tgd:np/1xhb".parse()?)?.ok_or("not found")?;
let (a, b) = (kathmandu.point, pokhara.point);
let (lat1, lon1, lat2, lon2) = (
a.lat_degrees(),
a.lon_degrees(),
b.lat_degrees(),
b.lon_degrees(),
);
println!(
"place to place: {:.1} km at {:.0}°",
meters_between(lat1, lon1, lat2, lon2) / 1000.0,
bearing_deg(lat1, lon1, lat2, lon2)
);Kathmandu to Pokhara: 142.4 km, heading 293°
place to place: 146.9 km at 296°The bindings' distance takes two place IDs and answers both in one row. The bearing
is the direction you set off in: on a great circle it changes along the way.
A place's outline
Engine::boundary decodes a unit's outline at a level of detail into an Outline you
reuse: its rings, its points and the level's tolerance_cm. It returns the layer that held it,
or None (and an empty outline) for a place without one. Outline::write_geojson writes the
geometry as RFC 7946 GeoJSON (outer rings counterclockwise, holes clockwise, seven decimals as
stored): the same bytes the servers and every binding's boundary answer.
let metro = engine.get("tgd:np/2gm".parse()?)?.ok_or("not found")?;
let mut shape = Outline::default();
engine
.boundary(&metro, 0, &mut shape)?
.ok_or("no outline")?;
// The geometry as GeoJSON (RFC 7946), the bytes every binding's `geojson` column holds.
let mut geometry = Vec::new();
shape.write_geojson(&mut geometry);
let kind = if geometry.starts_with(br#"{"type":"Polygon""#) {
"Polygon"
} else {
"MultiPolygon"
};
println!("{kind} of {} vertices at level 0", shape.points.len());
let tolerance_m = f64::from(shape.tolerance_cm) / 100.0;
let feature = format!(
r#"{{"type":"Feature","id":"{}","geometry":{},"properties":{{"lod":0,"tolerance_m":{tolerance_m},"vertices":{}}}}}"#,
metro.id,
String::from_utf8_lossy(&geometry),
shape.points.len()
);
println!(
"tolerance {tolerance_m:.0} m, {} bytes of GeoJSON",
feature.len()
);Polygon of 176 vertices at level 0
tolerance 0 m, 4362 bytes of GeoJSON- Level of detail. Level 0 is full resolution; 1 to 6 are coarser, each within its tolerance, with neighbouring units still sharing their borders at every level. A pack stored at full resolution only (the lite packs) reads every level as 0. Draw a coarser level; keep 0 for measuring.
Engine::boundary_verticescounts an outline's vertices without decoding it, andadmin_attests a point against the same outlines without building them.
Errors
A query fails with the engine's Error; the bindings map it to their eight stable codes:
Error | Meaning | Bindings' code |
|---|---|---|
Io | A file could not be read. | Io |
Format | The bytes are not a valid pack, or a section's structure is broken. | Corrupt |
Integrity { address, kind } | A section's bytes do not match its hash. | Corrupt |
Range | A section is missing or a byte range is outside it. | Corrupt |
MissingComponent { address, component } | The query needs a component the layer was installed without. | MissingComponent |
Arguments are checked by their types before a query runs: a Point is in range when it is made,
and a PlaceId or an IsoCode when it is parsed. The store (teigeodata-sync) has its own
error type for the network and the catalog. A query that finds nothing is not an error: it
returns None or no hits.
Rust returns Results: the tour's main returns Result<(), Box<dyn Error>> and uses ?
throughout. A point is checked when it is made, so the latitude error comes from
Point::from_degrees:
if let Err(e) = Point::<E6>::from_degrees(91.0, 0.0) {
println!("invalid argument: (91, 0) is not a point: {e}");
}invalid argument: (91, 0) is not a point: the latitude is outside -90 to 90 degreesThreads and updates
Engine is Send + Sync: share it in an Arc and query from any number of threads. To add or
remove layers while other threads query, hold a Shared: Shared::load gives the snapshot a
query runs on, and Shared::update changes a copy and publishes it atomically, so queries
already running finish on the snapshot they started with:
use teigeodata_engine::{Engine, Layer, LayerOptions, Shared};
let shared = Shared::new(Engine::new());
let id = shared.update(|e| e.add(Layer::open("world-np-lite.tgd", LayerOptions::default()).unwrap()));
let snapshot = shared.load(); // derefs to &EngineThe whole program
Run it from a checkout of the repository, which builds what the language needs, fetches the pinned pack and compares the output:
cargo xtask docs-examples --fetch --check --lang rust