use crate::query::Hit;
const LAT_BITS: u32 = 24;
const LON_BITS: u32 = 24;
const TAG_BITS: u32 = 3;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Kind {
Address = 0,
Street = 1,
Place = 2,
Poi = 3,
}
pub fn kind_of(h: &Hit) -> Kind {
if h.flags.contains(&"poi_layer") {
return Kind::Poi;
}
match h.precision {
"street" | "intersection" => Kind::Street,
"city" => Kind::Place,
_ => Kind::Address,
}
}
fn cell(v: f64, lo: f64, span: f64, bits: u32) -> u64 {
let n = ((v - lo) / span * (1u64 << bits) as f64).floor();
n.clamp(0.0, ((1u64 << bits) - 1) as f64) as u64
}
fn tag(h: &Hit) -> u64 {
let mut x: u64 = 0xcbf29ce484222325;
for b in h
.street
.bytes()
.chain(*b"|")
.chain(h.housenumber.as_deref().unwrap_or("").bytes())
{
x ^= u64::from(b);
x = x.wrapping_mul(0x100000001b3);
}
x & ((1 << TAG_BITS) - 1)
}
pub fn encode(h: &Hit) -> i64 {
let lat = cell(h.lat, -90.0, 180.0, LAT_BITS);
let lon = cell(h.lon, -180.0, 360.0, LON_BITS);
let n = ((kind_of(h) as u64) << (TAG_BITS + LAT_BITS + LON_BITS))
| (tag(h) << (LAT_BITS + LON_BITS))
| (lat << LON_BITS)
| lon;
-(n as i64)
}
pub fn in_cell(id: i64, h: &Hit) -> bool {
let mask = (1u64 << (LAT_BITS + LON_BITS)) - 1;
id.unsigned_abs() & mask == encode(h).unsigned_abs() & mask
}
pub fn decode(id: i64) -> Option<(Kind, f64, f64)> {
if id >= 0 {
return None;
}
let n = id.unsigned_abs();
if n >> (TAG_BITS + LAT_BITS + LON_BITS + 2) != 0 {
return None;
}
let kind = match n >> (TAG_BITS + LAT_BITS + LON_BITS) {
0 => Kind::Address,
1 => Kind::Street,
2 => Kind::Place,
_ => Kind::Poi,
};
let lat = (n >> LON_BITS) & ((1 << LAT_BITS) - 1);
let lon = n & ((1 << LON_BITS) - 1);
let centre = |c: u64, lo: f64, span: f64, bits: u32| {
lo + (c as f64 + 0.5) * span / (1u64 << bits) as f64
};
Some((
kind,
centre(lat, -90.0, 180.0, LAT_BITS),
centre(lon, -180.0, 360.0, LON_BITS),
))
}
pub fn parse_osm_id(s: &str) -> Option<i64> {
let s = s.trim();
let rest = s.strip_prefix('N').or_else(|| s.strip_prefix('n'))?;
rest.parse::<i64>().ok().filter(|n| *n < 0)
}
#[cfg(test)]
mod tests {
use super::*;
fn hit(lat: f64, lon: f64, precision: &'static str, flags: Vec<&'static str>) -> Hit {
Hit {
lat,
lon,
precision,
score: 1.0,
confidence: 0.9,
street: "Rue A".into(),
housenumber: Some("1".into()),
commune: "Ville".into(),
postcode: "10000".into(),
flags,
region: None,
distance_m: None,
}
}
#[test]
fn a_number_is_negative_within_53_bits_and_comes_back_to_its_kind_and_point() {
for (lat, lon) in [
(43.73, 7.42),
(-33.8688, 151.2093),
(89.999, -179.999),
(-90.0, 180.0),
(0.0, 0.0),
] {
for (precision, flags, kind) in [
("house", vec![], Kind::Address),
("interp", vec![], Kind::Address),
("street", vec![], Kind::Street),
("city", vec![], Kind::Place),
("house", vec!["poi_layer"], Kind::Poi),
] {
let id = encode(&hit(lat, lon, precision, flags));
assert!(id < 0 && id.unsigned_abs() < 1 << 53, "{id}");
let (k, la, lo) = decode(id).unwrap();
assert_eq!(k, kind);
assert!(
(la - lat).abs() < 1.1e-5 && (lo - lon).abs() < 2.2e-5,
"{lat},{lon} -> {la},{lo}"
);
}
}
}
#[test]
fn two_points_three_metres_apart_two_kinds_and_two_addresses_at_one_point_have_different_numbers(
) {
let a = encode(&hit(43.73, 7.42, "house", vec![]));
assert_ne!(
a,
encode(&hit(43.73003, 7.42, "house", vec![])),
"about 3.3 m north"
);
assert_ne!(
a,
encode(&hit(43.73, 7.42004, "house", vec![])),
"about 3.2 m east"
);
let mut two = hit(43.73, 7.42, "house", vec![]);
two.housenumber = Some("3".into());
assert_ne!(tag(&hit(43.73, 7.42, "house", vec![])), tag(&two));
assert_ne!(a, encode(&two));
assert_ne!(a, encode(&hit(43.73, 7.42, "street", vec![])));
assert_eq!(
a,
encode(&hit(43.73, 7.42, "near", vec![])),
"the neighbour's door is an address too"
);
}
#[test]
fn only_our_negative_numbers_are_read() {
let id = encode(&hit(43.73, 7.42, "house", vec![]));
assert_eq!(parse_osm_id(&format!("N{id}")), Some(id));
assert_eq!(parse_osm_id(&format!("n{id}")), Some(id));
for bad in ["N123", "W-5", "R-5", "N", "Nabc", "-5", ""] {
assert_eq!(parse_osm_id(bad), None, "{bad}");
}
assert_eq!(
decode(5),
None,
"a positive number is an OpenStreetMap object"
);
assert_eq!(decode(-(1i64 << 54)), None, "beyond 53 bits");
}
}