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

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

archive.rs285 lines · 10.3 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!("index of {count} needs {blob_at} bytes, file has {}", bytes.len()));
126 }
127 let mut index = Vec::with_capacity(count);
128 for i in 0..count {
129 let at = HEADER_LEN + i * ENTRY_LEN;
130 index.push((
131 u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap()),
132 u64::from_le_bytes(bytes[at + 8..at + 16].try_into().unwrap()),
133 ));
134 }
135 Ok(Archive { index, blob: bytes[blob_at..].to_vec() })
136 }
137
138 pub fn read(source: &mut impl Read) -> Result<Self, String> {
139 let mut bytes = Vec::new();
140 source.read_to_end(&mut bytes).map_err(|e| e.to_string())?;
141 Archive::parse(&bytes)
142 }
143
144 pub fn len(&self) -> usize {
145 self.index.len()
146 }
147
148 pub fn is_empty(&self) -> bool {
149 self.index.is_empty()
150 }
151
152 /// The description for `osm_id`, or `None`.
153 ///
154 /// Binary search, then read to the terminator. A truncated final run — a file cut short in
155 /// transit — reads to the end rather than failing, because a partial sentence is still better
156 /// than an error in a bottom sheet.
157 pub fn get(&self, osm_id: u64) -> Option<&str> {
158 let at = self.index.binary_search_by_key(&osm_id, |&(id, _)| id).ok()?;
159 let start = self.index[at].1 as usize;
160 if start >= self.blob.len() {
161 return None;
162 }
163 let rest = &self.blob[start..];
164 let end = rest.iter().position(|&b| b == 0).unwrap_or(rest.len());
165 std::str::from_utf8(&rest[..end]).ok()
166 }
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172
173 fn build(pairs: &[(u64, &str)]) -> Vec<u8> {
174 let mut b = Builder::new();
175 for &(id, text) in pairs {
176 b.add(id, text);
177 }
178 let mut out = Vec::new();
179 b.write(&mut out).expect("write");
180 out
181 }
182
183 #[test]
184 fn a_description_survives_a_round_trip() {
185 let bytes = build(&[(1, "Paris is the capital of France."), (2, "Berlin is in Germany.")]);
186 let a = Archive::parse(&bytes).expect("parse");
187 assert_eq!(a.len(), 2);
188 assert_eq!(a.get(1), Some("Paris is the capital of France."));
189 assert_eq!(a.get(2), Some("Berlin is in Germany."));
190 assert_eq!(a.get(3), None, "an id with no article");
191 }
192
193 /// Ids arrive in whatever order the dump yields them; the reader binary-searches, so the
194 /// writer sorts.
195 #[test]
196 fn the_index_is_sorted_whatever_order_ids_arrive_in() {
197 let bytes = build(&[(900, "nine"), (7, "seven"), (500, "five"), (1, "one")]);
198 let a = Archive::parse(&bytes).expect("parse");
199 let ids: Vec<u64> = a.index.iter().map(|&(id, _)| id).collect();
200 assert_eq!(ids, vec![1, 7, 500, 900]);
201 for (id, want) in [(1, "one"), (7, "seven"), (500, "five"), (900, "nine")] {
202 assert_eq!(a.get(id), Some(want));
203 }
204 }
205
206 /// The reason offsets are stored rather than lengths. Templated one-line leads repeat across a
207 /// planet, and a repeat should cost 16 bytes of index, not a second copy of the text.
208 #[test]
209 fn identical_text_is_stored_once() {
210 let shared = "A village in Timiș County, Romania.";
211 let mut b = Builder::new();
212 for id in 1..=100u64 {
213 b.add(id, shared);
214 }
215 assert_eq!(b.len(), 100);
216 assert_eq!(b.shared(), 99, "ninety-nine of them share the first copy");
217 assert_eq!(b.blob_len(), shared.len() + 1, "one copy plus its terminator");
218
219 let mut bytes = Vec::new();
220 b.write(&mut bytes).expect("write");
221 let a = Archive::parse(&bytes).expect("parse");
222 assert_eq!(a.get(1), Some(shared));
223 assert_eq!(a.get(100), Some(shared));
224 }
225
226 /// An entry resolving to nothing is worse than no entry: the caller cannot tell it from a real
227 /// empty article.
228 #[test]
229 fn empty_text_is_not_stored() {
230 let bytes = build(&[(1, ""), (2, "real")]);
231 let a = Archive::parse(&bytes).expect("parse");
232 assert_eq!(a.len(), 1);
233 assert_eq!(a.get(1), None);
234 assert_eq!(a.get(2), Some("real"));
235 }
236
237 #[test]
238 fn a_repeated_id_keeps_the_first_text() {
239 let bytes = build(&[(1, "first"), (1, "second")]);
240 let a = Archive::parse(&bytes).expect("parse");
241 assert_eq!(a.len(), 1);
242 assert_eq!(a.get(1), Some("first"), "so a build does not depend on input order");
243 }
244
245 #[test]
246 fn an_empty_archive_is_valid() {
247 let bytes = build(&[]);
248 let a = Archive::parse(&bytes).expect("parse");
249 assert!(a.is_empty());
250 assert_eq!(a.get(1), None);
251 }
252
253 #[test]
254 fn utf8_survives_intact() {
255 let text = "Săcălaz is a commune in Timiș County, Romania.";
256 let bytes = build(&[(1, text)]);
257 assert_eq!(Archive::parse(&bytes).expect("parse").get(1), Some(text));
258 }
259
260 #[test]
261 fn a_file_that_is_not_an_archive_is_rejected_rather_than_misread() {
262 assert!(Archive::parse(b"").is_err());
263 assert!(Archive::parse(b"short").is_err());
264 assert!(Archive::parse(b"NOTMAGIC\x01\0\0\0\0\0\0\0").is_err());
265 // Right magic, wrong version.
266 let mut wrong = MAGIC.to_vec();
267 wrong.extend_from_slice(&99u32.to_le_bytes());
268 wrong.extend_from_slice(&0u32.to_le_bytes());
269 assert!(Archive::parse(&wrong).is_err());
270 // A count the file cannot possibly hold.
271 let mut lying = MAGIC.to_vec();
272 lying.extend_from_slice(&VERSION.to_le_bytes());
273 lying.extend_from_slice(&1000u32.to_le_bytes());
274 assert!(Archive::parse(&lying).is_err());
275 }
276
277 /// A download cut short. A partial sentence beats an error in a bottom sheet.
278 #[test]
279 fn a_truncated_final_run_reads_to_the_end() {
280 let mut bytes = build(&[(1, "a complete sentence.")]);
281 bytes.truncate(bytes.len() - 5);
282 let a = Archive::parse(&bytes).expect("the index is intact");
283 assert_eq!(a.get(1), Some("a complete sente"));
284 }
285}