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

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

osm.rs442 lines · 14.2 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
9use crate::pbf::{PrimitiveBlock, KIND_NODES, KIND_RELATIONS, KIND_WAYS};
10use crate::proto::{self, Reader, Result, WIRE_BYTES, WIRE_VARINT};
11
12/// Relation member types, matching `Relation.MemberType` in the PBF schema.
13pub const MEMBER_NODE: u8 = 0;
14pub const MEMBER_WAY: u8 = 1;
15pub const MEMBER_RELATION: u8 = 2;
16
17enum 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.
25pub struct Tags<'b, 'a> {
26 block: &'b PrimitiveBlock<'a>,
27 layout: TagLayout<'b>,
28}
29
30impl<'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
76pub 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
83pub 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
90pub struct Member<'a> {
91 pub id: i64,
92 pub role: &'a [u8],
93 pub kind: u8,
94}
95
96pub struct RelationView<'b, 'a> {
97 pub id: i64,
98 pub tags: Tags<'b, 'a>,
99 pub members: &'b [Member<'a>],
100}
101
102pub 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.
113pub fn visit_block<F>(
114 block: &PrimitiveBlock,
115 want: u8,
116 kinds: &mut u8,
117 f: &mut F,
118) -> Result<()>
119where
120 F: FnMut(Element) -> Result<()>,
121{
122 let mut scratch = Scratch::default();
123 for group in &block.groups {
124 let mut g = Reader::new(group);
125 while let Some((field, wire)) = g.next_field()? {
126 if wire != WIRE_BYTES {
127 g.skip(wire)?;
128 continue;
129 }
130 match field {
131 1 => {
132 *kinds |= KIND_NODES;
133 let body = g.bytes()?;
134 if want & KIND_NODES != 0 {
135 visit_node(block, body, &mut scratch, f)?;
136 }
137 }
138 2 => {
139 *kinds |= KIND_NODES;
140 let body = g.bytes()?;
141 if want & KIND_NODES != 0 {
142 visit_dense(block, body, &mut scratch, f)?;
143 }
144 }
145 3 => {
146 *kinds |= KIND_WAYS;
147 let body = g.bytes()?;
148 if want & KIND_WAYS != 0 {
149 visit_way(block, body, &mut scratch, f)?;
150 }
151 }
152 4 => {
153 *kinds |= KIND_RELATIONS;
154 let body = g.bytes()?;
155 if want & KIND_RELATIONS != 0 {
156 visit_relation(block, body, &mut scratch, f)?;
157 }
158 }
159 _ => g.skip(wire)?,
160 }
161 }
162 }
163 Ok(())
164}
165
166#[derive(Default)]
167struct Scratch {
168 keys: Vec<u32>,
169 vals: Vec<u32>,
170 refs: Vec<i64>,
171 ids: Vec<i64>,
172 lats: Vec<i64>,
173 lons: Vec<i64>,
174 kv: Vec<u32>,
175 roles: Vec<u32>,
176 memids: Vec<i64>,
177 types: Vec<u32>,
178}
179
180fn visit_node<F>(block: &PrimitiveBlock, body: &[u8], s: &mut Scratch, f: &mut F) -> Result<()>
181where
182 F: FnMut(Element) -> Result<()>,
183{
184 s.keys.clear();
185 s.vals.clear();
186 let mut id = 0i64;
187 let mut lat = 0i64;
188 let mut lon = 0i64;
189 let mut r = Reader::new(body);
190 while let Some((field, wire)) = r.next_field()? {
191 match (field, wire) {
192 (1, WIRE_VARINT) => id = r.svarint()?,
193 (2, WIRE_BYTES) => proto::packed_u32(r.bytes()?, &mut s.keys)?,
194 (3, WIRE_BYTES) => proto::packed_u32(r.bytes()?, &mut s.vals)?,
195 (8, WIRE_VARINT) => lat = r.svarint()?,
196 (9, WIRE_VARINT) => lon = r.svarint()?,
197 _ => r.skip(wire)?,
198 }
199 }
200 let n = s.keys.len().min(s.vals.len());
201 f(Element::Node(NodeView {
202 id,
203 lat_e7: block.lat_e7(lat),
204 lon_e7: block.lon_e7(lon),
205 tags: Tags {
206 block,
207 layout: TagLayout::Split {
208 keys: &s.keys[..n],
209 vals: &s.vals[..n],
210 },
211 },
212 }))
213}
214
215fn visit_dense<F>(block: &PrimitiveBlock, body: &[u8], s: &mut Scratch, f: &mut F) -> Result<()>
216where
217 F: FnMut(Element) -> Result<()>,
218{
219 s.ids.clear();
220 s.lats.clear();
221 s.lons.clear();
222 s.kv.clear();
223 let mut r = Reader::new(body);
224 while let Some((field, wire)) = r.next_field()? {
225 match (field, wire) {
226 (1, WIRE_BYTES) => proto::packed_delta(r.bytes()?, &mut s.ids)?,
227 (8, WIRE_BYTES) => proto::packed_delta(r.bytes()?, &mut s.lats)?,
228 (9, WIRE_BYTES) => proto::packed_delta(r.bytes()?, &mut s.lons)?,
229 (10, WIRE_BYTES) => proto::packed_u32(r.bytes()?, &mut s.kv)?,
230 _ => r.skip(wire)?,
231 }
232 }
233 if s.lats.len() < s.ids.len() || s.lons.len() < s.ids.len() {
234 return proto::err("DenseNodes has fewer coordinates than ids");
235 }
236
237 // keys_vals is one flat 0-terminated k,v run per node, in node order. An
238 // absent keys_vals means no node in the block carries tags.
239 let mut cursor = 0usize;
240 for i in 0..s.ids.len() {
241 let start = cursor;
242 while cursor < s.kv.len() && s.kv[cursor] != 0 {
243 cursor += 2;
244 }
245 if cursor > s.kv.len() {
246 return proto::err("DenseNodes keys_vals is truncated");
247 }
248 let end = cursor;
249 if cursor < s.kv.len() {
250 cursor += 1; // step over the 0 terminator
251 }
252 f(Element::Node(NodeView {
253 id: s.ids[i],
254 lat_e7: block.lat_e7(s.lats[i]),
255 lon_e7: block.lon_e7(s.lons[i]),
256 tags: Tags {
257 block,
258 layout: TagLayout::Interleaved(&s.kv[start..end]),
259 },
260 }))?;
261 }
262 Ok(())
263}
264
265fn visit_way<F>(block: &PrimitiveBlock, body: &[u8], s: &mut Scratch, f: &mut F) -> Result<()>
266where
267 F: FnMut(Element) -> Result<()>,
268{
269 s.keys.clear();
270 s.vals.clear();
271 s.refs.clear();
272 let mut id = 0i64;
273 let mut r = Reader::new(body);
274 while let Some((field, wire)) = r.next_field()? {
275 match (field, wire) {
276 (1, WIRE_VARINT) => id = r.ivarint()?,
277 (2, WIRE_BYTES) => proto::packed_u32(r.bytes()?, &mut s.keys)?,
278 (3, WIRE_BYTES) => proto::packed_u32(r.bytes()?, &mut s.vals)?,
279 (8, WIRE_BYTES) => proto::packed_delta(r.bytes()?, &mut s.refs)?,
280 _ => r.skip(wire)?,
281 }
282 }
283 let n = s.keys.len().min(s.vals.len());
284 f(Element::Way(WayView {
285 id,
286 tags: Tags {
287 block,
288 layout: TagLayout::Split {
289 keys: &s.keys[..n],
290 vals: &s.vals[..n],
291 },
292 },
293 refs: &s.refs,
294 }))
295}
296
297fn visit_relation<F>(block: &PrimitiveBlock, body: &[u8], s: &mut Scratch, f: &mut F) -> Result<()>
298where
299 F: FnMut(Element) -> Result<()>,
300{
301 s.keys.clear();
302 s.vals.clear();
303 s.roles.clear();
304 s.memids.clear();
305 s.types.clear();
306 let mut id = 0i64;
307 let mut r = Reader::new(body);
308 while let Some((field, wire)) = r.next_field()? {
309 match (field, wire) {
310 (1, WIRE_VARINT) => id = r.ivarint()?,
311 (2, WIRE_BYTES) => proto::packed_u32(r.bytes()?, &mut s.keys)?,
312 (3, WIRE_BYTES) => proto::packed_u32(r.bytes()?, &mut s.vals)?,
313 (8, WIRE_BYTES) => proto::packed_u32(r.bytes()?, &mut s.roles)?,
314 (9, WIRE_BYTES) => proto::packed_delta(r.bytes()?, &mut s.memids)?,
315 (10, WIRE_BYTES) => proto::packed_u32(r.bytes()?, &mut s.types)?,
316 _ => r.skip(wire)?,
317 }
318 }
319 let count = s.memids.len().min(s.types.len()).min(s.roles.len());
320 let members: Vec<Member> = (0..count)
321 .map(|i| Member {
322 id: s.memids[i],
323 role: block.string(s.roles[i]),
324 kind: s.types[i] as u8,
325 })
326 .collect();
327 let n = s.keys.len().min(s.vals.len());
328 f(Element::Relation(RelationView {
329 id,
330 tags: Tags {
331 block,
332 layout: TagLayout::Split {
333 keys: &s.keys[..n],
334 vals: &s.vals[..n],
335 },
336 },
337 members: &members,
338 }))
339}
340
341#[cfg(test)]
342mod tests {
343 use super::*;
344 use crate::pbf;
345 use crate::testpbf;
346
347 /// `(id, lat_e7, lon_e7, tags)`, `(id, refs)`, `(id, [(member id, role, kind)])`.
348 type Decoded = (
349 Vec<(i64, i32, i32, Vec<(String, String)>)>,
350 Vec<(i64, Vec<i64>)>,
351 Vec<(i64, Vec<(i64, String, u8)>)>,
352 );
353
354 fn walk(want: u8) -> Decoded {
355 let mut blob = Vec::new();
356 pbf::inflate_blob(&testpbf::sample_data_blob(), &mut blob).unwrap();
357 let block = pbf::PrimitiveBlock::decode(&blob).unwrap();
358 let mut nodes = Vec::new();
359 let mut ways = Vec::new();
360 let mut rels = Vec::new();
361 let mut kinds = 0;
362 visit_block(&block, want, &mut kinds, &mut |el| {
363 match el {
364 Element::Node(n) => nodes.push((
365 n.id,
366 n.lat_e7,
367 n.lon_e7,
368 n.tags
369 .iter()
370 .map(|(k, v)| {
371 (
372 String::from_utf8_lossy(k).into_owned(),
373 String::from_utf8_lossy(v).into_owned(),
374 )
375 })
376 .collect(),
377 )),
378 Element::Way(w) => ways.push((w.id, w.refs.to_vec())),
379 Element::Relation(r) => rels.push((
380 r.id,
381 r.members
382 .iter()
383 .map(|m| (m.id, String::from_utf8_lossy(m.role).into_owned(), m.kind))
384 .collect(),
385 )),
386 }
387 Ok(())
388 })
389 .unwrap();
390 assert_eq!(kinds, KIND_NODES | KIND_WAYS | KIND_RELATIONS);
391 (nodes, ways, rels)
392 }
393
394 #[test]
395 fn decodes_dense_nodes_with_per_node_tags() {
396 let (nodes, _, _) = walk(KIND_NODES);
397 assert_eq!(nodes.len(), testpbf::NODE_COUNT);
398 // Ids are delta-encoded; check they accumulated.
399 assert_eq!(nodes[0].0, 1);
400 assert_eq!(nodes[1].0, 2);
401 // Coordinates come back as the exact 1e-7 integers.
402 assert_eq!((nodes[0].1, nodes[0].2), (370_000_000, -1_220_000_000));
403 // The bus stop and the cafe are the only tagged nodes in the sample.
404 let stop = nodes.iter().find(|n| n.0 == testpbf::STOP_NODE_ID).unwrap();
405 assert!(stop
406 .3
407 .iter()
408 .any(|(k, v)| k == "highway" && v == "bus_stop"));
409 assert!(stop.3.iter().any(|(k, v)| k == "name" && v == "Test Stop"));
410 // Untagged neighbours really have no tags (the 0 terminator is honoured).
411 assert!(nodes.iter().find(|n| n.0 == 1).unwrap().3.is_empty());
412 }
413
414 #[test]
415 fn decodes_way_refs_as_absolute_ids() {
416 let (_, ways, _) = walk(KIND_WAYS);
417 assert_eq!(ways.len(), 3);
418 assert_eq!(ways[0], (testpbf::MAIN_WAY_ID, vec![1, 2, 3, 4]));
419 assert_eq!(ways[1], (testpbf::SERVICE_WAY_ID, vec![4, 2]));
420 assert_eq!(ways[2], (testpbf::AREA_WAY_ID, vec![1, 2, 3, 4, 1]));
421 }
422
423 #[test]
424 fn decodes_relation_members_with_roles() {
425 let (_, _, rels) = walk(KIND_RELATIONS);
426 assert_eq!(rels.len(), 1);
427 let (id, members) = &rels[0];
428 assert_eq!(*id, testpbf::RELATION_ID);
429 assert_eq!(members.len(), 1);
430 assert_eq!(members[0].0, testpbf::AREA_WAY_ID);
431 assert_eq!(members[0].1, "outer");
432 assert_eq!(members[0].2, MEMBER_WAY);
433 }
434
435 #[test]
436 fn want_mask_skips_unwanted_kinds_but_still_reports_them() {
437 let (nodes, ways, rels) = walk(KIND_WAYS);
438 assert!(nodes.is_empty());
439 assert!(rels.is_empty());
440 assert_eq!(ways.len(), 3);
441 }
442}