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

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

names.rs164 lines · 5.7 KiBRaw
1//! Deduplicating NUL-terminated string pool.
2//!
3//! Both `road_names.bin` and `poi_names.bin` use the same convention: every
4//! unique string is stored exactly once, NUL-terminated and concatenated, and a
5//! "name offset" is the byte offset of the string's first byte. The device reads
6//! a name by scanning forward from that offset to the NUL.
7//!
8//! Interning is single-threaded on purpose. The parallel passes accumulate names
9//! per work chunk and the chunks are merged in index order, so a name's offset
10//! depends only on the input file — not on thread scheduling, which is what made
11//! the old C++ generator's `road_names.bin` differ between two runs of itself.
12
13use std::collections::HashMap;
14use std::io::{self, Write};
15
16/// Sentinel meaning "no name" in a `name_offset` field.
17pub const NO_NAME: u32 = 0xFFFF_FFFF;
18
19pub struct NamePool<W: Write> {
20 offsets: HashMap<Vec<u8>, u32>,
21 next: u32,
22 out: W,
23}
24
25impl<W: Write> NamePool<W> {
26 pub fn new(out: W) -> Self {
27 NamePool {
28 offsets: HashMap::new(),
29 next: 0,
30 out,
31 }
32 }
33
34 /// Offset of `name`, appending it to the pool the first time it is seen.
35 ///
36 /// Fails rather than wrapping once the pool would pass [`NO_NAME`]: a name
37 /// offset is a `u32` in the on-disk edge record, so the format caps the pool
38 /// at 4 GiB, and a wrapped `next` would hand every later name an offset that
39 /// points into the middle of an earlier string. The failure mode is
40 /// permanently wrong street names on device, which no later stage can detect.
41 pub fn intern(&mut self, name: &[u8]) -> io::Result<u32> {
42 if let Some(off) = self.offsets.get(name) {
43 return Ok(*off);
44 }
45 let off = self.next;
46 let grown = u32::try_from(name.len() as u64 + 1)
47 .ok()
48 .and_then(|n| off.checked_add(n))
49 .filter(|n| *n < NO_NAME)
50 .ok_or_else(|| {
51 io::Error::new(
52 io::ErrorKind::InvalidData,
53 format!("name pool would pass {NO_NAME} bytes at offset {off}"),
54 )
55 })?;
56 self.out.write_all(name)?;
57 self.out.write_all(&[0])?;
58 self.next = grown;
59 self.offsets.insert(name.to_vec(), off);
60 Ok(off)
61 }
62
63 pub fn unique_count(&self) -> usize {
64 self.offsets.len()
65 }
66
67 pub fn byte_len(&self) -> u32 {
68 self.next
69 }
70
71 pub fn finish(mut self) -> io::Result<W> {
72 self.out.flush()?;
73 Ok(self.out)
74 }
75
76 /// Start the pool near its ceiling, so the overflow guard can be tested
77 /// without writing 4 GiB of names.
78 #[cfg(test)]
79 fn seek_to(&mut self, next: u32) {
80 self.next = next;
81 }
82}
83
84/// Per-chunk name table used by the parallel passes: it maps a name to a
85/// chunk-local id, and the chunk's names are later interned into the real pool
86/// in local-id order.
87#[derive(Default)]
88pub struct LocalNames {
89 ids: HashMap<Vec<u8>, u32>,
90 pub names: Vec<Vec<u8>>,
91}
92
93impl LocalNames {
94 pub fn id(&mut self, name: &[u8]) -> u32 {
95 if let Some(id) = self.ids.get(name) {
96 return *id;
97 }
98 let id = self.names.len() as u32;
99 self.names.push(name.to_vec());
100 self.ids.insert(name.to_vec(), id);
101 id
102 }
103
104 /// Intern every local name into `pool`, returning local id -> pool offset.
105 pub fn flush<W: Write>(&self, pool: &mut NamePool<W>) -> io::Result<Vec<u32>> {
106 self.names.iter().map(|n| pool.intern(n)).collect()
107 }
108}
109
110#[cfg(test)]
111mod tests {
112 use super::*;
113
114 #[test]
115 fn dedupes_and_nul_terminates() {
116 let mut pool = NamePool::new(Vec::new());
117 assert_eq!(pool.intern(b"Main St").unwrap(), 0);
118 assert_eq!(pool.intern(b"Oak Ave").unwrap(), 8);
119 assert_eq!(pool.intern(b"Main St").unwrap(), 0, "second hit reuses");
120 assert_eq!(pool.intern(b"").unwrap(), 16, "empty name still costs its NUL");
121 assert_eq!(pool.unique_count(), 3);
122 assert_eq!(pool.byte_len(), 17);
123 assert_eq!(pool.finish().unwrap(), b"Main St\0Oak Ave\0\0".to_vec());
124 }
125
126 #[test]
127 fn the_pool_refuses_to_wrap_past_the_u32_offset_ceiling() {
128 let mut pool = NamePool::new(io::sink());
129 pool.seek_to(NO_NAME - 8);
130 // Six bytes plus a NUL lands one short of the sentinel, which is still a
131 // usable offset.
132 assert_eq!(pool.intern(b"Ada St").unwrap(), NO_NAME - 8);
133 assert_eq!(pool.byte_len(), NO_NAME - 1);
134 // The next name would wrap into offsets earlier names already own.
135 let err = pool.intern(b"Bee St").unwrap_err();
136 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
137 // A name that would land exactly on the sentinel is refused too.
138 let mut pool = NamePool::new(io::sink());
139 pool.seek_to(NO_NAME - 1);
140 assert!(pool.intern(b"").is_err());
141 // ...and the pool is unchanged, so the offsets already handed out stay
142 // valid for whatever the caller does with the error.
143 assert_eq!(pool.byte_len(), NO_NAME - 1);
144 assert_eq!(pool.unique_count(), 0);
145 }
146
147 #[test]
148 fn local_names_map_to_pool_offsets_in_local_order() {
149 let mut a = LocalNames::default();
150 assert_eq!(a.id(b"B"), 0);
151 assert_eq!(a.id(b"A"), 1);
152 assert_eq!(a.id(b"B"), 0);
153
154 let mut b = LocalNames::default();
155 assert_eq!(b.id(b"A"), 0);
156 assert_eq!(b.id(b"C"), 1);
157
158 let mut pool = NamePool::new(Vec::new());
159 // Chunk order decides offsets: B, A, then C (A already interned).
160 assert_eq!(a.flush(&mut pool).unwrap(), vec![0, 2]);
161 assert_eq!(b.flush(&mut pool).unwrap(), vec![2, 4]);
162 assert_eq!(pool.finish().unwrap(), b"B\0A\0C\0".to_vec());
163 }
164}