Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / networklocation / geodb_build / src / format.rs
format.rs290 lines · 11.4 KiBRaw
| 1 | //! The `geocoder.db` on-disk format, in one place. |
| 2 | //! |
| 3 | //! Every constant here is duplicated by hand in the reader, |
| 4 | //! `networklocation/src/main/rust/src/geocoder.rs`. That is the format's main hazard: the two |
| 5 | //! sides share no code, and a divergence does not fail loudly — it decodes to plausible |
| 6 | //! nonsense. `write::verify` reads a finished database back through an independent path, and |
| 7 | //! the reader has fixture tests, but neither replaces keeping this list and its counterpart in |
| 8 | //! step. |
| 9 | //! |
| 10 | //! ```text |
| 11 | //! 0 magic u32 = "MAGE" |
| 12 | //! 4 version u32 = 5 |
| 13 | //! 8 n u32 |
| 14 | //! 12 21 sections, each [u32 size][body]: |
| 15 | //! [0..6] dictionaries: name, house, street, city, state, country, postcode |
| 16 | //! [7..16] columns: lat, lon, name, house, street, city, state, country, postcode, kind |
| 17 | //! [17] grid |
| 18 | //! [18] fwd (records with a street, by structured address) |
| 19 | //! [19] nm_name (name ids, ascending) |
| 20 | //! [20] nm_rec (record index for each nm_name entry) |
| 21 | //! ``` |
| 22 | //! |
| 23 | //! All integers are **big-endian**, matching v2. |
| 24 | //! |
| 25 | //! ## What changed from v4 |
| 26 | //! |
| 27 | //! v5 changes no content, only how it can be read. The reader memory-maps the file and must |
| 28 | //! never have to hold a section in RAM; v4's reader inflated every dictionary on open, about |
| 29 | //! 2 GB of heap for the planet. |
| 30 | //! |
| 31 | //! - **Dictionaries are blocked**: [`DICT_BLOCK`] strings per zstd frame, behind an |
| 32 | //! uncompressed table of each block's first string, so a lookup binary-searches that table |
| 33 | //! and decompresses one block. See `codec::encode_dict`. |
| 34 | //! - **Column directories store each block's end offset** instead of its compressed length, so |
| 35 | //! a block is located without a prefix-sum table. |
| 36 | //! |
| 37 | //! ## What changed from v3 |
| 38 | //! |
| 39 | //! v4 is v3 cut down for size; the section layout is unchanged. |
| 40 | //! |
| 41 | //! - Coordinates are **e5** (about 1.1 m), not e7. Nobody needs centimetres from a geocoder, |
| 42 | //! and the two coordinate columns were nearly half the file. |
| 43 | //! - `fwd` holds only records that carry a street. A forward query always names one, so street |
| 44 | //! samples and unaddressed POIs and places could never match and were dead weight. |
| 45 | //! - The name index holds one entry per street name per grid cell, not one per street sample. |
| 46 | //! |
| 47 | //! ## What changed from v2 |
| 48 | //! |
| 49 | //! - Coordinates are **e7**, not e6. OSM stores e7, so v2's e6 threw away a decimal digit for |
| 50 | //! nothing. This is the change that forces [`morton_in_cell`] to widen (see below). |
| 51 | //! - Two new columns, `name` and `kind`, and a `name` dictionary. v2 could only hold addresses |
| 52 | //! because it had nowhere to put a feature's name or to say what sort of feature it was. |
| 53 | //! - Two new sections, `nm_name`/`nm_rec`, indexing records by name so forward search can find |
| 54 | //! a POI or a place rather than only an address. |
| 55 | |
| 56 | /// `"MAGE"`. |
| 57 | pub const MAGIC: u32 = 0x4D41_4745; |
| 58 | /// Format version. v2 was address-only and e6; v3 was e7 with a full forward index; v4 was e5; |
| 59 | /// v5 is v4 laid out to be read from a memory map. |
| 60 | pub const VERSION: u32 = 5; |
| 61 | /// Records per compressed column block. |
| 62 | pub const BLOCK: usize = 4096; |
| 63 | /// Strings per compressed dictionary block. Small enough that a lookup decompresses only a few |
| 64 | /// kilobytes; large enough that the uncompressed first-string table stays a fraction of the |
| 65 | /// dictionary. |
| 66 | pub const DICT_BLOCK: usize = 1024; |
| 67 | /// Zstandard level for column blocks and dictionaries. Measured on California's column blocks: |
| 68 | /// level 3 is 9.5% larger than 19 and about 37x faster to write. |
| 69 | pub const ZSTD_LEVEL: i32 = 3; |
| 70 | |
| 71 | /// Grid cell edge in e5 units: 0.05 degrees, about 5.5 km of latitude. |
| 72 | pub const CELL: i64 = 5_000; |
| 73 | /// Cell columns around the planet. |
| 74 | pub const COLS: i64 = 36_000_000 / CELL; |
| 75 | /// Lowest representable latitude, e5. |
| 76 | pub const MIN_LAT: i32 = -9_000_000; |
| 77 | /// Lowest representable longitude, e5. |
| 78 | pub const MIN_LON: i32 = -18_000_000; |
| 79 | |
| 80 | /// Number of string dictionaries. |
| 81 | pub const DICTS: usize = 7; |
| 82 | /// Number of record columns. |
| 83 | pub const COLUMNS: usize = 10; |
| 84 | /// Total sections after the header. |
| 85 | pub const SECTIONS: usize = DICTS + COLUMNS + 4; |
| 86 | |
| 87 | /// Dictionary slots, in section order. |
| 88 | pub const D_NAME: usize = 0; |
| 89 | /// House-number dictionary. |
| 90 | pub const D_HOUSE: usize = 1; |
| 91 | /// Street-name dictionary. |
| 92 | pub const D_STREET: usize = 2; |
| 93 | /// City dictionary. |
| 94 | pub const D_CITY: usize = 3; |
| 95 | /// State dictionary. |
| 96 | pub const D_STATE: usize = 4; |
| 97 | /// Country-code dictionary. |
| 98 | pub const D_COUNTRY: usize = 5; |
| 99 | /// Postcode dictionary. |
| 100 | pub const D_POSTCODE: usize = 6; |
| 101 | |
| 102 | /// Column slots, in section order. |
| 103 | pub const C_LAT: usize = 0; |
| 104 | /// Longitude column. |
| 105 | pub const C_LON: usize = 1; |
| 106 | /// Name dictionary id. |
| 107 | pub const C_NAME: usize = 2; |
| 108 | /// House-number dictionary id. |
| 109 | pub const C_HOUSE: usize = 3; |
| 110 | /// Street dictionary id. |
| 111 | pub const C_STREET: usize = 4; |
| 112 | /// City dictionary id. |
| 113 | pub const C_CITY: usize = 5; |
| 114 | /// State dictionary id. |
| 115 | pub const C_STATE: usize = 6; |
| 116 | /// Country dictionary id. |
| 117 | pub const C_COUNTRY: usize = 7; |
| 118 | /// Postcode dictionary id. |
| 119 | pub const C_POSTCODE: usize = 8; |
| 120 | /// Record kind, one of the `K_*` values. |
| 121 | pub const C_KIND: usize = 9; |
| 122 | |
| 123 | /// Which columns are delta-encoded against the previous value in their block. |
| 124 | pub const DELTA: [bool; COLUMNS] = |
| 125 | [true, true, false, false, false, false, false, false, false, false]; |
| 126 | |
| 127 | /// Column names, for the writer's size report. |
| 128 | pub const COL_NAME: [&str; COLUMNS] = |
| 129 | ["lat", "lon", "name", "house", "street", "city", "state", "country", "postcode", "kind"]; |
| 130 | |
| 131 | /// Dictionaries whose order is a **searchable** contract: the reader binary-searches them, so |
| 132 | /// they must be sorted by UTF-16 code unit. The rest are frequency-ordered for size. |
| 133 | pub const SEARCHABLE: [bool; DICTS] = [true, false, true, true, true, true, false]; |
| 134 | |
| 135 | /// A postal address. |
| 136 | pub const K_ADDRESS: u8 = 1; |
| 137 | /// A named road, sampled along its length. |
| 138 | pub const K_STREET: u8 = 2; |
| 139 | /// A named point of interest. |
| 140 | pub const K_POI: u8 = 3; |
| 141 | /// A populated place: city, town, village, suburb, neighbourhood. |
| 142 | pub const K_PLACE: u8 = 4; |
| 143 | |
| 144 | /// Round an OSM e7 coordinate to the e5 the database stores. |
| 145 | pub fn e7_to_e5(v: i32) -> i32 { |
| 146 | (v as i64 + 50).div_euclid(100) as i32 |
| 147 | } |
| 148 | |
| 149 | /// Grid cell containing an e5 coordinate. Row-major, `COLS` cells per row. |
| 150 | pub fn cell_id(lat: i32, lon: i32) -> i64 { |
| 151 | let row = (lat as i64 - MIN_LAT as i64) / CELL; |
| 152 | let col = (lon as i64 - MIN_LON as i64) / CELL; |
| 153 | row * COLS + col |
| 154 | } |
| 155 | |
| 156 | /// Z-order key of a coordinate **within** its cell. |
| 157 | /// |
| 158 | /// Records are ordered by cell and then by this, so both delta columns stay small: a plain |
| 159 | /// `(lat, lon)` sort keeps the latitude delta tiny but lets longitude swing across the whole |
| 160 | /// cell on every row. |
| 161 | /// |
| 162 | /// An e5 cell is 5 000 units and needs 13 bits per axis; this interleaves 20, so the offsets |
| 163 | /// cannot overflow. Too few bits would not fail — it would silently produce a wrong ordering. |
| 164 | pub fn morton_in_cell(lat: i32, lon: i32) -> u64 { |
| 165 | let lat_off = ((lat as i64 - MIN_LAT as i64) % CELL) as u64; |
| 166 | let lon_off = ((lon as i64 - MIN_LON as i64) % CELL) as u64; |
| 167 | (interleave20(lat_off) << 1) | interleave20(lon_off) |
| 168 | } |
| 169 | |
| 170 | /// Spread the low 20 bits of `v` into the even bit positions of a 40-bit result. |
| 171 | /// |
| 172 | /// Called twice per comparison while sorting hundreds of millions of rows, so it uses the |
| 173 | /// shift-and-mask spread rather than a bit-at-a-time loop. |
| 174 | fn interleave20(v: u64) -> u64 { |
| 175 | let mut x = v & 0xF_FFFF; |
| 176 | x = (x | (x << 16)) & 0x0000_FFFF_0000_FFFF; |
| 177 | x = (x | (x << 8)) & 0x00FF_00FF_00FF_00FF; |
| 178 | x = (x | (x << 4)) & 0x0F0F_0F0F_0F0F_0F0F; |
| 179 | x = (x | (x << 2)) & 0x3333_3333_3333_3333; |
| 180 | (x | (x << 1)) & 0x5555_5555_5555_5555 |
| 181 | } |
| 182 | |
| 183 | /// Whether an e5 coordinate is inside the representable range. |
| 184 | pub fn in_range(lat: i32, lon: i32) -> bool { |
| 185 | (MIN_LAT..=9_000_000).contains(&lat) && (MIN_LON..=18_000_000).contains(&lon) |
| 186 | } |
| 187 | |
| 188 | #[cfg(test)] |
| 189 | mod tests { |
| 190 | use super::*; |
| 191 | |
| 192 | #[test] |
| 193 | fn cells_tile_the_planet_without_gaps_or_overlap() { |
| 194 | assert_eq!(COLS, 7200); |
| 195 | // South-west corner is cell 0. |
| 196 | assert_eq!(cell_id(MIN_LAT, MIN_LON), 0); |
| 197 | // One cell east. |
| 198 | assert_eq!(cell_id(MIN_LAT, MIN_LON + CELL as i32), 1); |
| 199 | // One cell north. |
| 200 | assert_eq!(cell_id(MIN_LAT + CELL as i32, MIN_LON), COLS); |
| 201 | // The north-east corner stays inside i64 comfortably. |
| 202 | let last = cell_id(9_000_000, 18_000_000); |
| 203 | assert!(last > 0 && last < 26_000_000, "cell id {last} out of expected range"); |
| 204 | } |
| 205 | |
| 206 | #[test] |
| 207 | fn a_cell_is_a_twentieth_of_a_degree() { |
| 208 | // Anchored at a cell boundary so the arithmetic is unambiguous: 0.05 degrees is one |
| 209 | // cell, so 0.04 stays inside and 0.06 does not. |
| 210 | let lat = MIN_LAT + 2555 * CELL as i32; |
| 211 | let a = cell_id(lat, -12_241_942); |
| 212 | assert_eq!(cell_id(lat + 4_000, -12_241_942), a); |
| 213 | assert_ne!(cell_id(lat + 6_000, -12_241_942), a); |
| 214 | // And a cell step north moves by exactly one grid row. |
| 215 | assert_eq!(cell_id(lat + CELL as i32, -12_241_942), a + COLS); |
| 216 | } |
| 217 | |
| 218 | #[test] |
| 219 | fn the_fast_interleave_matches_the_bit_loop() { |
| 220 | let slow = |v: u64| (0..20).fold(0u64, |r, i| r | ((v >> i) & 1) << (2 * i)); |
| 221 | let mut v = 0x9E37_79B9u64; |
| 222 | for _ in 0..100_000 { |
| 223 | v ^= v << 13; |
| 224 | v ^= v >> 7; |
| 225 | v ^= v << 17; |
| 226 | assert_eq!(interleave20(v), slow(v), "{v:#x}"); |
| 227 | } |
| 228 | for v in [0, 1, 4_999, 0xF_FFFF, u64::MAX] { |
| 229 | assert_eq!(interleave20(v), slow(v), "{v:#x}"); |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | #[test] |
| 234 | fn morton_offsets_cannot_overflow_the_interleave() { |
| 235 | assert!(CELL <= (1 << 20), "cell wider than the interleave can represent"); |
| 236 | // Extremes of a cell. |
| 237 | let base_lat = MIN_LAT; |
| 238 | let base_lon = MIN_LON; |
| 239 | let hi = morton_in_cell(base_lat + CELL as i32 - 1, base_lon + CELL as i32 - 1); |
| 240 | assert!(hi < (1u64 << 40), "morton escaped 40 bits: {hi:#x}"); |
| 241 | assert_eq!(morton_in_cell(base_lat, base_lon), 0); |
| 242 | } |
| 243 | |
| 244 | #[test] |
| 245 | fn morton_orders_nearby_points_together() { |
| 246 | // Two points a metre apart must be far closer in Z-order than two a cell apart. |
| 247 | let a = morton_in_cell(3_777_493, -12_241_942); |
| 248 | let b = morton_in_cell(3_777_494, -12_241_942); |
| 249 | let near = a.abs_diff(b); |
| 250 | let far = a.abs_diff(morton_in_cell(3_777_493 + 4_000, -12_241_942)); |
| 251 | assert!(near < far, "z-order does not preserve locality: {near} vs {far}"); |
| 252 | } |
| 253 | |
| 254 | #[test] |
| 255 | fn morton_is_injective_within_a_cell() { |
| 256 | let mut seen = std::collections::HashSet::new(); |
| 257 | for dlat in 0..40 { |
| 258 | for dlon in 0..40 { |
| 259 | let m = morton_in_cell(MIN_LAT + dlat * 123, MIN_LON + dlon * 123); |
| 260 | assert!(seen.insert(m), "collision at ({dlat}, {dlon})"); |
| 261 | } |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | #[test] |
| 266 | fn range_check_matches_the_e5_field_width() { |
| 267 | assert!(in_range(0, 0)); |
| 268 | assert!(in_range(9_000_000, 18_000_000)); |
| 269 | assert!(in_range(-9_000_000, -18_000_000)); |
| 270 | assert!(!in_range(9_000_001, 0)); |
| 271 | assert!(!in_range(0, -18_000_001)); |
| 272 | } |
| 273 | |
| 274 | #[test] |
| 275 | fn e7_rounds_to_the_nearest_e5() { |
| 276 | assert_eq!(e7_to_e5(37_7749349), 3_777_493); |
| 277 | assert_eq!(e7_to_e5(37_7749350), 3_777_494); |
| 278 | assert_eq!(e7_to_e5(-122_4194249), -12_241_942); |
| 279 | assert_eq!(e7_to_e5(-122_4194251), -12_241_943); |
| 280 | assert_eq!(e7_to_e5(1_800_000_000), 18_000_000); |
| 281 | } |
| 282 | |
| 283 | #[test] |
| 284 | fn section_count_matches_the_layout() { |
| 285 | assert_eq!(SECTIONS, 21); |
| 286 | assert_eq!(DELTA.len(), COLUMNS); |
| 287 | assert_eq!(COL_NAME.len(), COLUMNS); |
| 288 | assert_eq!(SEARCHABLE.len(), DICTS); |
| 289 | } |
| 290 | } |