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

Modern-Apps.git / scripts / maps / mamaps_build / src / tilespill_part1.rs

tilespill_part1.rs364 lines · 15.7 KiBRaw
1impl ChunkReader<'_> {
2 /// Skip one entry without decoding it, returning its key and merge cost.
3 ///
4 /// Byte-for-byte the same cursor movement as [`next`](Self::next) —
5 /// header, fixed arenas, name lengths, turn counts, building and
6 /// carriageway sections — minus every allocation, UTF-8 check and struct
7 /// build. The range planner uses it to walk chunks cheaply (cost histogram
8 /// plus boundary offsets); the merge workers then decode for real. A corrupt
9 /// entry errors here exactly as `next` would surface it, so planning fails
10 /// fast rather than handing workers a desynced stream.
11 ///
12 /// Never touches the spill's read counters: planning reads are not
13 /// decoded entries, and `check_books` must see each entry counted once —
14 /// by the worker that decodes it.
15 pub fn skip_entry(&mut self) -> Result<Option<((u64, u8), u64)>> {
16 if self.left == 0 {
17 return Ok(None);
18 }
19 self.fill(ENTRY_HEADER_BYTES)?;
20 let head: &[u8; ENTRY_HEADER_BYTES] = self.buf[self.used..self.used + ENTRY_HEADER_BYTES]
21 .try_into()
22 .expect("a header's worth of bytes");
23 let header = entry_header(head)?;
24 let fixed =
25 payload_bytes(header.features, header.parts, header.coords, header.ids) as usize;
26 self.fill(ENTRY_HEADER_BYTES + fixed)?;
27 self.used += ENTRY_HEADER_BYTES + fixed;
28 for _ in 0..header.names {
29 self.fill(4)?;
30 let len = u32::from_le_bytes(
31 self.buf[self.used..self.used + 4].try_into().expect("4 bytes"),
32 ) as usize;
33 if len > 1 << 20 {
34 return err("a tile chunk entry names a megabyte-plus string".to_string());
35 }
36 self.fill(4 + len)?;
37 self.used += 4 + len;
38 }
39 if header.has_turns {
40 for _ in 0..header.features {
41 self.fill(2)?;
42 let (fwd, bwd) =
43 (self.buf[self.used] as usize, self.buf[self.used + 1] as usize);
44 let bytes = 2 + 2 * (fwd + bwd);
45 self.fill(bytes)?;
46 self.used += bytes;
47 }
48 }
49 if header.has_buildings {
50 let bytes = BUILDING_BYTES * header.features;
51 self.fill(bytes)?;
52 self.used += bytes;
53 }
54 if header.has_carriageways {
55 let bytes = CARRIAGEWAY_RECORD_LEN * header.features;
56 self.fill(bytes)?;
57 self.used += bytes;
58 }
59 self.left -= 1;
60 // Same cost unit the merge batches by (`tile_cost`): features plus
61 // coordinates, the proxy the encode pass balances tasks by.
62 let cost = header.features as u64 + header.coords as u64;
63 Ok(Some(((header.tile, header.layer_id), cost)))
64 }
65
66 /// File offset of the next unread byte: what a range worker seeks to.
67 ///
68 /// `at` is the first byte not yet buffered, so the unread position is
69 /// behind it by exactly the buffered-but-unconsumed span.
70 pub fn position(&self) -> u64 {
71 self.at - (self.buf.len() - self.used) as u64
72 }
73
74 /// The next entry's tile id without consuming it.
75 ///
76 /// A range worker seeks to a bucket edge (coarser than its tile bound),
77 /// then advances past entries below the bound with [`skip_entry`](Self::skip_entry)
78 /// — counted down from `left` like any consumed entry, uncounted in the
79 /// spill books like any skip. `None` past the last entry (no trailing
80 /// check here; [`next`](Self::next) owns that).
81 pub fn peek_tile(&mut self) -> Result<Option<u64>> {
82 if self.left == 0 {
83 return Ok(None);
84 }
85 self.fill(ENTRY_HEADER_BYTES)?;
86 let head: &[u8; ENTRY_HEADER_BYTES] = self.buf[self.used..self.used + ENTRY_HEADER_BYTES]
87 .try_into()
88 .expect("a header's worth of bytes");
89 Ok(Some(entry_header(head)?.tile))
90 }
91
92 /// Reposition a reader at a planned offset with a planned entry count.
93 ///
94 /// The buffer is discarded (its bytes belong to another range now and
95 /// will be re-read through the window); `end` is unchanged. `exact_end`
96 /// says whether this segment runs to the chunk's last byte: only then
97 /// does [`next`](Self::next) enforce the no-trailing-bytes check, since
98 /// any other segment legitimately ends mid-chunk with the next range's
99 /// bytes after it.
100 pub fn seek_to(&mut self, offset: u64, remaining: u64, exact_end: bool) {
101 self.buf.clear();
102 self.used = 0;
103 self.at = offset;
104 self.left = remaining;
105 self.exact_end = exact_end;
106 }
107 ///
108 /// Fallible, and that matters: a truncated scratch file must fail the build rather than silently
109 /// shorten the archive.
110 #[allow(clippy::should_implement_trait)]
111 pub fn next(&mut self) -> Result<Option<((u64, u8), ChunkEntry)>> {
112 if self.left == 0 {
113 if self.exact_end && (self.used < self.buf.len() || self.at < self.end) {
114 return err(format!(
115 "a tile chunk in {} holds bytes past its last entry",
116 self.spill.path.display()
117 ));
118 }
119 return Ok(None);
120 }
121 self.fill(ENTRY_HEADER_BYTES)?;
122 let head: &[u8; ENTRY_HEADER_BYTES] = self.buf[self.used..self.used + ENTRY_HEADER_BYTES]
123 .try_into()
124 .expect("a header's worth of bytes");
125 let header = entry_header(head)?;
126 // The fixed arenas first: their length is a pure function of the header, so one fill
127 // covers them. Names follow with inline lengths and are pulled one at a time — their
128 // byte length is known only once the previous one is read.
129 let fixed =
130 payload_bytes(header.features, header.parts, header.coords, header.ids) as usize;
131 self.fill(ENTRY_HEADER_BYTES + fixed)?;
132 let body = self.used + ENTRY_HEADER_BYTES;
133 let spare = self.spare.take();
134 let mut entry = decode_fixed(&header, &self.buf[body..body + fixed], spare)?;
135 self.used = body + fixed;
136 // Counted, not differenced: `fill` compacts the buffer when it tops up, so a span across
137 // two buffer positions is not the difference of two offsets.
138 let mut consumed = ENTRY_HEADER_BYTES + fixed;
139 for _ in 0..header.names {
140 self.fill(4)?;
141 let len = u32::from_le_bytes(
142 self.buf[self.used..self.used + 4].try_into().expect("4 bytes"),
143 ) as usize;
144 if len > 1 << 20 {
145 return err("a tile chunk entry names a megabyte-plus string".to_string());
146 }
147 self.fill(4 + len)?;
148 let bytes = &self.buf[self.used + 4..self.used + 4 + len];
149 entry.names.push(
150 std::str::from_utf8(bytes)
151 .map_err(|_| Error("a tile chunk entry's name is not UTF-8".to_string()))?
152 .to_string(),
153 );
154 self.used += 4 + len;
155 consumed += 4 + len;
156 }
157 // Every name index must land in the table just read: a dangling index would decode to
158 // the wrong label on device with no other symptom.
159 for feature in &entry.layer.features {
160 if feature.name_idx as usize > entry.names.len() {
161 return err("a tile chunk feature names past its entry's table".to_string());
162 }
163 }
164 // The turn-lane section, after the names when the flag is set: one record per feature,
165 // each a u8 forward count, u8 backward count, then that many u16 masks each.
166 if header.has_turns {
167 entry.turn_lanes.reserve(header.features);
168 for _ in 0..header.features {
169 self.fill(2)?;
170 let (fwd, bwd) =
171 (self.buf[self.used] as usize, self.buf[self.used + 1] as usize);
172 let bytes = 2 + 2 * (fwd + bwd);
173 self.fill(bytes)?;
174 let read = |off: usize, n: usize| -> Vec<u16> {
175 (0..n)
176 .map(|k| {
177 let o = self.used + off + k * 2;
178 u16::from_le_bytes([self.buf[o], self.buf[o + 1]])
179 })
180 .collect()
181 };
182 let forward = read(2, fwd);
183 let backward = read(2 + 2 * fwd, bwd);
184 entry.turn_lanes.push(tilecodec::mamaps::body::LaneTurns { forward, backward });
185 self.used += bytes;
186 consumed += bytes;
187 }
188 }
189 // The building section, after the turn-lane section when the flag is set: one
190 // BUILDING_BYTES record per feature, dense.
191 if header.has_buildings {
192 entry.buildings.reserve(header.features);
193 for _ in 0..header.features {
194 self.fill(BUILDING_BYTES)?;
195 let o = self.used;
196 let u16_at = |k: usize| u16::from_le_bytes([self.buf[o + k], self.buf[o + k + 1]]);
197 let u32_at = |k: usize| {
198 u32::from_le_bytes([
199 self.buf[o + k],
200 self.buf[o + k + 1],
201 self.buf[o + k + 2],
202 self.buf[o + k + 3],
203 ])
204 };
205 entry.buildings.push(BuildingAttrs {
206 height: u16_at(0),
207 min_height: u16_at(2),
208 roof_height: u16_at(4),
209 roof_shape: self.buf[o + 6],
210 roof_direction: self.buf[o + 7],
211 roof_orientation: self.buf[o + 8],
212 building_colour: u32_at(9),
213 roof_colour: u32_at(13),
214 });
215 self.used += BUILDING_BYTES;
216 consumed += BUILDING_BYTES;
217 }
218 }
219 // The carriageway section, last, when the flag is set: one [`CARRIAGEWAY_RECORD_LEN`]
220 // record per feature, dense.
221 if header.has_carriageways {
222 entry.carriageways.reserve(header.features);
223 for _ in 0..header.features {
224 self.fill(CARRIAGEWAY_RECORD_LEN)?;
225 let o = self.used;
226 entry.carriageways.push(Carriageway {
227 forward: self.buf[o],
228 backward: self.buf[o + 1],
229 solid_dividers: u32::from_le_bytes([
230 self.buf[o + 2],
231 self.buf[o + 3],
232 self.buf[o + 4],
233 self.buf[o + 5],
234 ]),
235 });
236 self.used += CARRIAGEWAY_RECORD_LEN;
237 consumed += CARRIAGEWAY_RECORD_LEN;
238 }
239 }
240 self.left -= 1;
241 self.spill.read.fetch_add(consumed as u64, Ordering::Relaxed);
242 self.spill.read_entries.fetch_add(1, Ordering::Relaxed);
243 Ok(Some(((header.tile, header.layer_id), entry)))
244 }
245
246 /// Make at least `need` unread bytes available in `buf`.
247 fn fill(&mut self, need: usize) -> Result<()> {
248 if self.buf.len() - self.used >= need {
249 return Ok(());
250 }
251 if self.used > 0 {
252 self.buf.copy_within(self.used.., 0);
253 let keep = self.buf.len() - self.used;
254 self.buf.truncate(keep);
255 self.used = 0;
256 }
257 // An entry larger than the window is read whole rather than in pieces: the decode wants it
258 // contiguous, and one such entry is bounded by `MAX_ENTRY_BYTES`.
259 let want = need.max(self.window) - self.buf.len();
260 let take = want.min((self.end - self.at) as usize);
261 if self.buf.len() + take < need {
262 return err(format!(
263 "a tile chunk in {} ends {} byte(s) into a {need}-byte read",
264 self.spill.path.display(),
265 self.buf.len() + take
266 ));
267 }
268 let base = self.buf.len();
269 self.buf.resize(base + take, 0);
270 match (&self.spill.file, &self.spill.anon) {
271 (Some(f), None) => {
272 tilecodec::pmtiles::read_exact_at(f, &mut self.buf[base..], self.at)
273 .map_err(|e| Error(format!("reading {}: {e}", self.spill.path.display())))?;
274 }
275 (None, Some(a)) => {
276 a.lock()
277 .expect("the anon tile chunk spill")
278 .read_at(self.at, &mut self.buf[base..])
279 .map_err(|e| Error(format!("reading {}: {e}", self.spill.path.display())))?;
280 }
281 _ => {
282 return err(format!(
283 "a tile chunk spill for {} has no backend",
284 self.spill.path.display()
285 ))
286 }
287 }
288 self.at += take as u64;
289 Ok(())
290 }
291
292 /// Take back an entry whose arenas the merge has drained, to reuse on the next decode.
293 ///
294 /// The merge hands this back the emptied [`ChunkEntry`] it just concatenated into its
295 /// accumulator; [`Self::next`] then fills these buffers instead of allocating fresh ones. Every
296 /// arena is cleared (so no stale value can leak into a later entry) but its capacity is kept,
297 /// which is the whole point. A single slot is enough: the merge consumes one of a reader's
298 /// entries and immediately decodes the next, so the buffers are back in hand exactly when the
299 /// next decode wants them.
300 pub fn recycle(&mut self, mut entry: ChunkEntry) {
301 entry.layer.features.clear();
302 entry.layer.parts.clear();
303 entry.layer.coords.clear();
304 entry.names.clear();
305 entry.ids.clear();
306 entry.turn_lanes.clear();
307 entry.buildings.clear();
308 entry.carriageways.clear();
309 self.spare = Some(entry);
310 }
311}
312
313/// How many bytes one entry encodes to, or an error when an arena is past what a `u32` addresses.
314fn entry_bytes(entry: &ChunkEntry) -> Result<u64> {
315 let layer = &entry.layer;
316 let count = |what: &str, n: usize| -> Result<usize> {
317 if n > u32::MAX as usize {
318 return err(format!("a tile chunk entry holds {n} {what}, which no header can address"));
319 }
320 Ok(n)
321 };
322 let features = count("feature(s)", layer.features.len())?;
323 let parts = count("part(s)", layer.parts.len())?;
324 let coords = count("coordinate(s)", layer.coords.len())?;
325 let ids = count("id(s)", entry.ids.len())?;
326 let mut names_bytes = 0u64;
327 for name in &entry.names {
328 names_bytes += 4 + name.len() as u64;
329 }
330 let mut turns_bytes = 0u64;
331 for turns in &entry.turn_lanes {
332 turns_bytes += 2 + 2 * (turns.forward.len() as u64 + turns.backward.len() as u64);
333 }
334 // The building section: one fixed record per feature when present.
335 let buildings_bytes = if entry.buildings.is_empty() {
336 0
337 } else {
338 entry.buildings.len() as u64 * BUILDING_BYTES as u64
339 };
340 // And the carriageway section, likewise fixed-width and one per feature.
341 let carriageways_bytes = if entry.carriageways.is_empty() {
342 0
343 } else {
344 entry.carriageways.len() as u64 * CARRIAGEWAY_RECORD_LEN as u64
345 };
346 Ok(ENTRY_HEADER_BYTES as u64
347 + payload_bytes(features, parts, coords, ids)
348 + names_bytes
349 + turns_bytes
350 + buildings_bytes
351 + carriageways_bytes)
352}
353
354/// The payload width implied by an entry's four counts. A pure function of the header, which is
355/// what lets a reader validate before it allocates. Names ride after the fixed arenas and are
356/// counted in the header's own `names` field.
357fn payload_bytes(features: usize, parts: usize, coords: usize, ids: usize) -> u64 {
358 features as u64 * FEATURE_BYTES as u64
359 + parts as u64 * PART_BYTES as u64
360 + coords as u64 * COORD_BYTES as u64
361 + ids as u64 * ID_BYTES as u64
362}
363
364include!("tilespill_part1_s1.rs");