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

Modern-Apps.git / scripts / networklocation / geodb_build / src / codec.rs

codec.rs468 lines · 17.0 KiBRaw
1//! String dictionaries and the column codec.
2//!
3//! ## The ordering contract
4//!
5//! A searchable dictionary must be sorted by **UTF-16 code unit**, because the reader binary
6//! -searches it with a UTF-16 comparator (`cmp_utf16` in `geocoder.rs`). UTF-8 byte order and
7//! UTF-16 order disagree for anything above the BMP: `U+10000` sorts *after* `U+FFFF` in UTF-8
8//! but *before* it in UTF-16, because surrogates start at `0xD800`. Sorting the wrong way does
9//! not corrupt anything visibly — forward lookups just start missing entries near the
10//! disagreement.
11//!
12//! Non-searchable dictionaries (house numbers, postcodes) are never string-searched, only
13//! displayed, so they are ordered by descending frequency instead. That puts the commonest
14//! values at the smallest ids and keeps those columns near a byte per record.
15
16use std::collections::HashMap;
17use std::io::{self, Write};
18
19use rayon::prelude::*;
20
21use crate::format::{BLOCK, DICT_BLOCK, ZSTD_LEVEL};
22use crate::progress::Progress;
23
24// --------------------------------------------------------------------------- interner
25/// Assigns a dense id to each distinct string, in first-seen order.
26#[derive(Default)]
27pub struct Interner {
28 ids: HashMap<Box<str>, u32>,
29 strings: Vec<Box<str>>,
30 counts: Vec<u32>,
31}
32
33impl Interner {
34 /// Empty interner.
35 pub fn new() -> Interner {
36 Interner::default()
37 }
38
39 /// Id for `s`, interning it if new. Counts occurrences for the frequency ordering.
40 pub fn intern(&mut self, s: &str) -> u32 {
41 if let Some(&id) = self.ids.get(s) {
42 if let Some(c) = self.counts.get_mut(id as usize) {
43 *c = c.saturating_add(1);
44 }
45 return id;
46 }
47 let id = self.strings.len() as u32;
48 let boxed: Box<str> = s.into();
49 let _ = self.ids.insert(boxed.clone(), id);
50 self.strings.push(boxed);
51 self.counts.push(1);
52 id
53 }
54
55 /// Number of distinct strings.
56 pub fn len(&self) -> usize {
57 self.strings.len()
58 }
59
60 /// Whether nothing has been interned.
61 pub fn is_empty(&self) -> bool {
62 self.strings.is_empty()
63 }
64
65 /// The strings, by id.
66 pub fn strings(&self) -> &[Box<str>] {
67 &self.strings
68 }
69
70 /// Occurrence count per id.
71 pub fn counts(&self) -> &[u32] {
72 &self.counts
73 }
74
75 /// Final id order and the remap from interned id to final id.
76 ///
77 /// `searchable` picks the contract: UTF-16 order for dictionaries the reader binary-searches,
78 /// descending frequency for the rest.
79 pub fn finish(&self, searchable: bool) -> (Vec<&str>, Vec<u32>) {
80 let mut order: Vec<u32> = (0..self.strings.len() as u32).collect();
81 if searchable {
82 order.par_sort_unstable_by(|&a, &b| {
83 cmp_utf16(&self.strings[a as usize], &self.strings[b as usize])
84 });
85 } else {
86 // Descending frequency, ties broken by UTF-16 order so the output is deterministic
87 // rather than dependent on the order strings happened to be seen in.
88 order.par_sort_unstable_by(|&a, &b| {
89 self.counts[b as usize]
90 .cmp(&self.counts[a as usize])
91 .then_with(|| cmp_utf16(&self.strings[a as usize], &self.strings[b as usize]))
92 });
93 }
94 let mut remap = vec![0u32; self.strings.len()];
95 let mut sorted = Vec::with_capacity(self.strings.len());
96 for (new_id, &old_id) in order.iter().enumerate() {
97 remap[old_id as usize] = new_id as u32;
98 sorted.push(&*self.strings[old_id as usize]);
99 }
100 (sorted, remap)
101 }
102}
103
104/// Compare two `str`s as Java/Kotlin `String`s do: by UTF-16 code unit.
105pub fn cmp_utf16(a: &str, b: &str) -> std::cmp::Ordering {
106 let mut ai = a.encode_utf16();
107 let mut bi = b.encode_utf16();
108 loop {
109 match (ai.next(), bi.next()) {
110 (None, None) => return std::cmp::Ordering::Equal,
111 (None, Some(_)) => return std::cmp::Ordering::Less,
112 (Some(_), None) => return std::cmp::Ordering::Greater,
113 (Some(x), Some(y)) if x == y => continue,
114 (Some(x), Some(y)) => return x.cmp(&y),
115 }
116 }
117}
118
119// --------------------------------------------------------------------------- encoders
120fn be32(out: &mut Vec<u8>, v: u32) {
121 out.extend_from_slice(&v.to_be_bytes());
122}
123
124fn be64(out: &mut Vec<u8>, v: i64) {
125 out.extend_from_slice(&v.to_be_bytes());
126}
127
128fn zigzag(v: i32) -> u32 {
129 ((v << 1) ^ (v >> 31)) as u32
130}
131
132fn write_varint(out: &mut Vec<u8>, mut v: u32) {
133 loop {
134 let b = (v & 0x7F) as u8;
135 v >>= 7;
136 if v == 0 {
137 out.push(b);
138 return;
139 }
140 out.push(b | 0x80);
141 }
142}
143
144/// Encode a dictionary section body, in independently compressed blocks:
145///
146/// ```text
147/// u32 count, u32 strings_per_block, u32 blocks
148/// u32 first_end[blocks] end of each block's first string within `firsts`
149/// firsts each block's first string, uncompressed and concatenated
150/// u32 block_end[blocks] end of each compressed block within `data`
151/// data per block: zstd([u32 len, utf8]...) for its strings
152/// ```
153///
154/// The reader binary-searches the uncompressed first strings straight out of the mapped file
155/// and decompresses one block of [`DICT_BLOCK`] strings, so it never holds a dictionary in
156/// memory. Blocks are compressed in parallel and reassembled in order, so the bytes do not
157/// depend on the thread count.
158pub fn encode_dict(strings: &[&str]) -> io::Result<Vec<u8>> {
159 let blocks: Vec<io::Result<Vec<u8>>> =
160 osm_ingest::par::map_chunks(strings, DICT_BLOCK, |_start, chunk| {
161 let mut raw = Vec::new();
162 for s in chunk {
163 be32(&mut raw, s.len() as u32);
164 raw.extend_from_slice(s.as_bytes());
165 }
166 zstd::encode_all(&raw[..], ZSTD_LEVEL)
167 });
168 let blocks: Vec<Vec<u8>> = blocks.into_iter().collect::<io::Result<_>>()?;
169
170 let mut out = Vec::new();
171 be32(&mut out, strings.len() as u32);
172 be32(&mut out, DICT_BLOCK as u32);
173 be32(&mut out, blocks.len() as u32);
174 let firsts: Vec<&str> = strings.iter().step_by(DICT_BLOCK).copied().collect();
175 let mut end = 0u32;
176 for s in &firsts {
177 end += s.len() as u32;
178 be32(&mut out, end);
179 }
180 for s in &firsts {
181 out.extend_from_slice(s.as_bytes());
182 }
183 let mut end = 0u32;
184 for b in &blocks {
185 end += b.len() as u32;
186 be32(&mut out, end);
187 }
188 for b in &blocks {
189 out.extend_from_slice(b);
190 }
191 Ok(out)
192}
193
194/// Encode a column section body.
195///
196/// A directory of `(raw_len, end)` per block comes first, where `end` is the block's end
197/// offset within the data that follows, so the reader finds any block straight from the mapped
198/// file without a table in memory. `prev` resets at each block boundary, which is what makes a
199/// block independently decodable.
200///
201/// Blocks are compressed in parallel. At level 19 zstd manages a couple of megabytes a second
202/// per core, which on a planet-scale column is hours of the build spent in one thread; the
203/// blocks are independent by construction, so this is the one place parallelism is free. The
204/// results are reassembled in chunk order, so the output does not depend on the thread count.
205pub fn encode_column(values: &[i32], delta: bool) -> io::Result<Vec<u8>> {
206 encode_column_with(values, delta, None)
207}
208
209/// Number of blocks [`encode_column`] writes for `n` values; an empty column still gets one.
210pub fn column_blocks(n: usize) -> u64 {
211 n.div_ceil(BLOCK).max(1) as u64
212}
213
214/// [`encode_column`], advancing `progress` once per compressed block.
215pub fn encode_column_with(
216 values: &[i32],
217 delta: bool,
218 progress: Option<&Progress>,
219) -> io::Result<Vec<u8>> {
220 let n = values.len();
221 let blocks = column_blocks(n) as usize;
222
223 let encoded: Vec<io::Result<(usize, Vec<u8>)>> =
224 osm_ingest::par::map_chunks(values, BLOCK, |_start, chunk| {
225 let mut raw = Vec::with_capacity(chunk.len() * 2);
226 let mut prev = 0i32;
227 for &v in chunk {
228 let enc = if delta { v.wrapping_sub(prev) } else { v };
229 write_varint(&mut raw, zigzag(enc));
230 prev = v;
231 }
232 let comp = zstd::encode_all(&raw[..], ZSTD_LEVEL)?;
233 if let Some(p) = progress {
234 p.inc();
235 }
236 Ok((raw.len(), comp))
237 });
238
239 let mut dir: Vec<(u32, u32)> = Vec::with_capacity(blocks);
240 let mut bodies: Vec<u8> = Vec::new();
241 for r in encoded {
242 let (raw_len, comp) = r?;
243 bodies.extend_from_slice(&comp);
244 dir.push((raw_len as u32, bodies.len() as u32));
245 }
246 // `map_chunks` yields nothing for an empty input, but the format still wants one empty
247 // block so the directory and the reader's block count agree.
248 if dir.is_empty() {
249 let comp = zstd::encode_all(&[][..], ZSTD_LEVEL)?;
250 bodies.extend_from_slice(&comp);
251 dir.push((0, bodies.len() as u32));
252 if let Some(p) = progress {
253 p.inc();
254 }
255 }
256
257 let mut out = Vec::with_capacity(bodies.len() + dir.len() * 8 + 8);
258 be32(&mut out, n as u32);
259 be32(&mut out, dir.len() as u32);
260 for (raw_len, end) in &dir {
261 be32(&mut out, *raw_len);
262 be32(&mut out, *end);
263 }
264 out.extend_from_slice(&bodies);
265 Ok(out)
266}
267
268/// Encode the grid section: `cellCount, [cellId, startRec]...`, uncompressed.
269///
270/// Left uncompressed because the reader's ring search probes it by binary search on open and
271/// on every reverse lookup; a compressed directory would have to be inflated whole first.
272pub fn encode_grid(cells: &[(i64, u32)]) -> Vec<u8> {
273 let mut out = Vec::with_capacity(cells.len() * 12 + 4);
274 be32(&mut out, cells.len() as u32);
275 for &(cell, start) in cells {
276 be64(&mut out, cell);
277 be32(&mut out, start);
278 }
279 out
280}
281
282/// Write one section: a big-endian length, then the body.
283pub fn write_section<W: Write>(out: &mut W, body: &[u8]) -> io::Result<u64> {
284 out.write_all(&(body.len() as u32).to_be_bytes())?;
285 out.write_all(body)?;
286 Ok(body.len() as u64 + 4)
287}
288
289#[cfg(test)]
290mod tests {
291 use super::*;
292
293 #[test]
294 fn utf16_order_differs_from_utf8_above_the_bmp() {
295 // U+FFFF encodes as ef bf bf; U+10000 as f0 90 80 80. UTF-8 puts U+10000 second.
296 let bmp = "\u{FFFF}";
297 let astral = "\u{10000}";
298 assert!(bmp.as_bytes() < astral.as_bytes(), "premise: UTF-8 puts the astral char second");
299 // UTF-16 puts it first, because a surrogate pair starts at 0xD800.
300 assert_eq!(cmp_utf16(astral, bmp), std::cmp::Ordering::Less);
301 }
302
303 #[test]
304 fn utf16_order_agrees_with_the_obvious_cases() {
305 use std::cmp::Ordering::*;
306 assert_eq!(cmp_utf16("", "a"), Less);
307 assert_eq!(cmp_utf16("a", "a"), Equal);
308 assert_eq!(cmp_utf16("a", "b"), Less);
309 assert_eq!(cmp_utf16("ab", "b"), Less);
310 assert_eq!(cmp_utf16("Z", "a"), Less);
311 assert_eq!(cmp_utf16("café", "cafe"), Greater);
312 }
313
314 #[test]
315 fn searchable_dictionaries_come_out_in_utf16_order() {
316 let mut i = Interner::new();
317 for s in ["banana", "", "\u{10000}", "\u{FFFF}", "apple", "banana"] {
318 let _ = i.intern(s);
319 }
320 let banana_old = i.intern("banana");
321 let (sorted, remap) = i.finish(true);
322 assert_eq!(sorted[0], "", "empty sorts first");
323 for w in sorted.windows(2) {
324 assert!(cmp_utf16(w[0], w[1]) == std::cmp::Ordering::Less, "{:?} !< {:?}", w[0], w[1]);
325 }
326 // The remap must send each interned id to where its string ended up.
327 assert_eq!(sorted[remap[banana_old as usize] as usize], "banana");
328 }
329
330 #[test]
331 fn frequency_dictionaries_put_the_commonest_value_at_id_zero() {
332 let mut i = Interner::new();
333 for _ in 0..10 {
334 let _ = i.intern("1");
335 }
336 for _ in 0..3 {
337 let _ = i.intern("22");
338 }
339 let _ = i.intern("333");
340 let one_old = i.intern("1");
341 let (sorted, remap) = i.finish(false);
342 assert_eq!(sorted, vec!["1", "22", "333"]);
343 assert_eq!(remap[one_old as usize], 0);
344 }
345
346 #[test]
347 fn frequency_ties_are_broken_deterministically() {
348 let mut a = Interner::new();
349 let _ = a.intern("x");
350 let _ = a.intern("y");
351 let mut b = Interner::new();
352 let _ = b.intern("y");
353 let _ = b.intern("x");
354 // Same multiset, different insertion order, same output.
355 assert_eq!(a.finish(false).0, b.finish(false).0);
356 }
357
358 /// Decode a column the way the reader does, to check the encoder against something other
359 /// than itself.
360 fn decode_column(body: &[u8], delta: bool) -> Vec<i32> {
361 let rd32 = |p: usize| -> u32 {
362 u32::from_be_bytes([body[p], body[p + 1], body[p + 2], body[p + 3]])
363 };
364 let n = rd32(0) as usize;
365 let blocks = rd32(4) as usize;
366 let data = 8 + blocks * 8;
367 let mut out = Vec::with_capacity(n);
368 let mut start = 0usize;
369 for b in 0..blocks {
370 let end = rd32(8 + b * 8 + 4) as usize;
371 let raw = zstd::decode_all(&body[data + start..data + end]).unwrap();
372 start = end;
373 let mut p = 0usize;
374 let mut prev = 0i32;
375 let count = (n - b * BLOCK).min(BLOCK);
376 for _ in 0..count {
377 let mut v = 0u32;
378 let mut shift = 0;
379 loop {
380 let byte = raw[p];
381 p += 1;
382 v |= ((byte & 0x7F) as u32) << shift;
383 if byte & 0x80 == 0 {
384 break;
385 }
386 shift += 7;
387 }
388 let dec = ((v >> 1) as i32) ^ -((v & 1) as i32);
389 let value = if delta { prev.wrapping_add(dec) } else { dec };
390 out.push(value);
391 prev = value;
392 }
393 }
394 out
395 }
396
397 #[test]
398 fn columns_round_trip_across_block_boundaries() {
399 // Deliberately not a multiple of BLOCK, so the last block is short.
400 let values: Vec<i32> = (0..BLOCK * 2 + 37).map(|i| (i as i32) * 7 - 1000).collect();
401 for delta in [true, false] {
402 let body = encode_column(&values, delta).unwrap();
403 assert_eq!(decode_column(&body, delta), values, "delta={delta}");
404 }
405 }
406
407 #[test]
408 fn columns_round_trip_extremes_and_negatives() {
409 let values = vec![0, -1, 1, i32::MIN, i32::MAX, -900_000_000, 1_800_000_000, 0];
410 for delta in [true, false] {
411 let body = encode_column(&values, delta).unwrap();
412 assert_eq!(decode_column(&body, delta), values, "delta={delta}");
413 }
414 }
415
416 #[test]
417 fn an_empty_column_still_produces_a_readable_section() {
418 let body = encode_column(&[], false).unwrap();
419 assert_eq!(decode_column(&body, false), Vec::<i32>::new());
420 }
421
422 #[test]
423 fn delta_encoding_actually_shrinks_a_sorted_column() {
424 let values: Vec<i32> = (0..BLOCK).map(|i| 370_000_000 + i as i32).collect();
425 let plain = encode_column(&values, false).unwrap().len();
426 let delta = encode_column(&values, true).unwrap().len();
427 assert!(delta < plain, "delta {delta} should beat plain {plain}");
428 }
429
430 #[test]
431 fn dictionaries_round_trip() {
432 let strings = vec!["", "Main Street", "café", "\u{10000}"];
433 let body = encode_dict(&strings).unwrap();
434 assert_eq!(crate::write::decode_dict(&body).unwrap(), strings);
435 }
436
437 #[test]
438 fn dictionaries_round_trip_across_block_boundaries() {
439 // Not a multiple of DICT_BLOCK, so the last block is short.
440 let owned: Vec<String> = (0..DICT_BLOCK * 2 + 37).map(|i| format!("name {i:06}")).collect();
441 let strings: Vec<&str> = owned.iter().map(String::as_str).collect();
442 let body = encode_dict(&strings).unwrap();
443 assert_eq!(crate::write::decode_dict(&body).unwrap(), strings);
444
445 // The first-string table is uncompressed and names each block's first entry, which is
446 // what lets the reader binary-search without decompressing.
447 let rd32 = |p: usize| u32::from_be_bytes(body[p..p + 4].try_into().unwrap()) as usize;
448 assert_eq!(rd32(8), 3, "three blocks");
449 let firsts = 12 + 3 * 4;
450 let (e0, e1) = (rd32(12), rd32(16));
451 assert_eq!(&body[firsts..firsts + e0], strings[0].as_bytes());
452 assert_eq!(&body[firsts + e0..firsts + e1], strings[DICT_BLOCK].as_bytes());
453 }
454
455 #[test]
456 fn an_empty_dictionary_is_readable() {
457 let body = encode_dict(&[]).unwrap();
458 assert_eq!(crate::write::decode_dict(&body).unwrap(), Vec::<String>::new());
459 }
460
461 #[test]
462 fn the_grid_section_is_fixed_width_and_ascending() {
463 let cells = vec![(0i64, 0u32), (5, 10), (7200, 25)];
464 let body = encode_grid(&cells);
465 assert_eq!(body.len(), 4 + cells.len() * 12);
466 assert_eq!(u32::from_be_bytes([body[0], body[1], body[2], body[3]]), 3);
467 }
468}