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

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

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