54 lines
1.8 KiB
Rust
54 lines
1.8 KiB
Rust
//! Name normalization and geodesy helpers.
|
|||
|
|
|
||
|
|
/// Normalizes a place or country name for matching: transliterates to ASCII,
|
||
|
|
/// lowercases, and collapses everything that is not a letter or digit into
|
||
|
|
/// single spaces ("Hódmezővásárhely" -> "hodmezovasarhely",
|
||
|
|
/// "Budapest XIII. kerület" -> "budapest xiii kerulet").
|
||
|
|
pub fn normalize(name: &str) -> String {
|
||
|
|
let ascii = deunicode::deunicode(name);
|
||
|
|
let mut out = String::with_capacity(ascii.len());
|
||
|
|
let mut pending_space = false;
|
||
|
|
for c in ascii.chars() {
|
||
|
|
if c.is_ascii_alphanumeric() {
|
||
|
|
if pending_space && !out.is_empty() {
|
||
|
|
out.push(' ');
|
||
|
|
}
|
||
|
|
pending_space = false;
|
||
|
|
out.push(c.to_ascii_lowercase());
|
||
|
|
} else {
|
||
|
|
pending_space = true;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
out
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Great-circle distance in kilometers.
|
||
|
|
pub fn distance_km(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {
|
||
|
|
const EARTH_RADIUS_KM: f64 = 6371.0;
|
||
|
|
let (p1, p2) = (lat1.to_radians(), lat2.to_radians());
|
||
|
|
let dp = (lat2 - lat1).to_radians();
|
||
|
|
let dl = (lon2 - lon1).to_radians();
|
||
|
|
let a = (dp / 2.0).sin().powi(2) + p1.cos() * p2.cos() * (dl / 2.0).sin().powi(2);
|
||
|
|
2.0 * EARTH_RADIUS_KM * a.sqrt().min(1.0).asin()
|
||
|
|
}
|
||
|
|
|
||
|
|
#[cfg(test)]
|
||
|
|
mod tests {
|
||
|
|
use super::*;
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn normalizes_names() {
|
||
|
|
assert_eq!(normalize("Hódmezővásárhely"), "hodmezovasarhely");
|
||
|
|
assert_eq!(normalize(" Budapest XIII. kerület "), "budapest xiii kerulet");
|
||
|
|
assert_eq!(normalize("Kolozsvár"), "kolozsvar");
|
||
|
|
assert_eq!(normalize("Москва"), "moskva");
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn distances() {
|
||
|
|
// Budapest - Szeged ~ 161 km
|
||
|
|
let d = distance_km(47.4979, 19.0402, 46.253, 20.14824);
|
||
|
|
assert!((155.0..170.0).contains(&d), "{d}");
|
||
|
|
}
|
||
|
|
}
|