Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / osm_ingest / src / osm.rs
osm.rs435 lines · 14.7 KiBRaw
| 1 | //! Typed iteration over a `PrimitiveBlock`: dense nodes, plain nodes, ways and |
| 2 | //! relations, each with string-table-resolved tag lookup. |
| 3 | //! |
| 4 | //! This is the layer that replaces libosmium's `buf.select<osmium::Node>()` / |
| 5 | //! `way.tags().get_value_by_key(...)` API surface. Views borrow from the |
| 6 | //! inflated block and from short-lived scratch buffers, so a whole blob is |
| 7 | //! walked with a handful of allocations. |
| 8 | |
| 9 | use crate::pbf::{PrimitiveBlock, KIND_NODES, KIND_RELATIONS, KIND_WAYS}; |
| 10 | use crate::proto::{self, Reader, Result, WIRE_BYTES, WIRE_VARINT}; |
| 11 | |
| 12 | /// Relation member types, matching `Relation.MemberType` in the PBF schema. |
| 13 | pub const MEMBER_NODE: u8 = 0; |
| 14 | pub const MEMBER_WAY: u8 = 1; |
| 15 | pub const MEMBER_RELATION: u8 = 2; |
| 16 | |
| 17 | enum TagLayout<'b> { |
| 18 | /// `Node`/`Way`/`Relation`: parallel key and value string-table indices. |
| 19 | Split { keys: &'b [u32], vals: &'b [u32] }, |
| 20 | /// `DenseNodes.keys_vals`: `k, v, k, v, ...` for one node. |
| 21 | Interleaved(&'b [u32]), |
| 22 | } |
| 23 | |
| 24 | /// One element's tag set, resolved lazily against the block string table. |
| 25 | pub struct Tags<'b, 'a> { |
| 26 | block: &'b PrimitiveBlock<'a>, |
| 27 | layout: TagLayout<'b>, |
| 28 | } |
| 29 | |
| 30 | impl<'b, 'a> Tags<'b, 'a> { |
| 31 | pub fn get(&self, key: &str) -> Option<&'a [u8]> { |
| 32 | let want = key.as_bytes(); |
| 33 | match self.layout { |
| 34 | TagLayout::Split { keys, vals } => keys |
| 35 | .iter() |
| 36 | .zip(vals) |
| 37 | .find(|(k, _)| self.block.string(**k) == want) |
| 38 | .map(|(_, v)| self.block.string(*v)), |
| 39 | TagLayout::Interleaved(kv) => kv |
| 40 | .chunks_exact(2) |
| 41 | .find(|p| self.block.string(p[0]) == want) |
| 42 | .map(|p| self.block.string(p[1])), |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | /// Tag value as UTF-8. OSM guarantees UTF-8; a non-conforming value is |
| 47 | /// treated as absent rather than silently mangled. |
| 48 | pub fn get_str(&self, key: &str) -> Option<&'a str> { |
| 49 | std::str::from_utf8(self.get(key)?).ok() |
| 50 | } |
| 51 | |
| 52 | pub fn iter(&self) -> impl Iterator<Item = (&'a [u8], &'a [u8])> + '_ { |
| 53 | let split = match self.layout { |
| 54 | TagLayout::Split { keys, vals } => Some(keys.iter().copied().zip(vals.iter().copied())), |
| 55 | TagLayout::Interleaved(_) => None, |
| 56 | }; |
| 57 | let inter = match self.layout { |
| 58 | TagLayout::Interleaved(kv) => Some(kv.chunks_exact(2).map(|p| (p[0], p[1]))), |
| 59 | TagLayout::Split { .. } => None, |
| 60 | }; |
| 61 | split |
| 62 | .into_iter() |
| 63 | .flatten() |
| 64 | .chain(inter.into_iter().flatten()) |
| 65 | .map(|(k, v)| (self.block.string(k), self.block.string(v))) |
| 66 | } |
| 67 | |
| 68 | pub fn is_empty(&self) -> bool { |
| 69 | match self.layout { |
| 70 | TagLayout::Split { keys, .. } => keys.is_empty(), |
| 71 | TagLayout::Interleaved(kv) => kv.is_empty(), |
| 72 | } |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | pub struct NodeView<'b, 'a> { |
| 77 | pub id: i64, |
| 78 | pub lat_e7: i32, |
| 79 | pub lon_e7: i32, |
| 80 | pub tags: Tags<'b, 'a>, |
| 81 | } |
| 82 | |
| 83 | pub struct WayView<'b, 'a> { |
| 84 | pub id: i64, |
| 85 | pub tags: Tags<'b, 'a>, |
| 86 | /// Absolute node ids (the on-disk deltas are already accumulated). |
| 87 | pub refs: &'b [i64], |
| 88 | } |
| 89 | |
| 90 | pub struct Member<'a> { |
| 91 | pub id: i64, |
| 92 | pub role: &'a [u8], |
| 93 | pub kind: u8, |
| 94 | } |
| 95 | |
| 96 | pub struct RelationView<'b, 'a> { |
| 97 | pub id: i64, |
| 98 | pub tags: Tags<'b, 'a>, |
| 99 | pub members: &'b [Member<'a>], |
| 100 | } |
| 101 | |
| 102 | pub enum Element<'b, 'a> { |
| 103 | Node(NodeView<'b, 'a>), |
| 104 | Way(WayView<'b, 'a>), |
| 105 | Relation(RelationView<'b, 'a>), |
| 106 | } |
| 107 | |
| 108 | /// Walk every element of `block` whose kind is in `want`, calling `f`. |
| 109 | /// |
| 110 | /// `kinds` accumulates the kinds the block *contains* (regardless of `want`), so |
| 111 | /// a first full pass can record a per-blob mask and later passes can skip blobs |
| 112 | /// outright. |
| 113 | pub fn visit_block<F>(block: &PrimitiveBlock, want: u8, kinds: &mut u8, f: &mut F) -> Result<()> |
| 114 | where |
| 115 | F: FnMut(Element) -> Result<()>, |
| 116 | { |
| 117 | // Reuse this thread's decode buffers across blocks. A fresh `Scratch` per |
| 118 | // block regrew ~10 vectors from empty to tens of KB on every blob, and with |
| 119 | // 192 decode threads that malloc/realloc churn serialised on allocator |
| 120 | // locks (most of a California build's ~400 s of system time). Contents are |
| 121 | // cleared before every use, so reuse changes nothing but the allocations. |
| 122 | // Taken, not borrowed, so a nested visit (none exists) would just get a |
| 123 | // fresh one. |
| 124 | let mut scratch = SCRATCH.with(|c| c.take()); |
| 125 | let r = visit_groups(block, want, kinds, f, &mut scratch); |
| 126 | SCRATCH.with(|c| c.set(scratch)); |
| 127 | r |
| 128 | } |
| 129 | |
| 130 | thread_local! { |
| 131 | static SCRATCH: std::cell::Cell<Scratch> = std::cell::Cell::new(Scratch::default()); |
| 132 | } |
| 133 | |
| 134 | fn visit_groups<F>( |
| 135 | block: &PrimitiveBlock, |
| 136 | want: u8, |
| 137 | kinds: &mut u8, |
| 138 | f: &mut F, |
| 139 | scratch: &mut Scratch, |
| 140 | ) -> Result<()> |
| 141 | where |
| 142 | F: FnMut(Element) -> Result<()>, |
| 143 | { |
| 144 | for group in &block.groups { |
| 145 | let mut g = Reader::new(group); |
| 146 | while let Some((field, wire)) = g.next_field()? { |
| 147 | if wire != WIRE_BYTES { |
| 148 | g.skip(wire)?; |
| 149 | continue; |
| 150 | } |
| 151 | match field { |
| 152 | 1 => { |
| 153 | *kinds |= KIND_NODES; |
| 154 | let body = g.bytes()?; |
| 155 | if want & KIND_NODES != 0 { |
| 156 | visit_node(block, body, scratch, f)?; |
| 157 | } |
| 158 | } |
| 159 | 2 => { |
| 160 | *kinds |= KIND_NODES; |
| 161 | let body = g.bytes()?; |
| 162 | if want & KIND_NODES != 0 { |
| 163 | visit_dense(block, body, scratch, f)?; |
| 164 | } |
| 165 | } |
| 166 | 3 => { |
| 167 | *kinds |= KIND_WAYS; |
| 168 | let body = g.bytes()?; |
| 169 | if want & KIND_WAYS != 0 { |
| 170 | visit_way(block, body, scratch, f)?; |
| 171 | } |
| 172 | } |
| 173 | 4 => { |
| 174 | *kinds |= KIND_RELATIONS; |
| 175 | let body = g.bytes()?; |
| 176 | if want & KIND_RELATIONS != 0 { |
| 177 | visit_relation(block, body, scratch, f)?; |
| 178 | } |
| 179 | } |
| 180 | _ => g.skip(wire)?, |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | Ok(()) |
| 185 | } |
| 186 | |
| 187 | #[derive(Default)] |
| 188 | struct Scratch { |
| 189 | keys: Vec<u32>, |
| 190 | vals: Vec<u32>, |
| 191 | refs: Vec<i64>, |
| 192 | ids: Vec<i64>, |
| 193 | lats: Vec<i64>, |
| 194 | lons: Vec<i64>, |
| 195 | kv: Vec<u32>, |
| 196 | roles: Vec<u32>, |
| 197 | memids: Vec<i64>, |
| 198 | types: Vec<u32>, |
| 199 | } |
| 200 | |
| 201 | fn visit_node<F>(block: &PrimitiveBlock, body: &[u8], s: &mut Scratch, f: &mut F) -> Result<()> |
| 202 | where |
| 203 | F: FnMut(Element) -> Result<()>, |
| 204 | { |
| 205 | s.keys.clear(); |
| 206 | s.vals.clear(); |
| 207 | let mut id = 0i64; |
| 208 | let mut lat = 0i64; |
| 209 | let mut lon = 0i64; |
| 210 | let mut r = Reader::new(body); |
| 211 | while let Some((field, wire)) = r.next_field()? { |
| 212 | match (field, wire) { |
| 213 | (1, WIRE_VARINT) => id = r.svarint()?, |
| 214 | (2, WIRE_BYTES) => proto::packed_u32(r.bytes()?, &mut s.keys)?, |
| 215 | (3, WIRE_BYTES) => proto::packed_u32(r.bytes()?, &mut s.vals)?, |
| 216 | (8, WIRE_VARINT) => lat = r.svarint()?, |
| 217 | (9, WIRE_VARINT) => lon = r.svarint()?, |
| 218 | _ => r.skip(wire)?, |
| 219 | } |
| 220 | } |
| 221 | let n = s.keys.len().min(s.vals.len()); |
| 222 | f(Element::Node(NodeView { |
| 223 | id, |
| 224 | lat_e7: block.lat_e7(lat), |
| 225 | lon_e7: block.lon_e7(lon), |
| 226 | tags: Tags { block, layout: TagLayout::Split { keys: &s.keys[..n], vals: &s.vals[..n] } }, |
| 227 | })) |
| 228 | } |
| 229 | |
| 230 | fn visit_dense<F>(block: &PrimitiveBlock, body: &[u8], s: &mut Scratch, f: &mut F) -> Result<()> |
| 231 | where |
| 232 | F: FnMut(Element) -> Result<()>, |
| 233 | { |
| 234 | s.ids.clear(); |
| 235 | s.lats.clear(); |
| 236 | s.lons.clear(); |
| 237 | s.kv.clear(); |
| 238 | let mut r = Reader::new(body); |
| 239 | while let Some((field, wire)) = r.next_field()? { |
| 240 | match (field, wire) { |
| 241 | (1, WIRE_BYTES) => proto::packed_delta(r.bytes()?, &mut s.ids)?, |
| 242 | (8, WIRE_BYTES) => proto::packed_delta(r.bytes()?, &mut s.lats)?, |
| 243 | (9, WIRE_BYTES) => proto::packed_delta(r.bytes()?, &mut s.lons)?, |
| 244 | (10, WIRE_BYTES) => proto::packed_u32(r.bytes()?, &mut s.kv)?, |
| 245 | _ => r.skip(wire)?, |
| 246 | } |
| 247 | } |
| 248 | if s.lats.len() < s.ids.len() || s.lons.len() < s.ids.len() { |
| 249 | return proto::err("DenseNodes has fewer coordinates than ids"); |
| 250 | } |
| 251 | |
| 252 | // keys_vals is one flat 0-terminated k,v run per node, in node order. An |
| 253 | // absent keys_vals means no node in the block carries tags. |
| 254 | let mut cursor = 0usize; |
| 255 | for i in 0..s.ids.len() { |
| 256 | let start = cursor; |
| 257 | while cursor < s.kv.len() && s.kv[cursor] != 0 { |
| 258 | cursor += 2; |
| 259 | } |
| 260 | if cursor > s.kv.len() { |
| 261 | return proto::err("DenseNodes keys_vals is truncated"); |
| 262 | } |
| 263 | let end = cursor; |
| 264 | if cursor < s.kv.len() { |
| 265 | cursor += 1; // step over the 0 terminator |
| 266 | } |
| 267 | f(Element::Node(NodeView { |
| 268 | id: s.ids[i], |
| 269 | lat_e7: block.lat_e7(s.lats[i]), |
| 270 | lon_e7: block.lon_e7(s.lons[i]), |
| 271 | tags: Tags { block, layout: TagLayout::Interleaved(&s.kv[start..end]) }, |
| 272 | }))?; |
| 273 | } |
| 274 | Ok(()) |
| 275 | } |
| 276 | |
| 277 | fn visit_way<F>(block: &PrimitiveBlock, body: &[u8], s: &mut Scratch, f: &mut F) -> Result<()> |
| 278 | where |
| 279 | F: FnMut(Element) -> Result<()>, |
| 280 | { |
| 281 | s.keys.clear(); |
| 282 | s.vals.clear(); |
| 283 | s.refs.clear(); |
| 284 | let mut id = 0i64; |
| 285 | let mut r = Reader::new(body); |
| 286 | while let Some((field, wire)) = r.next_field()? { |
| 287 | match (field, wire) { |
| 288 | (1, WIRE_VARINT) => id = r.ivarint()?, |
| 289 | (2, WIRE_BYTES) => proto::packed_u32(r.bytes()?, &mut s.keys)?, |
| 290 | (3, WIRE_BYTES) => proto::packed_u32(r.bytes()?, &mut s.vals)?, |
| 291 | (8, WIRE_BYTES) => proto::packed_delta(r.bytes()?, &mut s.refs)?, |
| 292 | _ => r.skip(wire)?, |
| 293 | } |
| 294 | } |
| 295 | let n = s.keys.len().min(s.vals.len()); |
| 296 | f(Element::Way(WayView { |
| 297 | id, |
| 298 | tags: Tags { block, layout: TagLayout::Split { keys: &s.keys[..n], vals: &s.vals[..n] } }, |
| 299 | refs: &s.refs, |
| 300 | })) |
| 301 | } |
| 302 | |
| 303 | fn visit_relation<F>(block: &PrimitiveBlock, body: &[u8], s: &mut Scratch, f: &mut F) -> Result<()> |
| 304 | where |
| 305 | F: FnMut(Element) -> Result<()>, |
| 306 | { |
| 307 | s.keys.clear(); |
| 308 | s.vals.clear(); |
| 309 | s.roles.clear(); |
| 310 | s.memids.clear(); |
| 311 | s.types.clear(); |
| 312 | let mut id = 0i64; |
| 313 | let mut r = Reader::new(body); |
| 314 | while let Some((field, wire)) = r.next_field()? { |
| 315 | match (field, wire) { |
| 316 | (1, WIRE_VARINT) => id = r.ivarint()?, |
| 317 | (2, WIRE_BYTES) => proto::packed_u32(r.bytes()?, &mut s.keys)?, |
| 318 | (3, WIRE_BYTES) => proto::packed_u32(r.bytes()?, &mut s.vals)?, |
| 319 | (8, WIRE_BYTES) => proto::packed_u32(r.bytes()?, &mut s.roles)?, |
| 320 | (9, WIRE_BYTES) => proto::packed_delta(r.bytes()?, &mut s.memids)?, |
| 321 | (10, WIRE_BYTES) => proto::packed_u32(r.bytes()?, &mut s.types)?, |
| 322 | _ => r.skip(wire)?, |
| 323 | } |
| 324 | } |
| 325 | let count = s.memids.len().min(s.types.len()).min(s.roles.len()); |
| 326 | let members: Vec<Member> = (0..count) |
| 327 | .map(|i| Member { id: s.memids[i], role: block.string(s.roles[i]), kind: s.types[i] as u8 }) |
| 328 | .collect(); |
| 329 | let n = s.keys.len().min(s.vals.len()); |
| 330 | f(Element::Relation(RelationView { |
| 331 | id, |
| 332 | tags: Tags { block, layout: TagLayout::Split { keys: &s.keys[..n], vals: &s.vals[..n] } }, |
| 333 | members: &members, |
| 334 | })) |
| 335 | } |
| 336 | |
| 337 | #[cfg(test)] |
| 338 | mod tests { |
| 339 | use super::*; |
| 340 | use crate::pbf; |
| 341 | use crate::testpbf; |
| 342 | |
| 343 | /// `(id, lat_e7, lon_e7, tags)`, `(id, refs)`, `(id, [(member id, role, kind)])`. |
| 344 | type Decoded = ( |
| 345 | Vec<(i64, i32, i32, Vec<(String, String)>)>, |
| 346 | Vec<(i64, Vec<i64>)>, |
| 347 | Vec<(i64, Vec<(i64, String, u8)>)>, |
| 348 | ); |
| 349 | |
| 350 | fn walk(want: u8) -> Decoded { |
| 351 | let mut blob = Vec::new(); |
| 352 | pbf::inflate_blob(&testpbf::sample_data_blob(), &mut blob).unwrap(); |
| 353 | let block = pbf::PrimitiveBlock::decode(&blob).unwrap(); |
| 354 | let mut nodes = Vec::new(); |
| 355 | let mut ways = Vec::new(); |
| 356 | let mut rels = Vec::new(); |
| 357 | let mut kinds = 0; |
| 358 | visit_block(&block, want, &mut kinds, &mut |el| { |
| 359 | match el { |
| 360 | Element::Node(n) => nodes.push(( |
| 361 | n.id, |
| 362 | n.lat_e7, |
| 363 | n.lon_e7, |
| 364 | n.tags |
| 365 | .iter() |
| 366 | .map(|(k, v)| { |
| 367 | ( |
| 368 | String::from_utf8_lossy(k).into_owned(), |
| 369 | String::from_utf8_lossy(v).into_owned(), |
| 370 | ) |
| 371 | }) |
| 372 | .collect(), |
| 373 | )), |
| 374 | Element::Way(w) => ways.push((w.id, w.refs.to_vec())), |
| 375 | Element::Relation(r) => rels.push(( |
| 376 | r.id, |
| 377 | r.members |
| 378 | .iter() |
| 379 | .map(|m| (m.id, String::from_utf8_lossy(m.role).into_owned(), m.kind)) |
| 380 | .collect(), |
| 381 | )), |
| 382 | } |
| 383 | Ok(()) |
| 384 | }) |
| 385 | .unwrap(); |
| 386 | assert_eq!(kinds, KIND_NODES | KIND_WAYS | KIND_RELATIONS); |
| 387 | (nodes, ways, rels) |
| 388 | } |
| 389 | |
| 390 | #[test] |
| 391 | fn decodes_dense_nodes_with_per_node_tags() { |
| 392 | let (nodes, _, _) = walk(KIND_NODES); |
| 393 | assert_eq!(nodes.len(), testpbf::NODE_COUNT); |
| 394 | // Ids are delta-encoded; check they accumulated. |
| 395 | assert_eq!(nodes[0].0, 1); |
| 396 | assert_eq!(nodes[1].0, 2); |
| 397 | // Coordinates come back as the exact 1e-7 integers. |
| 398 | assert_eq!((nodes[0].1, nodes[0].2), (370_000_000, -1_220_000_000)); |
| 399 | // The bus stop and the cafe are the only tagged nodes in the sample. |
| 400 | let stop = nodes.iter().find(|n| n.0 == testpbf::STOP_NODE_ID).unwrap(); |
| 401 | assert!(stop.3.iter().any(|(k, v)| k == "highway" && v == "bus_stop")); |
| 402 | assert!(stop.3.iter().any(|(k, v)| k == "name" && v == "Test Stop")); |
| 403 | // Untagged neighbours really have no tags (the 0 terminator is honoured). |
| 404 | assert!(nodes.iter().find(|n| n.0 == 1).unwrap().3.is_empty()); |
| 405 | } |
| 406 | |
| 407 | #[test] |
| 408 | fn decodes_way_refs_as_absolute_ids() { |
| 409 | let (_, ways, _) = walk(KIND_WAYS); |
| 410 | assert_eq!(ways.len(), 3); |
| 411 | assert_eq!(ways[0], (testpbf::MAIN_WAY_ID, vec![1, 2, 3, 4])); |
| 412 | assert_eq!(ways[1], (testpbf::SERVICE_WAY_ID, vec![4, 2])); |
| 413 | assert_eq!(ways[2], (testpbf::AREA_WAY_ID, vec![1, 2, 3, 4, 1])); |
| 414 | } |
| 415 | |
| 416 | #[test] |
| 417 | fn decodes_relation_members_with_roles() { |
| 418 | let (_, _, rels) = walk(KIND_RELATIONS); |
| 419 | assert_eq!(rels.len(), 1); |
| 420 | let (id, members) = &rels[0]; |
| 421 | assert_eq!(*id, testpbf::RELATION_ID); |
| 422 | assert_eq!(members.len(), 1); |
| 423 | assert_eq!(members[0].0, testpbf::AREA_WAY_ID); |
| 424 | assert_eq!(members[0].1, "outer"); |
| 425 | assert_eq!(members[0].2, MEMBER_WAY); |
| 426 | } |
| 427 | |
| 428 | #[test] |
| 429 | fn want_mask_skips_unwanted_kinds_but_still_reports_them() { |
| 430 | let (nodes, ways, rels) = walk(KIND_WAYS); |
| 431 | assert!(nodes.is_empty()); |
| 432 | assert!(rels.is_empty()); |
| 433 | assert_eq!(ways.len(), 3); |
| 434 | } |
| 435 | } |