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

Modern-Apps.git / scripts / maps / wikidesc / src / archive.rs

archive.rs288 lines · 10.4 KiBRaw
1//! The `wikidesc` container: an id-sorted index over a blob of NUL-terminated paragraphs.
2//!
3//! ```text
4//! magic 8 "WIKIDESC"
5//! version 4 u32 LE
6//! count 4 u32 LE number of index entries
7//! index 16n (osm_id u64 LE, offset u64 LE), ASCENDING BY osm_id
8//! blob … UTF-8 paragraphs, each NUL-terminated
9//! ```
10//!
11//! # Why the index is sorted
12//!
13//! A lookup is a binary search followed by one read up to the next NUL. Sorted order is what makes
14//! that possible without loading anything, so the same file works whether it is downloaded whole —
15//! which is the plan, because descriptions have to survive going offline — or range-read like the
16//! basemap. Nothing about the format forces that choice.
17//!
18//! # Why offsets rather than lengths
19//!
20//! Two ids can point at the same offset, and identical text is then stored once. That matters more
21//! than it sounds: the lead of a small settlement is often a single templated sentence, and across
22//! a planet the repeats are not rare. It costs nothing — the terminator already delimits the text,
23//! so a length field would only be redundant.
24
25use std::collections::HashMap;
26use std::io::{Read, Write};
27
28pub const MAGIC: &[u8; 8] = b"WIKIDESC";
29pub const VERSION: u32 = 1;
30/// `magic` + `version` + `count`.
31const HEADER_LEN: usize = 16;
32const ENTRY_LEN: usize = 16;
33
34/// Collects descriptions and writes the archive.
35#[derive(Default)]
36pub struct Builder {
37 /// `osm_id -> offset into `blob``.
38 entries: Vec<(u64, u64)>,
39 /// Text already written, so a repeat costs one index entry rather than a second copy.
40 seen: HashMap<String, u64>,
41 blob: Vec<u8>,
42}
43
44impl Builder {
45 pub fn new() -> Self {
46 Self::default()
47 }
48
49 /// Record `text` for `osm_id`.
50 ///
51 /// Empty text is dropped rather than stored: an entry that resolves to nothing is worse than
52 /// no entry, because the caller cannot tell "no article" from "an article that said nothing".
53 /// A repeated id keeps the first text, which makes the build order-independent.
54 pub fn add(&mut self, osm_id: u64, text: &str) {
55 if text.is_empty() || self.entries.iter().any(|&(id, _)| id == osm_id) {
56 return;
57 }
58 let offset = match self.seen.get(text) {
59 Some(&at) => at,
60 None => {
61 let at = self.blob.len() as u64;
62 self.blob.extend_from_slice(text.as_bytes());
63 self.blob.push(0);
64 self.seen.insert(text.to_string(), at);
65 at
66 }
67 };
68 self.entries.push((osm_id, offset));
69 }
70
71 pub fn len(&self) -> usize {
72 self.entries.len()
73 }
74
75 pub fn is_empty(&self) -> bool {
76 self.entries.is_empty()
77 }
78
79 /// Bytes the blob would occupy, i.e. the archive minus its index.
80 pub fn blob_len(&self) -> usize {
81 self.blob.len()
82 }
83
84 /// How many entries share text with an earlier one.
85 pub fn shared(&self) -> usize {
86 self.entries.len() - self.seen.len()
87 }
88
89 pub fn write(mut self, out: &mut impl Write) -> std::io::Result<()> {
90 // Sorted here rather than demanded of the caller: the reader binary-searches, and a
91 // generator that streams a dump has no reason to produce ids in order.
92 self.entries.sort_unstable_by_key(|&(id, _)| id);
93 out.write_all(MAGIC)?;
94 out.write_all(&VERSION.to_le_bytes())?;
95 out.write_all(&(self.entries.len() as u32).to_le_bytes())?;
96 for (id, offset) in &self.entries {
97 out.write_all(&id.to_le_bytes())?;
98 out.write_all(&offset.to_le_bytes())?;
99 }
100 out.write_all(&self.blob)
101 }
102}
103
104/// A parsed archive held in memory.
105pub struct Archive {
106 index: Vec<(u64, u64)>,
107 blob: Vec<u8>,
108}
109
110impl Archive {
111 pub fn parse(bytes: &[u8]) -> Result<Self, String> {
112 if bytes.len() < HEADER_LEN {
113 return Err(format!("too short to be a wikidesc archive: {} bytes", bytes.len()));
114 }
115 if &bytes[..8] != MAGIC {
116 return Err("not a wikidesc archive: bad magic".to_string());
117 }
118 let version = u32::from_le_bytes(bytes[8..12].try_into().unwrap());
119 if version != VERSION {
120 return Err(format!("wikidesc version {version}, expected {VERSION}"));
121 }
122 let count = u32::from_le_bytes(bytes[12..16].try_into().unwrap()) as usize;
123 let blob_at = HEADER_LEN + count * ENTRY_LEN;
124 if bytes.len() < blob_at {
125 return Err(format!(
126 "index of {count} needs {blob_at} bytes, file has {}",
127 bytes.len()
128 ));
129 }
130 let mut index = Vec::with_capacity(count);
131 for i in 0..count {
132 let at = HEADER_LEN + i * ENTRY_LEN;
133 index.push((
134 u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap()),
135 u64::from_le_bytes(bytes[at + 8..at + 16].try_into().unwrap()),
136 ));
137 }
138 Ok(Archive { index, blob: bytes[blob_at..].to_vec() })
139 }
140
141 pub fn read(source: &mut impl Read) -> Result<Self, String> {
142 let mut bytes = Vec::new();
143 source.read_to_end(&mut bytes).map_err(|e| e.to_string())?;
144 Archive::parse(&bytes)
145 }
146
147 pub fn len(&self) -> usize {
148 self.index.len()
149 }
150
151 pub fn is_empty(&self) -> bool {
152 self.index.is_empty()
153 }
154
155 /// The description for `osm_id`, or `None`.
156 ///
157 /// Binary search, then read to the terminator. A truncated final run — a file cut short in
158 /// transit — reads to the end rather than failing, because a partial sentence is still better
159 /// than an error in a bottom sheet.
160 pub fn get(&self, osm_id: u64) -> Option<&str> {
161 let at = self.index.binary_search_by_key(&osm_id, |&(id, _)| id).ok()?;
162 let start = self.index[at].1 as usize;
163 if start >= self.blob.len() {
164 return None;
165 }
166 let rest = &self.blob[start..];
167 let end = rest.iter().position(|&b| b == 0).unwrap_or(rest.len());
168 std::str::from_utf8(&rest[..end]).ok()
169 }
170}
171
172#[cfg(test)]
173mod tests {
174 use super::*;
175
176 fn build(pairs: &[(u64, &str)]) -> Vec<u8> {
177 let mut b = Builder::new();
178 for &(id, text) in pairs {
179 b.add(id, text);
180 }
181 let mut out = Vec::new();
182 b.write(&mut out).expect("write");
183 out
184 }
185
186 #[test]
187 fn a_description_survives_a_round_trip() {
188 let bytes = build(&[(1, "Paris is the capital of France."), (2, "Berlin is in Germany.")]);
189 let a = Archive::parse(&bytes).expect("parse");
190 assert_eq!(a.len(), 2);
191 assert_eq!(a.get(1), Some("Paris is the capital of France."));
192 assert_eq!(a.get(2), Some("Berlin is in Germany."));
193 assert_eq!(a.get(3), None, "an id with no article");
194 }
195
196 /// Ids arrive in whatever order the dump yields them; the reader binary-searches, so the
197 /// writer sorts.
198 #[test]
199 fn the_index_is_sorted_whatever_order_ids_arrive_in() {
200 let bytes = build(&[(900, "nine"), (7, "seven"), (500, "five"), (1, "one")]);
201 let a = Archive::parse(&bytes).expect("parse");
202 let ids: Vec<u64> = a.index.iter().map(|&(id, _)| id).collect();
203 assert_eq!(ids, vec![1, 7, 500, 900]);
204 for (id, want) in [(1, "one"), (7, "seven"), (500, "five"), (900, "nine")] {
205 assert_eq!(a.get(id), Some(want));
206 }
207 }
208
209 /// The reason offsets are stored rather than lengths. Templated one-line leads repeat across a
210 /// planet, and a repeat should cost 16 bytes of index, not a second copy of the text.
211 #[test]
212 fn identical_text_is_stored_once() {
213 let shared = "A village in Timiș County, Romania.";
214 let mut b = Builder::new();
215 for id in 1..=100u64 {
216 b.add(id, shared);
217 }
218 assert_eq!(b.len(), 100);
219 assert_eq!(b.shared(), 99, "ninety-nine of them share the first copy");
220 assert_eq!(b.blob_len(), shared.len() + 1, "one copy plus its terminator");
221
222 let mut bytes = Vec::new();
223 b.write(&mut bytes).expect("write");
224 let a = Archive::parse(&bytes).expect("parse");
225 assert_eq!(a.get(1), Some(shared));
226 assert_eq!(a.get(100), Some(shared));
227 }
228
229 /// An entry resolving to nothing is worse than no entry: the caller cannot tell it from a real
230 /// empty article.
231 #[test]
232 fn empty_text_is_not_stored() {
233 let bytes = build(&[(1, ""), (2, "real")]);
234 let a = Archive::parse(&bytes).expect("parse");
235 assert_eq!(a.len(), 1);
236 assert_eq!(a.get(1), None);
237 assert_eq!(a.get(2), Some("real"));
238 }
239
240 #[test]
241 fn a_repeated_id_keeps_the_first_text() {
242 let bytes = build(&[(1, "first"), (1, "second")]);
243 let a = Archive::parse(&bytes).expect("parse");
244 assert_eq!(a.len(), 1);
245 assert_eq!(a.get(1), Some("first"), "so a build does not depend on input order");
246 }
247
248 #[test]
249 fn an_empty_archive_is_valid() {
250 let bytes = build(&[]);
251 let a = Archive::parse(&bytes).expect("parse");
252 assert!(a.is_empty());
253 assert_eq!(a.get(1), None);
254 }
255
256 #[test]
257 fn utf8_survives_intact() {
258 let text = "Săcălaz is a commune in Timiș County, Romania.";
259 let bytes = build(&[(1, text)]);
260 assert_eq!(Archive::parse(&bytes).expect("parse").get(1), Some(text));
261 }
262
263 #[test]
264 fn a_file_that_is_not_an_archive_is_rejected_rather_than_misread() {
265 assert!(Archive::parse(b"").is_err());
266 assert!(Archive::parse(b"short").is_err());
267 assert!(Archive::parse(b"NOTMAGIC\x01\0\0\0\0\0\0\0").is_err());
268 // Right magic, wrong version.
269 let mut wrong = MAGIC.to_vec();
270 wrong.extend_from_slice(&99u32.to_le_bytes());
271 wrong.extend_from_slice(&0u32.to_le_bytes());
272 assert!(Archive::parse(&wrong).is_err());
273 // A count the file cannot possibly hold.
274 let mut lying = MAGIC.to_vec();
275 lying.extend_from_slice(&VERSION.to_le_bytes());
276 lying.extend_from_slice(&1000u32.to_le_bytes());
277 assert!(Archive::parse(&lying).is_err());
278 }
279
280 /// A download cut short. A partial sentence beats an error in a bottom sheet.
281 #[test]
282 fn a_truncated_final_run_reads_to_the_end() {
283 let mut bytes = build(&[(1, "a complete sentence.")]);
284 bytes.truncate(bytes.len() - 5);
285 let a = Archive::parse(&bytes).expect("the index is intact");
286 assert_eq!(a.get(1), Some("a complete sente"));
287 }
288}