Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / scripts / maps / osm_ingest / src / poi_admin.rs

poi_admin.rs173 lines · 7.0 KiBRaw
1//! `poi_admin.bin`: the administrative hierarchy behind `poi_region.bin`.
2//!
3//! `poi_region.bin` gives every POI ONE tagged boundary id — its native label
4//! link or the smallest administrative boundary containing it — but nothing
5//! says what that boundary is called, what level it is, or what contains it, so
6//! the app could name at most the city and never the state or country. This
7//! sidecar is the missing table: for every boundary a POI links to, and every
8//! boundary above those, its name, its `admin_level` and its parent.
9//!
10//! ## Layout (little-endian)
11//!
12//! ```text
13//! magic "PAD1" | u32 version | u32 entry_count | u32 names_len (16-byte header)
14//! entry[entry_count], 32 bytes each, ascending by tagged_id:
15//! u64 tagged_id same tagging as poi_region.bin ((osm_id << 2) | space)
16//! u64 parent_tagged the containing boundary one level up, 0 at the top
17//! u32 name_off byte offset of `name` in the pool
18//! u32 name_en_off byte offset of `name:en`, or u32::MAX when absent
19//! or identical to `name`
20//! u8 admin_level OSM admin_level (2 country, 4 state/province, ...)
21//! u8[7] reserved zero
22//! names: names_len bytes of NUL-terminated UTF-8, deduplicated
23//! ```
24//!
25//! A reader binary-searches `tagged_id` (fixed-width entries) and follows
26//! `parent_tagged` to the top. The parent is the smallest-area boundary of a
27//! LOWER `admin_level` that contains a point strictly inside the child (see
28//! `poi_build::admin_table`), so a city's parent is its county where one exists
29//! and its state otherwise; a reader wanting "the state" walks up to the first
30//! level 3-4 entry.
31//!
32//! Additive and versioned: an archive packs it as its own section kind
33//! (`ARCHIVE_KIND_POI_ADMIN`, 16), which older apps skip like any unknown kind,
34//! and a reader refuses a version it does not know.
35
36use std::collections::HashMap;
37use std::io::{self, Write};
38
39pub const ADMIN_MAGIC: &[u8; 4] = b"PAD1";
40pub const ADMIN_VERSION: u32 = 1;
41pub const ADMIN_HEADER_BYTES: usize = 16;
42pub const ADMIN_ENTRY_BYTES: usize = 32;
43/// `name_en_off` for an entry without a distinct English name.
44pub const ADMIN_NO_NAME: u32 = u32::MAX;
45
46/// One boundary of the hierarchy.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct AdminEntry {
49 /// Tagged OSM id, as in `poi_region.bin`.
50 pub tagged: u64,
51 /// Tagged id of the containing boundary one level up, or 0.
52 pub parent: u64,
53 pub admin_level: u8,
54 /// The `name` tag (may be empty when OSM has none).
55 pub name: Vec<u8>,
56 /// The `name:en` tag, empty when absent.
57 pub name_en: Vec<u8>,
58}
59
60/// Write `poi_admin.bin` for `entries` (any order; written sorted by tagged id,
61/// one entry per id). Returns the entry count.
62pub fn write_admin<W: Write>(out: &mut W, entries: &[AdminEntry]) -> io::Result<usize> {
63 let mut sorted: Vec<&AdminEntry> = entries.iter().collect();
64 sorted.sort_by_key(|e| e.tagged);
65 sorted.dedup_by_key(|e| e.tagged);
66
67 let mut pool: Vec<u8> = Vec::new();
68 let mut offsets: HashMap<&[u8], u32> = HashMap::new();
69
70 let mut body: Vec<u8> = Vec::with_capacity(sorted.len() * ADMIN_ENTRY_BYTES);
71 for e in &sorted {
72 let name_off =
73 *offsets.entry(e.name.as_slice()).or_insert_with(|| intern_owned(&e.name, &mut pool));
74 let name_en_off = if e.name_en.is_empty() || e.name_en == e.name {
75 ADMIN_NO_NAME
76 } else {
77 *offsets
78 .entry(e.name_en.as_slice())
79 .or_insert_with(|| intern_owned(&e.name_en, &mut pool))
80 };
81 body.extend_from_slice(&e.tagged.to_le_bytes());
82 body.extend_from_slice(&e.parent.to_le_bytes());
83 body.extend_from_slice(&name_off.to_le_bytes());
84 body.extend_from_slice(&name_en_off.to_le_bytes());
85 body.push(e.admin_level);
86 body.extend_from_slice(&[0u8; 7]);
87 }
88
89 out.write_all(ADMIN_MAGIC)?;
90 out.write_all(&ADMIN_VERSION.to_le_bytes())?;
91 out.write_all(&(sorted.len() as u32).to_le_bytes())?;
92 out.write_all(&(pool.len() as u32).to_le_bytes())?;
93 out.write_all(&body)?;
94 out.write_all(&pool)?;
95 Ok(sorted.len())
96}
97
98fn intern_owned(s: &[u8], pool: &mut Vec<u8>) -> u32 {
99 let off = pool.len() as u32;
100 // A NUL inside a name would cut it short for the reader; OSM never has one,
101 // but the pool's framing must not depend on that.
102 pool.extend(s.iter().copied().filter(|b| *b != 0));
103 pool.push(0);
104 off
105}
106
107#[cfg(test)]
108mod tests {
109 use super::*;
110
111 fn u32_at(b: &[u8], at: usize) -> u32 {
112 u32::from_le_bytes(b[at..at + 4].try_into().unwrap())
113 }
114
115 fn u64_at(b: &[u8], at: usize) -> u64 {
116 u64::from_le_bytes(b[at..at + 8].try_into().unwrap())
117 }
118
119 fn cstr(pool: &[u8], off: u32) -> &[u8] {
120 let s = &pool[off as usize..];
121 &s[..s.iter().position(|b| *b == 0).unwrap()]
122 }
123
124 #[test]
125 fn layout_is_sorted_fixed_width_with_a_shared_pool() {
126 let e = |tagged, parent, level, name: &str, en: &str| AdminEntry {
127 tagged,
128 parent,
129 admin_level: level,
130 name: name.as_bytes().to_vec(),
131 name_en: en.as_bytes().to_vec(),
132 };
133 let entries = vec![
134 e(903, 902, 8, "Köln", "Cologne"),
135 e(901, 0, 2, "Deutschland", "Germany"),
136 e(902, 901, 4, "Nordrhein-Westfalen", "North Rhine-Westphalia"),
137 // Same name and name:en: stored once, no English offset.
138 e(907, 902, 8, "Bonn", "Bonn"),
139 // A duplicate id is written once.
140 e(901, 0, 2, "Deutschland", "Germany"),
141 ];
142 let mut out = Vec::new();
143 assert_eq!(write_admin(&mut out, &entries).unwrap(), 4);
144 assert_eq!(&out[0..4], ADMIN_MAGIC);
145 assert_eq!(u32_at(&out, 4), ADMIN_VERSION);
146 assert_eq!(u32_at(&out, 8), 4);
147 let names_len = u32_at(&out, 12) as usize;
148 let pool_at = ADMIN_HEADER_BYTES + 4 * ADMIN_ENTRY_BYTES;
149 assert_eq!(out.len(), pool_at + names_len);
150 let pool = &out[pool_at..];
151
152 let at = |i: usize| ADMIN_HEADER_BYTES + i * ADMIN_ENTRY_BYTES;
153 let ids: Vec<u64> = (0..4).map(|i| u64_at(&out, at(i))).collect();
154 assert_eq!(ids, vec![901, 902, 903, 907], "ascending tagged ids");
155 // Köln: parent, level, both names.
156 assert_eq!(u64_at(&out, at(2) + 8), 902);
157 assert_eq!(out[at(2) + 24], 8);
158 assert_eq!(cstr(pool, u32_at(&out, at(2) + 16)), "Köln".as_bytes());
159 assert_eq!(cstr(pool, u32_at(&out, at(2) + 20)), b"Cologne");
160 assert!(out[at(2) + 25..at(2) + 32].iter().all(|b| *b == 0), "reserved bytes are zero");
161 // Bonn: identical English name is not stored twice.
162 assert_eq!(u32_at(&out, at(3) + 20), ADMIN_NO_NAME);
163 // The country is the top: parent 0.
164 assert_eq!(u64_at(&out, at(0) + 8), 0);
165 }
166
167 #[test]
168 fn an_empty_table_is_just_a_header() {
169 let mut out = Vec::new();
170 assert_eq!(write_admin(&mut out, &[]).unwrap(), 0);
171 assert_eq!(out.len(), ADMIN_HEADER_BYTES);
172 }
173}