💚 End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add offline city lookup
Neeraj Gupta983a77b9cc96
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex df81838461..1e6f782d65 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2633,6 +2633,18 @@ name = "ente-location"version = "0.0.0"dependencies = ["thiserror 2.0.18",+ "unicode-normalization",+]++[[package]]+name = "ente-location-dataset"+version = "0.0.0"+dependencies = [+ "ente-location",+ "reqwest 0.12.28",+ "sha2 0.11.0",+ "thiserror 2.0.18",+ "zip 8.6.0",][[package]]@@ -3193,6 +3205,7 @@ checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"dependencies = ["crc32fast","miniz_oxide",+ "zlib-rs",][[package]]@@ -7544,6 +7557,7 @@ dependencies = ["base64 0.22.1","bytes","encoding_rs",+ "futures-channel","futures-core","futures-util","h2",@@ -9980,6 +9994,12 @@ dependencies = ["sponge-cursor",]+[[package]]+name = "typed-path"+version = "0.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e"+[[package]]name = "typeid"version = "1.0.3"@@ -11756,6 +11776,25 @@ dependencies = ["memchr",]+[[package]]+name = "zip"+version = "8.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b"+dependencies = [+ "crc32fast",+ "flate2",+ "indexmap 2.14.0",+ "memchr",+ "typed-path",+]++[[package]]+name = "zlib-rs"+version = "0.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12"+[[package]]name = "zmij"version = "1.0.21"diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex d87ecee7db..cc106cc428 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -32,6 +32,7 @@ members = ["crates/image","crates/legacy","crates/location",+ "crates/location-dataset","crates/ml","crates/paste","crates/photos",diff --git a/rust/crates/location-dataset/Cargo.toml b/rust/crates/location-dataset/Cargo.tomlnew file mode 100644index 0000000000..89c5542fcc--- /dev/null+++ b/rust/crates/location-dataset/Cargo.toml@@ -0,0 +1,11 @@+[package]+name = "ente-location-dataset"+edition = "2024"+publish = false++[dependencies]+ente-location.workspace = true+reqwest = { workspace = true, features = ["blocking", "rustls-tls-webpki-roots"] }+sha2.workspace = true+thiserror.workspace = true+zip = { version = "8.6.0", default-features = false, features = ["deflate-flate2-zlib-rs"] }diff --git a/rust/crates/location-dataset/README.md b/rust/crates/location-dataset/README.mdnew file mode 100644index 0000000000..217695fc11--- /dev/null+++ b/rust/crates/location-dataset/README.md@@ -0,0 +1,18 @@+# ente-location-dataset++Host-side generator for the city asset consumed by `ente-location`.++```sh+cargo run --release -p ente-location-dataset -- \+ build --output /tmp/ente-location+```++The command downloads and caches its sources, writes `cities.bin`, and prints+its size and SHA-256 hash.++## Source++City data is derived from [GeoNames](https://www.geonames.org/) `cities5000`+and `countryInfo`, licensed under+[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). Ente filters and+converts the data, which is provided without warranty.diff --git a/rust/crates/location-dataset/src/city.rs b/rust/crates/location-dataset/src/city.rsnew file mode 100644index 0000000000..26a2c7fc37--- /dev/null+++ b/rust/crates/location-dataset/src/city.rs@@ -0,0 +1,421 @@+use std::cmp::Ordering;+use std::collections::{BTreeMap, HashMap, HashSet};+use std::fs::File;+use std::io::{BufRead, BufReader};+use std::path::Path;++use ente_location::CountryCode;++use crate::{Result, invalid};++const HEADER_LEN: usize = 72;+const NODE_LEN: usize = 3;+const POINT_LEN: usize = 15;+const NAME_OFFSET_LEN: usize = 3;+const MAX_U24: u32 = 0x00ff_ffff;++struct SourceCity {+ source_id: u32,+ name: String,+ ascii_name: String,+ country_code: [u8; 2],+ latitude: f64,+ longitude: f64,+ population: u64,+ importance: u8,+}++impl SourceCity {+ fn rank(&self) -> u8 {+ if self.importance == 0 || self.population >= 5_000_000 {+ 4+ } else if self.importance == 1 || self.population >= 1_000_000 {+ 3+ } else if self.importance == 2 || self.population >= 250_000 {+ 2+ } else if self.population >= 50_000 {+ 1+ } else {+ 0+ }+ }+}++pub(crate) fn build(cities_path: &Path, country_info_path: &Path) -> Result<Vec<u8>> {+ let countries = read_countries(country_info_path)?;+ let mut cities = read_cities(cities_path, &countries)?;+ cities.sort_by(compare_priority);+ encode(&cities, &countries)+}++fn read_countries(path: &Path) -> Result<BTreeMap<[u8; 2], String>> {+ let reader = BufReader::new(File::open(path)?);+ let mut countries = BTreeMap::new();+ for line in reader.lines() {+ let line = line?;+ if line.is_empty() || line.starts_with('#') {+ continue;+ }+ let fields: Vec<&str> = line.split('\t').collect();+ if fields.len() < 5 {+ return Err(invalid("GeoNames countryInfo row has too few fields"));+ }+ let code = code(fields[0])?;+ let name = fields[4].trim();+ if name.is_empty() || countries.insert(code, name.to_owned()).is_some() {+ return Err(invalid(+ "GeoNames countryInfo contains an invalid duplicate",+ ));+ }+ }+ Ok(countries)+}++fn read_cities(path: &Path, countries: &BTreeMap<[u8; 2], String>) -> Result<Vec<SourceCity>> {+ let reader = BufReader::new(File::open(path)?);+ let mut cities = Vec::new();+ let mut source_ids = HashSet::new();+ for (line_index, line) in reader.lines().enumerate() {+ let line = line?;+ let fields: Vec<&str> = line.split('\t').collect();+ if fields.len() < 19 {+ return Err(invalid(format!(+ "GeoNames city row {} has too few fields",+ line_index + 1+ )));+ }+ let feature_code = fields[7];+ if !is_current_place(feature_code) {+ continue;+ }+ let source_id = parse(fields[0], "GeoNames ID", line_index)?;+ let name = fields[1].trim();+ let ascii_name = fields[2].trim();+ let latitude: f64 = parse(fields[4], "latitude", line_index)?;+ let longitude: f64 = parse(fields[5], "longitude", line_index)?;+ let country_code = code(fields[8])?;+ let population = parse(fields[14], "population", line_index)?;+ if !countries.contains_key(&country_code) {+ return Err(invalid(format!(+ "GeoNames city row {} has unknown country {}",+ line_index + 1,+ fields[8]+ )));+ }+ if name.is_empty()+ || name.contains('\0')+ || ascii_name.contains('\0')+ || source_id > MAX_U24+ || !latitude.is_finite()+ || !(-90.0..=90.0).contains(&latitude)+ || !longitude.is_finite()+ || !(-180.0..=180.0).contains(&longitude)+ || !source_ids.insert(source_id)+ {+ return Err(invalid(format!(+ "GeoNames city row {} is invalid",+ line_index + 1+ )));+ }+ let importance = match feature_code {+ "PPLC" => 0,+ "PPLA" => 1,+ "PPLA2" | "PPLA3" | "PPLA4" => 2,+ _ => 3,+ };+ cities.push(SourceCity {+ source_id,+ name: name.to_owned(),+ ascii_name: ascii_name.to_owned(),+ country_code,+ latitude,+ longitude,+ population,+ importance,+ });+ }+ if cities.is_empty() {+ return Err(invalid("GeoNames city source is empty"));+ }+ Ok(cities)+}++fn is_current_place(feature_code: &str) -> bool {+ !matches!(feature_code, "PPLH" | "PPLQ" | "PPLW")+}++fn compare_priority(left: &SourceCity, right: &SourceCity) -> Ordering {+ right+ .rank()+ .cmp(&left.rank())+ .then_with(|| left.importance.cmp(&right.importance))+ .then_with(|| right.population.cmp(&left.population))+ .then_with(|| left.country_code.cmp(&right.country_code))+ .then_with(|| left.source_id.cmp(&right.source_id))+}++fn encode(cities: &[SourceCity], countries: &BTreeMap<[u8; 2], String>) -> Result<Vec<u8>> {+ if cities.len() > MAX_U24 as usize {+ return Err(invalid("city index exceeds 24-bit point indices"));+ }+ let nodes = build_tree(cities);+ let mut names = Vec::<String>::new();+ let mut name_indices = HashMap::<String, u32>::new();+ let mut point_names = Vec::with_capacity(cities.len());+ for city in cities {+ let mut key = city.name.clone();+ if !city.ascii_name.is_empty() && city.ascii_name != city.name {+ key.push('\0');+ key.push_str(&city.ascii_name.to_lowercase());+ }+ let next = names.len() as u32;+ let index = *name_indices.entry(key.clone()).or_insert_with(|| {+ names.push(key);+ next+ });+ point_names.push(index);+ }++ let country_codes: Vec<[u8; 2]> = countries.keys().copied().collect();+ if country_codes.len() > 256 {+ return Err(invalid("city country table exceeds one-byte indices"));+ }+ let country_indices: BTreeMap<[u8; 2], u8> = country_codes+ .iter()+ .copied()+ .enumerate()+ .map(|(index, code)| (code, index as u8))+ .collect();+ let name_table = string_table_u24(names.iter().map(String::as_str))?;+ let country_table = string_table_u32(countries.values().map(String::as_str))?;+ let rank_ends = [4, 3, 2, 1].map(|rank| cities.partition_point(|city| city.rank() >= rank));++ let nodes_offset = HEADER_LEN;+ let points_offset = nodes_offset + nodes.len() * NODE_LEN;+ let name_offsets_offset = points_offset + cities.len() * POINT_LEN;+ let names_offset = name_offsets_offset + name_table.0.len();+ let country_offsets_offset = names_offset + name_table.1.len();+ let countries_offset = country_offsets_offset + country_table.0.len();+ let country_codes_offset = countries_offset + country_table.1.len();+ let file_length = country_codes_offset + country_codes.len() * 2;+ let mut output = vec![0; file_length];++ output[..4].copy_from_slice(b"CITY");+ put_u16(&mut output, 4, 1);+ put_u16(&mut output, 6, HEADER_LEN as u16);+ put_len(&mut output, 8, cities.len())?;+ put_len(&mut output, 12, names.len())?;+ put_u16(+ &mut output,+ 16,+ u16::try_from(country_codes.len()).map_err(|_| invalid("too many countries"))?,+ );+ put_u16(&mut output, 18, POINT_LEN as u16);+ put_u16(&mut output, 20, NODE_LEN as u16);+ put_u16(&mut output, 22, NAME_OFFSET_LEN as u16);+ for (field, value) in [+ (24, nodes_offset),+ (28, points_offset),+ (32, name_offsets_offset),+ (36, names_offset),+ (40, country_offsets_offset),+ (44, countries_offset),+ (48, country_codes_offset),+ (52, file_length),+ ] {+ put_len(&mut output, field, value)?;+ }+ for (field, value) in [56, 60, 64, 68].into_iter().zip(rank_ends) {+ put_len(&mut output, field, value)?;+ }++ for (index, &point) in nodes.iter().enumerate() {+ let offset = nodes_offset + index * NODE_LEN;+ put_u24(&mut output, offset, point as u32);+ }+ for (index, city) in cities.iter().enumerate() {+ let offset = points_offset + index * POINT_LEN;+ output[offset..offset + 4].copy_from_slice(&(city.latitude as f32).to_le_bytes());+ output[offset + 4..offset + 8].copy_from_slice(&(city.longitude as f32).to_le_bytes());+ put_u24(&mut output, offset + 8, point_names[index]);+ output[offset + 11] = country_indices[&city.country_code];+ put_u24(&mut output, offset + 12, city.source_id);+ }+ copy(&mut output, name_offsets_offset, &name_table.0);+ copy(&mut output, names_offset, &name_table.1);+ copy(&mut output, country_offsets_offset, &country_table.0);+ copy(&mut output, countries_offset, &country_table.1);+ for (index, code) in country_codes.iter().enumerate() {+ copy(&mut output, country_codes_offset + index * 2, code);+ }+ Ok(output)+}++fn build_tree(cities: &[SourceCity]) -> Vec<usize> {+ fn build(cities: &[SourceCity], nodes: &mut Vec<usize>, points: &mut [usize], depth: usize) {+ if points.is_empty() {+ return;+ }+ let axis = depth % 2;+ let median = points.len() / 2;+ points.select_nth_unstable_by(median, |&left, &right| {+ let ordering = if axis == 0 {+ cities[left].latitude.total_cmp(&cities[right].latitude)+ } else {+ cities[left].longitude.total_cmp(&cities[right].longitude)+ };+ ordering.then_with(|| left.cmp(&right))+ });+ let point = points[median];+ nodes.push(point);+ let (left, right_with_median) = points.split_at_mut(median);+ let (_, right) = right_with_median+ .split_first_mut()+ .expect("nonempty median slice");+ build(cities, nodes, left, depth + 1);+ build(cities, nodes, right, depth + 1);+ }++ let mut points: Vec<usize> = (0..cities.len()).collect();+ let mut nodes = Vec::with_capacity(cities.len());+ build(cities, &mut nodes, &mut points, 0);+ nodes+}++fn string_table_u24<'a>(+ values: impl ExactSizeIterator<Item = &'a str>,+) -> Result<(Vec<u8>, Vec<u8>)> {+ let mut offsets = Vec::with_capacity((values.len() + 1) * NAME_OFFSET_LEN);+ let mut blob = Vec::new();+ for value in values {+ push_u24(&mut offsets, blob.len())?;+ blob.extend_from_slice(value.as_bytes());+ }+ push_u24(&mut offsets, blob.len())?;+ Ok((offsets, blob))+}++fn string_table_u32<'a>(+ values: impl ExactSizeIterator<Item = &'a str>,+) -> Result<(Vec<u8>, Vec<u8>)> {+ let mut offsets = Vec::with_capacity((values.len() + 1) * 4);+ let mut blob = Vec::new();+ for value in values {+ offsets.extend_from_slice(+ &u32::try_from(blob.len())+ .map_err(|_| invalid("string table exceeds 4 GiB"))?+ .to_le_bytes(),+ );+ blob.extend_from_slice(value.as_bytes());+ }+ offsets.extend_from_slice(+ &u32::try_from(blob.len())+ .map_err(|_| invalid("string table exceeds 4 GiB"))?+ .to_le_bytes(),+ );+ Ok((offsets, blob))+}++fn code(value: &str) -> Result<[u8; 2]> {+ value+ .trim()+ .parse::<CountryCode>()+ .map(CountryCode::as_bytes)+ .map_err(|_| invalid(format!("invalid country code {value:?}")))+}++fn parse<T: std::str::FromStr>(value: &str, field: &str, line_index: usize) -> Result<T> {+ value.parse().map_err(|_| {+ invalid(format!(+ "GeoNames city row {} has invalid {field}",+ line_index + 1+ ))+ })+}++fn put_u16(output: &mut [u8], offset: usize, value: u16) {+ output[offset..offset + 2].copy_from_slice(&value.to_le_bytes());+}++fn put_u32(output: &mut [u8], offset: usize, value: u32) {+ output[offset..offset + 4].copy_from_slice(&value.to_le_bytes());+}++fn put_u24(output: &mut [u8], offset: usize, value: u32) {+ output[offset..offset + 3].copy_from_slice(&value.to_le_bytes()[..3]);+}++fn push_u24(output: &mut Vec<u8>, value: usize) -> Result<()> {+ let value = u32::try_from(value).map_err(|_| invalid("city name table exceeds 16 MiB"))?;+ if value > MAX_U24 {+ return Err(invalid("city name table exceeds 16 MiB"));+ }+ output.extend_from_slice(&value.to_le_bytes()[..3]);+ Ok(())+}++fn put_len(output: &mut [u8], offset: usize, value: usize) -> Result<()> {+ put_u32(+ output,+ offset,+ u32::try_from(value).map_err(|_| invalid("city index exceeds 4 GiB"))?,+ );+ Ok(())+}++fn copy(output: &mut [u8], offset: usize, bytes: &[u8]) {+ output[offset..offset + bytes.len()].copy_from_slice(bytes);+}++#[cfg(test)]+mod tests {+ use std::collections::BTreeMap;++ use ente_location::{CityIndex, Coordinate, CountryCode};++ use super::{SourceCity, encode};++ #[test]+ fn round_trips_city_search_and_lookup() {+ let cities = vec![+ city(1, "Delhi", "Delhi", *b"IN", 28.6139, 77.2090, 4),+ city(2, "Zürich", "Zuerich", *b"CH", 47.3667, 8.5500, 3),+ ];+ let countries = BTreeMap::from([+ (*b"CH", "Switzerland".to_owned()),+ (*b"IN", "India".to_owned()),+ ]);+ let bytes = encode(&cities, &countries).unwrap();+ let index = CityIndex::from_bytes(bytes).unwrap();++ assert_eq!(index.search("zurich", 5)[0].name, "Zürich");+ assert_eq!(index.search("ZUERICH", 5)[0].name, "Zürich");+ assert_eq!(+ index.match_coordinates(&[Coordinate::new(28.61, 77.21)], "")[0]+ .city+ .country_code,+ CountryCode::from_bytes(*b"IN").unwrap()+ );+ }++ fn city(+ source_id: u32,+ name: &str,+ ascii_name: &str,+ country_code: [u8; 2],+ latitude: f64,+ longitude: f64,+ rank: u8,+ ) -> SourceCity {+ SourceCity {+ source_id,+ name: name.to_owned(),+ ascii_name: ascii_name.to_owned(),+ country_code,+ latitude,+ longitude,+ population: [10_000, 100_000, 300_000, 1_500_000, 6_000_000][usize::from(rank)],+ importance: 3,+ }+ }+}diff --git a/rust/crates/location-dataset/src/download.rs b/rust/crates/location-dataset/src/download.rsnew file mode 100644index 0000000000..10e27b0697--- /dev/null+++ b/rust/crates/location-dataset/src/download.rs@@ -0,0 +1,35 @@+use std::fs::File;+use std::io::{BufWriter, Write};+use std::path::Path;++use reqwest::blocking::Client;+use zip::ZipArchive;++use crate::Result;++pub(crate) fn download(client: &Client, url: &str, path: &Path) -> Result<()> {+ if path.is_file() {+ return Ok(());+ }+ let temporary = path.with_extension("download");+ let mut response = client.get(url).send()?.error_for_status()?;+ let mut writer = BufWriter::new(File::create(&temporary)?);+ std::io::copy(&mut response, &mut writer)?;+ writer.flush()?;+ std::fs::rename(temporary, path)?;+ Ok(())+}++pub(crate) fn extract(archive_path: &Path, output: &Path, name: &str) -> Result<()> {+ if output.is_file() {+ return Ok(());+ }+ let mut archive = ZipArchive::new(File::open(archive_path)?)?;+ let mut source = archive.by_name(name)?;+ let temporary = output.with_extension("extract");+ let mut writer = BufWriter::new(File::create(&temporary)?);+ std::io::copy(&mut source, &mut writer)?;+ writer.flush()?;+ std::fs::rename(temporary, output)?;+ Ok(())+}diff --git a/rust/crates/location-dataset/src/lib.rs b/rust/crates/location-dataset/src/lib.rsnew file mode 100644index 0000000000..2b660a2ffe--- /dev/null+++ b/rust/crates/location-dataset/src/lib.rs@@ -0,0 +1,66 @@+use std::fmt::Write as _;+use std::path::PathBuf;++use ente_location::CityIndex;+use sha2::{Digest, Sha256};+use thiserror::Error;++mod city;+mod download;+mod sources;++pub use sources::{RemoteSources, SourcePaths};++pub const CITY_FILE: &str = "cities.bin";++pub type Result<T> = std::result::Result<T, Error>;++#[derive(Debug, Error)]+pub enum Error {+ #[error("I/O error: {0}")]+ Io(#[from] std::io::Error),+ #[error("download failed: {0}")]+ Http(#[from] reqwest::Error),+ #[error("ZIP archive is invalid: {0}")]+ Zip(#[from] zip::result::ZipError),+ #[error("invalid location data: {0}")]+ InvalidData(String),+ #[error(transparent)]+ Location(#[from] ente_location::Error),+}++pub struct BuildOptions {+ pub sources: SourcePaths,+ pub output: PathBuf,+}++pub struct BuildOutput {+ pub city_count: usize,+ pub byte_length: usize,+ pub sha256: String,+}++pub fn build(options: &BuildOptions) -> Result<BuildOutput> {+ let bytes = city::build(&options.sources.cities, &options.sources.country_info)?;+ let city_count = CityIndex::from_bytes(bytes.as_slice())?.len();+ let output = BuildOutput {+ city_count,+ byte_length: bytes.len(),+ sha256: hex(Sha256::digest(&bytes)),+ };+ std::fs::create_dir_all(&options.output)?;+ std::fs::write(options.output.join(CITY_FILE), bytes)?;+ Ok(output)+}++fn invalid(message: impl Into<String>) -> Error {+ Error::InvalidData(message.into())+}++fn hex(bytes: impl AsRef<[u8]>) -> String {+ let mut output = String::with_capacity(bytes.as_ref().len() * 2);+ for byte in bytes.as_ref() {+ write!(output, "{byte:02x}").expect("writing to a string is infallible");+ }+ output+}diff --git a/rust/crates/location-dataset/src/main.rs b/rust/crates/location-dataset/src/main.rsnew file mode 100644index 0000000000..4ed8dad10b--- /dev/null+++ b/rust/crates/location-dataset/src/main.rs@@ -0,0 +1,81 @@+use std::env;+use std::error::Error;+use std::path::PathBuf;++use ente_location_dataset::{BuildOptions, CITY_FILE, RemoteSources, SourcePaths, build};++const USAGE: &str = concat!(+ "usage: ente-location-dataset build --output <directory> [--cache <directory>] ",+ "[--cities <file> --country-info <file>]"+);++fn main() {+ if let Err(error) = run() {+ eprintln!("{error}");+ std::process::exit(1);+ }+}++fn run() -> Result<(), Box<dyn Error>> {+ let Arguments {+ output,+ cache,+ cities,+ country_info,+ } = Arguments::parse()?;+ let sources = match (cities, country_info) {+ (None, None) => RemoteSources::new(cache).fetch()?,+ (Some(cities), Some(country_info)) => SourcePaths {+ cities,+ country_info,+ },+ _ => return Err("local generation requires both source paths".into()),+ };+ let result = build(&BuildOptions { sources, output })?;+ println!("cities: {}", result.city_count);+ println!(+ "{CITY_FILE}: {} bytes, sha256 {}",+ result.byte_length, result.sha256+ );+ Ok(())+}++struct Arguments {+ output: PathBuf,+ cache: PathBuf,+ cities: Option<PathBuf>,+ country_info: Option<PathBuf>,+}++impl Arguments {+ fn parse() -> Result<Self, Box<dyn Error>> {+ let mut args = env::args().skip(1);+ if args.next().as_deref() != Some("build") {+ return Err(USAGE.into());+ }+ let mut output = None;+ let mut cache = None;+ let mut cities = None;+ let mut country_info = None;+ while let Some(argument) = args.next() {+ let value = args.next().ok_or(USAGE)?;+ match argument.as_str() {+ "--output" => output = Some(value.into()),+ "--cache" => cache = Some(value.into()),+ "--cities" => cities = Some(value.into()),+ "--country-info" => country_info = Some(value.into()),+ _ => return Err(USAGE.into()),+ }+ }+ Ok(Self {+ output: output.ok_or(USAGE)?,+ cache: cache.unwrap_or_else(default_cache),+ cities,+ country_info,+ })+ }+}++fn default_cache() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/location-dataset/sources")+}diff --git a/rust/crates/location-dataset/src/sources.rs b/rust/crates/location-dataset/src/sources.rsnew file mode 100644index 0000000000..75b0ef90da--- /dev/null+++ b/rust/crates/location-dataset/src/sources.rs@@ -0,0 +1,45 @@+use std::path::PathBuf;++use reqwest::blocking::Client;++use crate::Result;+use crate::download::{download, extract};++const CITIES_URL: &str = "https://download.geonames.org/export/dump/cities5000.zip";+const COUNTRY_INFO_URL: &str = "https://download.geonames.org/export/dump/countryInfo.txt";++#[derive(Clone, Debug)]+pub struct SourcePaths {+ pub cities: PathBuf,+ pub country_info: PathBuf,+}++#[derive(Clone, Debug)]+pub struct RemoteSources {+ cache: PathBuf,+}++impl RemoteSources {+ pub fn new(cache: impl Into<PathBuf>) -> Self {+ Self {+ cache: cache.into(),+ }+ }++ pub fn fetch(&self) -> Result<SourcePaths> {+ std::fs::create_dir_all(&self.cache)?;+ let client = Client::builder()+ .user_agent("ente-location-dataset")+ .build()?;+ let cities_archive = self.cache.join("cities5000.zip");+ let cities = self.cache.join("cities5000.txt");+ let country_info = self.cache.join("countryInfo.txt");+ download(&client, CITIES_URL, &cities_archive)?;+ download(&client, COUNTRY_INFO_URL, &country_info)?;+ extract(&cities_archive, &cities, "cities5000.txt")?;+ Ok(SourcePaths {+ cities,+ country_info,+ })+ }+}diff --git a/rust/crates/location/Cargo.toml b/rust/crates/location/Cargo.tomlindex 61c12f4b6f..9789550643 100644--- a/rust/crates/location/Cargo.toml+++ b/rust/crates/location/Cargo.toml@@ -4,3 +4,4 @@ edition = "2024"[dependencies]thiserror.workspace = true+unicode-normalization = "0.1.25"diff --git a/rust/crates/location/src/binary.rs b/rust/crates/location/src/binary.rsnew file mode 100644index 0000000000..acaf6297f3--- /dev/null+++ b/rust/crates/location/src/binary.rs@@ -0,0 +1,26 @@+use std::ops::Range;++pub(crate) fn array<const N: usize>(bytes: &[u8], offset: usize) -> Option<[u8; N]> {+ bytes.get(offset..offset.checked_add(N)?)?.try_into().ok()+}++pub(crate) fn u16_at(bytes: &[u8], offset: usize) -> Option<u16> {+ Some(u16::from_le_bytes(array(bytes, offset)?))+}++pub(crate) fn u24_at(bytes: &[u8], offset: usize) -> Option<u32> {+ let [a, b, c] = array(bytes, offset)?;+ Some(u32::from_le_bytes([a, b, c, 0]))+}++pub(crate) fn u32_at(bytes: &[u8], offset: usize) -> Option<u32> {+ Some(u32::from_le_bytes(array(bytes, offset)?))+}++pub(crate) fn f32_at(bytes: &[u8], offset: usize) -> Option<f32> {+ Some(f32::from_le_bytes(array(bytes, offset)?))+}++pub(crate) fn range(offset: usize, count: usize, stride: usize) -> Option<Range<usize>> {+ Some(offset..offset.checked_add(count.checked_mul(stride)?)?)+}diff --git a/rust/crates/location/src/city.rs b/rust/crates/location/src/city.rsnew file mode 100644index 0000000000..c472671dc1--- /dev/null+++ b/rust/crates/location/src/city.rs@@ -0,0 +1,826 @@+use std::cmp::Ordering;+use std::collections::BTreeMap;+use std::fs;+use std::path::Path;++use unicode_normalization::UnicodeNormalization;+use unicode_normalization::char::is_combining_mark;++use crate::binary::{f32_at, range, u16_at, u24_at, u32_at};+use crate::{Coordinate, CountryCode, Error};++const MAGIC: &[u8; 4] = b"CITY";+const VERSION: u16 = 1;+const HEADER_LEN: usize = 72;+const NODE_LEN: usize = 3;+const POINT_LEN: usize = 15;+const NAME_OFFSET_LEN: usize = 3;+const MAX_U24: usize = 0x00ff_ffff;+const MAX_CATCHMENT_KM: f64 = 30.0;+const SECTION: &str = "city index";++#[derive(Clone, Debug, PartialEq)]+pub struct City {+ pub point_index: u32,+ pub source_id: u32,+ pub name: String,+ pub country_name: String,+ pub country_code: CountryCode,+ pub latitude: f64,+ pub longitude: f64,+ pub rank: u8,+}++#[derive(Clone, Debug, PartialEq)]+pub struct CityMatch {+ pub city: City,+ pub coordinate_indices: Vec<u32>,+}++#[derive(Clone, Copy, Debug)]+struct Layout {+ point_count: usize,+ name_count: usize,+ country_count: usize,+ nodes: usize,+ points: usize,+ name_offsets: usize,+ names: usize,+ country_offsets: usize,+ countries: usize,+ country_codes: usize,+ rank_ends: [usize; 4],+}++#[derive(Clone, Copy)]+struct Point {+ latitude: f32,+ longitude: f32,+ name: usize,+ country: usize,+ source_id: u32,+}++#[derive(Clone, Copy)]+struct SearchBounds {+ minimum_latitude: f64,+ maximum_latitude: f64,+ minimum_longitude: f64,+ maximum_longitude: f64,+}++impl SearchBounds {+ const fn new(+ minimum_latitude: f64,+ maximum_latitude: f64,+ minimum_longitude: f64,+ maximum_longitude: f64,+ ) -> Self {+ Self {+ minimum_latitude,+ maximum_latitude,+ minimum_longitude,+ maximum_longitude,+ }+ }+}++struct SearchPattern {+ characters: Vec<char>,+ fallback: Vec<usize>,+}++impl SearchPattern {+ fn new(query: &str) -> Option<Self> {+ let characters: Vec<char> = search_characters(query).collect();+ if characters.is_empty() {+ return None;+ }+ let mut fallback = vec![0; characters.len()];+ let mut matched = 0;+ for index in 1..characters.len() {+ while matched > 0 && characters[index] != characters[matched] {+ matched = fallback[matched - 1];+ }+ if characters[index] == characters[matched] {+ matched += 1;+ fallback[index] = matched;+ }+ }+ Some(Self {+ characters,+ fallback,+ })+ }++ fn matches(&self, value: &str) -> bool {+ let mut matched = 0;+ for character in search_characters(value) {+ while matched > 0 && character != self.characters[matched] {+ matched = self.fallback[matched - 1];+ }+ if character == self.characters[matched] {+ matched += 1;+ if matched == self.characters.len() {+ return true;+ }+ }+ }+ false+ }+}++fn search_characters(value: &str) -> impl Iterator<Item = char> + '_ {+ value+ .nfd()+ .filter(|&character| !is_combining_mark(character))+ .flat_map(char::to_lowercase)+}++pub struct CityIndex {+ bytes: Box<[u8]>,+ layout: Layout,+}++impl CityIndex {+ pub fn from_path(path: impl AsRef<Path>) -> crate::Result<Self> {+ Self::from_bytes(fs::read(path)?)+ }++ pub fn from_bytes(bytes: impl Into<Box<[u8]>>) -> crate::Result<Self> {+ let bytes = bytes.into();+ let layout = validate(&bytes)?;+ Ok(Self { bytes, layout })+ }++ pub const fn len(&self) -> usize {+ self.layout.point_count+ }++ pub const fn is_empty(&self) -> bool {+ self.len() == 0+ }++ pub fn search(&self, query: &str, limit: usize) -> Vec<City> {+ if limit == 0 {+ return Vec::new();+ }+ let matching_names = self.matching_names(query);+ if no_names_match(&matching_names) {+ return Vec::new();+ }+ let mut cities = Vec::new();+ for point_index in 0..self.layout.point_count {+ let point = self.point(point_index);+ if matching_names+ .as_ref()+ .is_none_or(|matches| matches[point.name])+ {+ cities.push(self.city(point_index));+ if cities.len() == limit {+ break;+ }+ }+ }+ cities+ }++ pub fn match_coordinates(&self, coordinates: &[Coordinate], query: &str) -> Vec<CityMatch> {+ if coordinates.is_empty() {+ return Vec::new();+ }+ let matching_names = self.matching_names(query);+ if no_names_match(&matching_names) {+ return Vec::new();+ }+ let mut matches = BTreeMap::<usize, Vec<u32>>::new();+ let mut candidates = Vec::new();+ let mut eligible = Vec::new();+ let mut stack = Vec::new();++ for (coordinate_index, &coordinate) in coordinates.iter().enumerate() {+ if !coordinate.is_valid() {+ continue;+ }+ self.range_around(coordinate, MAX_CATCHMENT_KM, &mut candidates, &mut stack);+ eligible.clear();+ for &point_index in &candidates {+ let point = self.point(point_index);+ if matching_names+ .as_ref()+ .is_some_and(|matches| !matches[point.name])+ {+ continue;+ }+ let distance_km = distance_km(+ coordinate.latitude,+ coordinate.longitude,+ f64::from(point.latitude),+ f64::from(point.longitude),+ );+ let rank = self.rank(point_index);+ if distance_km <= catchment_km(rank) {+ eligible.push(Candidate {+ point: point_index,+ distance_km,+ rank,+ source_id: point.source_id,+ });+ }+ }++ let Some(nearest) = eligible+ .iter()+ .map(|candidate| candidate.distance_km)+ .reduce(f64::min)+ else {+ continue;+ };+ let prominence_window = (0.5 + nearest * 0.25).min(2.0);+ let best = eligible+ .iter()+ .filter(|candidate| candidate.distance_km <= nearest + prominence_window)+ .min_by(compare_candidates)+ .expect("eligible candidates are nonempty");+ matches+ .entry(best.point)+ .or_default()+ .push(coordinate_index as u32);+ }++ matches+ .into_iter()+ .map(|(point, coordinate_indices)| CityMatch {+ city: self.city(point),+ coordinate_indices,+ })+ .collect()+ }++ fn matching_names(&self, query: &str) -> Option<Vec<bool>> {+ let pattern = SearchPattern::new(query)?;+ Some(+ (0..self.layout.name_count)+ .map(|index| {+ let (name, alias) = self.name_parts(index);+ pattern.matches(name) || alias.is_some_and(|alias| pattern.matches(alias))+ })+ .collect(),+ )+ }++ fn range_around(+ &self,+ coordinate: Coordinate,+ maximum_distance_km: f64,+ result: &mut Vec<usize>,+ stack: &mut Vec<(usize, usize, u8)>,+ ) {+ result.clear();+ let latitude_delta = maximum_distance_km / 110.574;+ let longitude_scale = coordinate.latitude.to_radians().cos().abs().max(0.01);+ let longitude_delta = (maximum_distance_km / (111.320 * longitude_scale)).min(180.0);+ let minimum_latitude = (coordinate.latitude - latitude_delta).max(-90.0);+ let maximum_latitude = (coordinate.latitude + latitude_delta).min(90.0);+ if longitude_delta >= 180.0 {+ self.range_into(+ SearchBounds::new(minimum_latitude, maximum_latitude, -180.0, 180.0),+ result,+ stack,+ );+ return;+ }++ let minimum_longitude = coordinate.longitude - longitude_delta;+ let maximum_longitude = coordinate.longitude + longitude_delta;+ if minimum_longitude < -180.0 {+ self.range_into(+ SearchBounds::new(+ minimum_latitude,+ maximum_latitude,+ minimum_longitude + 360.0,+ 180.0,+ ),+ result,+ stack,+ );+ self.range_into(+ SearchBounds::new(+ minimum_latitude,+ maximum_latitude,+ -180.0,+ maximum_longitude,+ ),+ result,+ stack,+ );+ } else if maximum_longitude > 180.0 {+ self.range_into(+ SearchBounds::new(minimum_latitude, maximum_latitude, minimum_longitude, 180.0),+ result,+ stack,+ );+ self.range_into(+ SearchBounds::new(+ minimum_latitude,+ maximum_latitude,+ -180.0,+ maximum_longitude - 360.0,+ ),+ result,+ stack,+ );+ } else {+ self.range_into(+ SearchBounds::new(+ minimum_latitude,+ maximum_latitude,+ minimum_longitude,+ maximum_longitude,+ ),+ result,+ stack,+ );+ }+ }++ fn range_into(+ &self,+ bounds: SearchBounds,+ result: &mut Vec<usize>,+ stack: &mut Vec<(usize, usize, u8)>,+ ) {+ if self.layout.point_count == 0 {+ return;+ }+ stack.clear();+ stack.push((0, self.layout.point_count, 0));+ while let Some((node_index, subtree_size, axis)) = stack.pop() {+ let point_index = self.node(node_index);+ let point = self.point(point_index);+ let latitude = f64::from(point.latitude);+ let longitude = f64::from(point.longitude);+ if (bounds.minimum_latitude..=bounds.maximum_latitude).contains(&latitude)+ && (bounds.minimum_longitude..=bounds.maximum_longitude).contains(&longitude)+ {+ result.push(point_index);+ }++ let left_size = subtree_size / 2;+ let right_size = subtree_size - left_size - 1;+ let next_axis = axis ^ 1;+ if axis == 0 {+ if bounds.minimum_latitude <= latitude && left_size > 0 {+ stack.push((node_index + 1, left_size, next_axis));+ }+ if bounds.maximum_latitude >= latitude && right_size > 0 {+ stack.push((node_index + left_size + 1, right_size, next_axis));+ }+ } else {+ if bounds.minimum_longitude <= longitude && left_size > 0 {+ stack.push((node_index + 1, left_size, next_axis));+ }+ if bounds.maximum_longitude >= longitude && right_size > 0 {+ stack.push((node_index + left_size + 1, right_size, next_axis));+ }+ }+ }+ }++ fn city(&self, point_index: usize) -> City {+ let point = self.point(point_index);+ City {+ point_index: point_index as u32,+ source_id: point.source_id,+ name: self.name(point.name).to_owned(),+ country_name: self.country(point.country).to_owned(),+ country_code: self.country_code(point.country),+ latitude: f64::from(point.latitude),+ longitude: f64::from(point.longitude),+ rank: self.rank(point_index),+ }+ }++ fn node(&self, index: usize) -> usize {+ u24_at(&self.bytes, self.layout.nodes + index * NODE_LEN).expect("validated node") as usize+ }++ fn point(&self, index: usize) -> Point {+ let offset = self.layout.points + index * POINT_LEN;+ Point {+ latitude: f32_at(&self.bytes, offset).expect("validated point"),+ longitude: f32_at(&self.bytes, offset + 4).expect("validated point"),+ name: u24_at(&self.bytes, offset + 8).expect("validated point") as usize,+ country: usize::from(self.bytes[offset + 11]),+ source_id: u24_at(&self.bytes, offset + 12).expect("validated point"),+ }+ }++ fn rank(&self, point_index: usize) -> u8 {+ self.layout+ .rank_ends+ .iter()+ .position(|&end| point_index < end)+ .map_or(0, |index| 4 - index as u8)+ }++ fn name(&self, index: usize) -> &str {+ self.name_parts(index).0+ }++ fn name_parts(&self, index: usize) -> (&str, Option<&str>) {+ let value = table_entry_u24(+ &self.bytes,+ self.layout.name_offsets,+ self.layout.names,+ index,+ );+ value+ .split_once('\0')+ .map_or((value, None), |(name, alias)| (name, Some(alias)))+ }++ fn country(&self, index: usize) -> &str {+ table_entry_u32(+ &self.bytes,+ self.layout.country_offsets,+ self.layout.countries,+ index,+ )+ }++ fn country_code(&self, index: usize) -> CountryCode {+ let offset = self.layout.country_codes + index * 2;+ CountryCode::from_validated([self.bytes[offset], self.bytes[offset + 1]])+ }+}++#[derive(Clone, Copy)]+struct Candidate {+ point: usize,+ distance_km: f64,+ rank: u8,+ source_id: u32,+}++fn no_names_match(matching_names: &Option<Vec<bool>>) -> bool {+ matching_names+ .as_ref()+ .is_some_and(|matches| !matches.iter().any(|&matched| matched))+}++fn validate(bytes: &[u8]) -> crate::Result<Layout> {+ if bytes.len() < HEADER_LEN {+ return Err(invalid("truncated"));+ }+ if &bytes[..4] != MAGIC {+ return Err(invalid("invalid magic"));+ }+ let version = read_u16(bytes, 4)?;+ if version != VERSION {+ return Err(Error::invalid(+ SECTION,+ format!("unsupported format version {version}"),+ ));+ }+ if usize::from(read_u16(bytes, 6)?) != HEADER_LEN {+ return Err(invalid("unexpected header length"));+ }+ if usize::from(read_u16(bytes, 18)?) != POINT_LEN+ || usize::from(read_u16(bytes, 20)?) != NODE_LEN+ || usize::from(read_u16(bytes, 22)?) != NAME_OFFSET_LEN+ {+ return Err(invalid("unexpected record length"));+ }++ let layout = Layout {+ point_count: read_usize(bytes, 8)?,+ name_count: read_usize(bytes, 12)?,+ country_count: usize::from(read_u16(bytes, 16)?),+ nodes: read_usize(bytes, 24)?,+ points: read_usize(bytes, 28)?,+ name_offsets: read_usize(bytes, 32)?,+ names: read_usize(bytes, 36)?,+ country_offsets: read_usize(bytes, 40)?,+ countries: read_usize(bytes, 44)?,+ country_codes: read_usize(bytes, 48)?,+ rank_ends: [+ read_usize(bytes, 56)?,+ read_usize(bytes, 60)?,+ read_usize(bytes, 64)?,+ read_usize(bytes, 68)?,+ ],+ };+ let declared_length = read_usize(bytes, 52)?;+ validate_sections(bytes, layout, declared_length)?;+ validate_strings(bytes, layout)?;+ validate_points(bytes, layout)?;+ validate_tree(bytes, layout)?;+ Ok(layout)+}++fn validate_sections(bytes: &[u8], layout: Layout, declared_length: usize) -> crate::Result<()> {+ if layout.point_count > MAX_U24+ || layout.name_count > MAX_U24+ || layout.country_count > 256+ || (layout.point_count > 0 && (layout.name_count == 0 || layout.country_count == 0))+ || layout.rank_ends[3] > layout.point_count+ || layout.rank_ends.windows(2).any(|ends| ends[0] > ends[1])+ {+ return Err(invalid("invalid section count"));+ }+ let nodes = range(layout.nodes, layout.point_count, NODE_LEN)+ .ok_or(invalid("node section overflow"))?;+ let points = range(layout.points, layout.point_count, POINT_LEN)+ .ok_or(invalid("point section overflow"))?;+ let name_offsets = offset_table_range(layout.name_offsets, layout.name_count, NAME_OFFSET_LEN)?;+ let name_bytes = terminal_offset(+ bytes,+ layout.name_offsets,+ layout.name_count,+ NAME_OFFSET_LEN,+ )?;+ let country_offsets = offset_table_range(layout.country_offsets, layout.country_count, 4)?;+ let country_bytes = terminal_offset(bytes, layout.country_offsets, layout.country_count, 4)?;+ let country_codes = range(layout.country_codes, layout.country_count, 2)+ .ok_or(invalid("country-code section overflow"))?;+ let names_end = layout+ .names+ .checked_add(name_bytes)+ .ok_or(invalid("name section overflow"))?;+ let countries_end = layout+ .countries+ .checked_add(country_bytes)+ .ok_or(invalid("country section overflow"))?;++ if layout.nodes != HEADER_LEN+ || layout.points != nodes.end+ || layout.name_offsets != points.end+ || layout.names != name_offsets.end+ || layout.country_offsets != names_end+ || layout.countries != country_offsets.end+ || layout.country_codes != countries_end+ || country_codes.end != bytes.len()+ || declared_length != bytes.len()+ {+ return Err(invalid("sections are not contiguous"));+ }+ Ok(())+}++fn validate_strings(bytes: &[u8], layout: Layout) -> crate::Result<()> {+ validate_table(+ bytes,+ layout.name_offsets,+ layout.names,+ layout.name_count,+ NAME_OFFSET_LEN,+ "name table",+ )?;+ validate_table(+ bytes,+ layout.country_offsets,+ layout.countries,+ layout.country_count,+ 4,+ "country-name table",+ )?;+ for index in 0..layout.name_count {+ let value = table_entry_u24(bytes, layout.name_offsets, layout.names, index);+ if let Some((name, alias)) = value.split_once('\0')+ && (name.is_empty() || alias.is_empty() || alias.contains('\0'))+ {+ return Err(invalid("invalid city name"));+ }+ }++ let mut seen_codes = [false; 26 * 26];+ for index in 0..layout.country_count {+ let offset = layout.country_codes + index * 2;+ let code = [bytes[offset], bytes[offset + 1]];+ if !code.iter().all(u8::is_ascii_uppercase) {+ return Err(invalid("invalid country code"));+ }+ let slot = usize::from(code[0] - b'A') * 26 + usize::from(code[1] - b'A');+ if seen_codes[slot] {+ return Err(invalid("duplicate country code"));+ }+ seen_codes[slot] = true;+ }+ Ok(())+}++fn validate_points(bytes: &[u8], layout: Layout) -> crate::Result<()> {+ for index in 0..layout.point_count {+ let offset = layout.points + index * POINT_LEN;+ let latitude = f32_at(bytes, offset).ok_or(invalid("truncated"))?;+ let longitude = f32_at(bytes, offset + 4).ok_or(invalid("truncated"))?;+ let name = u24_at(bytes, offset + 8).ok_or(invalid("truncated"))? as usize;+ let country = usize::from(bytes[offset + 11]);+ if !latitude.is_finite()+ || !(-90.0..=90.0).contains(&latitude)+ || !longitude.is_finite()+ || !(-180.0..=180.0).contains(&longitude)+ || name >= layout.name_count+ || country >= layout.country_count+ {+ return Err(invalid("invalid city point"));+ }+ }+ Ok(())+}++fn validate_tree(bytes: &[u8], layout: Layout) -> crate::Result<()> {+ if layout.point_count == 0 {+ return Ok(());+ }++ let mut visited_points = vec![false; layout.point_count];+ let mut stack = vec![(0usize, layout.point_count, 0u8, -90.0, 90.0, -180.0, 180.0)];+ while let Some((node_index, size, axis, min_lat, max_lat, min_lng, max_lng)) = stack.pop() {+ if size == 0+ || node_index+ .checked_add(size)+ .is_none_or(|end| end > layout.point_count)+ {+ return Err(invalid("invalid tree layout"));+ }+ let point = u24_at(bytes, layout.nodes + node_index * NODE_LEN)+ .ok_or(invalid("truncated"))? as usize;+ if point >= layout.point_count || visited_points[point] {+ return Err(invalid("invalid tree node"));+ }+ visited_points[point] = true;+ let point_offset = layout.points + point * POINT_LEN;+ let latitude = f64::from(f32_at(bytes, point_offset).expect("validated point"));+ let longitude = f64::from(f32_at(bytes, point_offset + 4).expect("validated point"));+ if !(min_lat..=max_lat).contains(&latitude) || !(min_lng..=max_lng).contains(&longitude) {+ return Err(invalid("invalid KD ordering"));+ }++ let left_size = size / 2;+ let right_size = size - left_size - 1;+ let next_axis = axis ^ 1;+ if axis == 0 {+ if left_size > 0 {+ stack.push((+ node_index + 1,+ left_size,+ next_axis,+ min_lat,+ latitude,+ min_lng,+ max_lng,+ ));+ }+ if right_size > 0 {+ stack.push((+ node_index + left_size + 1,+ right_size,+ next_axis,+ latitude,+ max_lat,+ min_lng,+ max_lng,+ ));+ }+ } else {+ if left_size > 0 {+ stack.push((+ node_index + 1,+ left_size,+ next_axis,+ min_lat,+ max_lat,+ min_lng,+ longitude,+ ));+ }+ if right_size > 0 {+ stack.push((+ node_index + left_size + 1,+ right_size,+ next_axis,+ min_lat,+ max_lat,+ longitude,+ max_lng,+ ));+ }+ }+ }+ if visited_points.iter().any(|&visited| !visited) {+ return Err(invalid("tree does not cover every point"));+ }+ Ok(())+}++fn validate_table(+ bytes: &[u8],+ offsets: usize,+ blob: usize,+ count: usize,+ offset_len: usize,+ name: &'static str,+) -> crate::Result<()> {+ let blob_length = terminal_offset(bytes, offsets, count, offset_len)?;+ let mut previous = 0;+ for index in 0..count {+ let start = string_offset(bytes, offsets + index * offset_len, offset_len)?;+ let end = string_offset(bytes, offsets + (index + 1) * offset_len, offset_len)?;+ if start != previous || end <= start || end > blob_length {+ return Err(invalid("invalid string offsets"));+ }+ std::str::from_utf8(&bytes[blob + start..blob + end])+ .map_err(|_| Error::invalid(SECTION, format!("invalid UTF-8 in {name}")))?;+ previous = end;+ }+ Ok(())+}++fn offset_table_range(+ offset: usize,+ count: usize,+ stride: usize,+) -> crate::Result<std::ops::Range<usize>> {+ range(+ offset,+ count+ .checked_add(1)+ .ok_or(invalid("offset count overflow"))?,+ stride,+ )+ .ok_or(invalid("offset table overflow"))+}++fn terminal_offset(+ bytes: &[u8],+ offset: usize,+ count: usize,+ stride: usize,+) -> crate::Result<usize> {+ let terminal = offset+ .checked_add(+ count+ .checked_mul(stride)+ .ok_or(invalid("offset table overflow"))?,+ )+ .ok_or(invalid("offset table overflow"))?;+ string_offset(bytes, terminal, stride)+}++fn string_offset(bytes: &[u8], offset: usize, length: usize) -> crate::Result<usize> {+ match length {+ NAME_OFFSET_LEN => Ok(u24_at(bytes, offset).ok_or(invalid("truncated"))? as usize),+ 4 => Ok(u32_at(bytes, offset).ok_or(invalid("truncated"))? as usize),+ _ => unreachable!("validated offset length"),+ }+}++fn table_entry_u24(bytes: &[u8], offsets: usize, blob: usize, index: usize) -> &str {+ let start =+ u24_at(bytes, offsets + index * NAME_OFFSET_LEN).expect("validated string table") as usize;+ let end = u24_at(bytes, offsets + (index + 1) * NAME_OFFSET_LEN)+ .expect("validated string table") as usize;+ std::str::from_utf8(&bytes[blob + start..blob + end]).expect("validated UTF-8")+}++fn table_entry_u32(bytes: &[u8], offsets: usize, blob: usize, index: usize) -> &str {+ let start = u32_at(bytes, offsets + index * 4).expect("validated string table") as usize;+ let end = u32_at(bytes, offsets + (index + 1) * 4).expect("validated string table") as usize;+ std::str::from_utf8(&bytes[blob + start..blob + end]).expect("validated UTF-8")+}++fn read_u16(bytes: &[u8], offset: usize) -> crate::Result<u16> {+ u16_at(bytes, offset).ok_or(invalid("truncated"))+}++fn read_usize(bytes: &[u8], offset: usize) -> crate::Result<usize> {+ Ok(u32_at(bytes, offset).ok_or(invalid("truncated"))? as usize)+}++fn invalid(reason: &'static str) -> Error {+ Error::invalid(SECTION, reason)+}++fn compare_candidates(left: &&Candidate, right: &&Candidate) -> Ordering {+ right+ .rank+ .cmp(&left.rank)+ .then_with(|| left.distance_km.total_cmp(&right.distance_km))+ .then_with(|| left.source_id.cmp(&right.source_id))+}++fn catchment_km(rank: u8) -> f64 {+ [8.0, 10.0, 14.0, 20.0, 30.0][usize::from(rank)]+}++fn distance_km(lat1: f64, lng1: f64, lat2: f64, lng2: f64) -> f64 {+ let lat1 = lat1.to_radians();+ let lat2 = lat2.to_radians();+ let delta_latitude = lat2 - lat1;+ let delta_longitude = (lng2 - lng1).to_radians();+ let a = (delta_latitude / 2.0).sin().powi(2)+ + lat1.cos() * lat2.cos() * (delta_longitude / 2.0).sin().powi(2);+ 6371.0 * 2.0 * a.sqrt().atan2((1.0 - a).sqrt())+}diff --git a/rust/crates/location/src/error.rs b/rust/crates/location/src/error.rsindex 95d41e2b9a..3d0605a3c7 100644--- a/rust/crates/location/src/error.rs+++ b/rust/crates/location/src/error.rs@@ -1,9 +1,18 @@+use std::borrow::Cow;+use thiserror::Error;pub type Result<T> = std::result::Result<T, Error>;#[derive(Debug, Error)]pub enum Error {+ #[error("failed to read location asset: {0}")]+ Io(#[from] std::io::Error),+ #[error("invalid {section}: {reason}")]+ InvalidData {+ section: &'static str,+ reason: Cow<'static, str>,+ },#[error("map point {0} has an invalid coordinate")]InvalidMapPoint(usize),#[error("minimum marker distance must be finite and positive")]@@ -11,3 +20,12 @@ pub enum Error {#[error("map viewport is invalid")]InvalidViewport,}++impl Error {+ pub(crate) fn invalid(section: &'static str, reason: impl Into<Cow<'static, str>>) -> Self {+ Self::InvalidData {+ section,+ reason: reason.into(),+ }+ }+}diff --git a/rust/crates/location/src/lib.rs b/rust/crates/location/src/lib.rsindex fc016b57b9..412c4a1205 100644--- a/rust/crates/location/src/lib.rs+++ b/rust/crates/location/src/lib.rs@@ -1,6 +1,12 @@+use std::fmt;+use std::str::FromStr;++mod binary;+mod city;pub mod cluster;mod error;+pub use city::{City, CityIndex, CityMatch};pub use error::{Error, Result};#[derive(Clone, Copy, Debug, PartialEq)]@@ -24,3 +30,50 @@ impl Coordinate {&& (-180.0..=180.0).contains(&self.longitude)}}++#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]+pub struct CountryCode([u8; 2]);++impl CountryCode {+ pub fn from_bytes(bytes: [u8; 2]) -> std::result::Result<Self, InvalidCountryCode> {+ if bytes.iter().all(u8::is_ascii_uppercase) {+ Ok(Self(bytes))+ } else {+ Err(InvalidCountryCode)+ }+ }++ pub const fn as_bytes(self) -> [u8; 2] {+ self.0+ }++ pub fn as_str(&self) -> &str {+ std::str::from_utf8(&self.0).expect("country code is ASCII")+ }++ pub(crate) const fn from_validated(bytes: [u8; 2]) -> Self {+ Self(bytes)+ }+}++impl fmt::Display for CountryCode {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ formatter.write_str(self.as_str())+ }+}++impl FromStr for CountryCode {+ type Err = InvalidCountryCode;++ fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {+ let bytes = value+ .as_bytes()+ .try_into()+ .map_err(|_| InvalidCountryCode)?;+ Self::from_bytes(bytes)+ }+}++#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]+#[error("country codes must contain two uppercase ASCII letters")]+pub struct InvalidCountryCode;