Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / tilespill_part1.rs
tilespill_part1.rs594 lines · 25.6 KiBRaw
| 1 | impl 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 | /// + 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. |
| 314 | fn 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. |
| 357 | fn 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 | |
| 364 | fn encode_entry(tile: u64, layer_id: u8, entry: &ChunkEntry, out: &mut Vec<u8>) { |
| 365 | let layer = &entry.layer; |
| 366 | let base = out.len(); |
| 367 | out.resize(base + ENTRY_HEADER_BYTES, 0); |
| 368 | out[base..base + 8].copy_from_slice(&tile.to_le_bytes()); |
| 369 | out[base + 8..base + 12].copy_from_slice(&(layer.features.len() as u32).to_le_bytes()); |
| 370 | out[base + 12..base + 16].copy_from_slice(&(layer.parts.len() as u32).to_le_bytes()); |
| 371 | out[base + 16..base + 20].copy_from_slice(&(layer.coords.len() as u32).to_le_bytes()); |
| 372 | out[base + 20] = layer_id; |
| 373 | // Byte 21 flags a turn-lane section after the names; byte 22 a building section after that; |
| 374 | // byte 23 a carriageway section after that. The building section is `features` records (one per |
| 375 | // feature, dense), each a BUILDING_BYTES packed [`BuildingAttrs`]. Present only for a |
| 376 | // `buildings` tile that had S3DB attributes in it. |
| 377 | // |
| 378 | // The carriageway section is the same shape for the `roads` layer. It has to be here rather |
| 379 | // than reconstructed later: a side table that never reaches the spill is dropped on every |
| 380 | // build that spills a zoom, and the archive comes back with no lane markings and no error. |
| 381 | let has_turns = !entry.turn_lanes.is_empty(); |
| 382 | let has_buildings = !entry.buildings.is_empty(); |
| 383 | let has_carriageways = !entry.carriageways.is_empty(); |
| 384 | out[base + 21] = has_turns as u8; |
| 385 | out[base + 22] = has_buildings as u8; |
| 386 | out[base + 23] = has_carriageways as u8; |
| 387 | out[base + 24..base + 28].copy_from_slice(&(entry.names.len() as u32).to_le_bytes()); |
| 388 | out[base + 28..base + 32].copy_from_slice(&(entry.ids.len() as u32).to_le_bytes()); |
| 389 | for feature in &layer.features { |
| 390 | // The spill carries the v2 index, not the v1 wire: name_idx, transit_color and the three |
| 391 | // transit lane bytes ride the entry and are re-encoded by the body serializer, so the |
| 392 | // scratch format never lags the codec by a version. |
| 393 | out.extend_from_slice(&feature.kind.to_le_bytes()); |
| 394 | out.extend_from_slice(&feature.kind_detail.to_le_bytes()); |
| 395 | out.push(feature.geom_type); |
| 396 | out.push(feature.flags); |
| 397 | out.extend_from_slice(&feature.name_idx.to_le_bytes()); |
| 398 | out.extend_from_slice(&feature.parts_offset.to_le_bytes()); |
| 399 | out.extend_from_slice(&feature.part_count.to_le_bytes()); |
| 400 | out.extend_from_slice(&feature.transit_color.to_le_bytes()); |
| 401 | out.push(feature.transit_ordinal); |
| 402 | out.push(feature.transit_lanes); |
| 403 | out.push(feature.transit_taper); |
| 404 | out.push(feature.lane_count); |
| 405 | } |
| 406 | for part in &layer.parts { |
| 407 | out.extend_from_slice(&part.coord_start.to_le_bytes()); |
| 408 | out.extend_from_slice(&part.point_count.to_le_bytes()); |
| 409 | out.extend_from_slice(&part.winding.to_le_bytes()); |
| 410 | } |
| 411 | for (x, y) in &layer.coords { |
| 412 | out.extend_from_slice(&x.to_le_bytes()); |
| 413 | out.extend_from_slice(&y.to_le_bytes()); |
| 414 | } |
| 415 | for id in &entry.ids { |
| 416 | out.extend_from_slice(&id.to_le_bytes()); |
| 417 | } |
| 418 | for name in &entry.names { |
| 419 | out.extend_from_slice(&(name.len() as u32).to_le_bytes()); |
| 420 | out.extend_from_slice(name.as_bytes()); |
| 421 | } |
| 422 | // The turn-lane section, after the names, when present. One record per feature, dense. |
| 423 | if has_turns { |
| 424 | for turns in &entry.turn_lanes { |
| 425 | out.push(turns.forward.len() as u8); |
| 426 | out.push(turns.backward.len() as u8); |
| 427 | for m in turns.forward.iter().chain(&turns.backward) { |
| 428 | out.extend_from_slice(&m.to_le_bytes()); |
| 429 | } |
| 430 | } |
| 431 | } |
| 432 | // The building section, after the turn-lane section, when present. One record per feature. |
| 433 | if has_buildings { |
| 434 | for a in &entry.buildings { |
| 435 | out.extend_from_slice(&a.height.to_le_bytes()); |
| 436 | out.extend_from_slice(&a.min_height.to_le_bytes()); |
| 437 | out.extend_from_slice(&a.roof_height.to_le_bytes()); |
| 438 | out.push(a.roof_shape); |
| 439 | out.push(a.roof_direction); |
| 440 | out.push(a.roof_orientation); |
| 441 | out.extend_from_slice(&a.building_colour.to_le_bytes()); |
| 442 | out.extend_from_slice(&a.roof_colour.to_le_bytes()); |
| 443 | } |
| 444 | } |
| 445 | // The carriageway section, last, when present. One record per feature, in the same field order |
| 446 | // the body's own [`CARRIAGEWAY_RECORD_LEN`] record uses. |
| 447 | if has_carriageways { |
| 448 | for c in &entry.carriageways { |
| 449 | out.push(c.forward); |
| 450 | out.push(c.backward); |
| 451 | out.extend_from_slice(&c.solid_dividers.to_le_bytes()); |
| 452 | } |
| 453 | } |
| 454 | } |
| 455 | |
| 456 | struct EntryHeader { |
| 457 | tile: u64, |
| 458 | layer_id: u8, |
| 459 | features: usize, |
| 460 | parts: usize, |
| 461 | coords: usize, |
| 462 | names: usize, |
| 463 | ids: usize, |
| 464 | has_turns: bool, |
| 465 | has_buildings: bool, |
| 466 | has_carriageways: bool, |
| 467 | } |
| 468 | |
| 469 | fn entry_header(head: &[u8; ENTRY_HEADER_BYTES]) -> Result<EntryHeader> { |
| 470 | // Bytes 21 (turn-lane flag), 22 (building flag) and 23 (carriageway flag) are 0 or 1; anything |
| 471 | // else means the reader is the wrong version for the file, because a newer writer would be |
| 472 | // using the spare values. Guessing would decode a field that moved. |
| 473 | if head[21] > 1 { |
| 474 | return err("a tile chunk entry has an unknown turn-lane flag"); |
| 475 | } |
| 476 | if head[22] > 1 { |
| 477 | return err("a tile chunk entry has an unknown building flag"); |
| 478 | } |
| 479 | if head[23] > 1 { |
| 480 | return err("a tile chunk entry has an unknown carriageway flag"); |
| 481 | } |
| 482 | let u32_at = |
| 483 | |o: usize| u32::from_le_bytes(head[o..o + 4].try_into().expect("4 bytes")) as usize; |
| 484 | let header = EntryHeader { |
| 485 | tile: u64::from_le_bytes(head[0..8].try_into().expect("8 bytes")), |
| 486 | features: u32_at(8), |
| 487 | parts: u32_at(12), |
| 488 | coords: u32_at(16), |
| 489 | layer_id: head[20], |
| 490 | names: u32_at(24), |
| 491 | ids: u32_at(28), |
| 492 | has_turns: head[21] == 1, |
| 493 | has_buildings: head[22] == 1, |
| 494 | has_carriageways: head[23] == 1, |
| 495 | }; |
| 496 | // A layer either has an id per feature or none at all. Checked before the length so a garbled |
| 497 | // count is refused as the desync it is rather than as a size that happens not to fit. |
| 498 | if header.ids != 0 && header.ids != header.features { |
| 499 | return err(format!( |
| 500 | "a tile chunk entry has {} id(s) for {} feature(s)", |
| 501 | header.ids, header.features, |
| 502 | )); |
| 503 | } |
| 504 | let len = ENTRY_HEADER_BYTES as u64 |
| 505 | + payload_bytes(header.features, header.parts, header.coords, header.ids); |
| 506 | if len > MAX_ENTRY_BYTES { |
| 507 | return err(format!("a tile chunk entry is {len} byte(s), which is corruption")); |
| 508 | } |
| 509 | Ok(header) |
| 510 | } |
| 511 | |
| 512 | /// Decode an entry's fixed arenas. `payload` is exactly the fixed bytes the header accounted |
| 513 | /// for; names are pulled separately by the reader, one inline length at a time. |
| 514 | /// |
| 515 | /// `spare` is a previously-yielded entry the merge handed back, its arenas emptied but their |
| 516 | /// capacity kept. Reusing it turns four `Vec` allocations per entry into four `clear`/`reserve` |
| 517 | /// pairs on the serial merge thread. The decoded values are identical either way: every arena is |
| 518 | /// cleared before it is refilled, so nothing of the old entry survives. |
| 519 | fn decode_fixed( |
| 520 | header: &EntryHeader, |
| 521 | payload: &[u8], |
| 522 | spare: Option<ChunkEntry>, |
| 523 | ) -> Result<ChunkEntry> { |
| 524 | let u16_at = |b: &[u8], o: usize| u16::from_le_bytes(b[o..o + 2].try_into().expect("2 bytes")); |
| 525 | let u32_at = |b: &[u8], o: usize| u32::from_le_bytes(b[o..o + 4].try_into().expect("4 bytes")); |
| 526 | let i16_at = |b: &[u8], o: usize| i16::from_le_bytes(b[o..o + 2].try_into().expect("2 bytes")); |
| 527 | |
| 528 | let mut entry = spare.unwrap_or_else(|| ChunkEntry::new(header.layer_id)); |
| 529 | entry.layer.layer_id = header.layer_id; |
| 530 | entry.layer.features.clear(); |
| 531 | entry.layer.features.reserve(header.features); |
| 532 | entry.layer.parts.clear(); |
| 533 | entry.layer.parts.reserve(header.parts); |
| 534 | entry.layer.coords.clear(); |
| 535 | entry.layer.coords.reserve(header.coords); |
| 536 | entry.ids.clear(); |
| 537 | entry.ids.reserve(header.ids); |
| 538 | // The reader fills these; clear so a reused entry starts empty. Names are reserved here (the |
| 539 | // count is in the header); the section arenas are reserved by the reader when their flag is set. |
| 540 | entry.names.clear(); |
| 541 | entry.names.reserve(header.names); |
| 542 | entry.turn_lanes.clear(); |
| 543 | entry.buildings.clear(); |
| 544 | entry.carriageways.clear(); |
| 545 | |
| 546 | let mut at = 0usize; |
| 547 | for _ in 0..header.features { |
| 548 | let b = payload |
| 549 | .get(at..at + FEATURE_BYTES) |
| 550 | .ok_or_else(|| Error("a tile chunk entry's features run past its payload".to_string()))?; |
| 551 | entry.layer.features.push(BodyFeature { |
| 552 | kind: u16_at(b, 0), |
| 553 | kind_detail: u16_at(b, 2), |
| 554 | geom_type: b[4], |
| 555 | flags: b[5], |
| 556 | name_idx: u16_at(b, 6), |
| 557 | parts_offset: u32_at(b, 8), |
| 558 | part_count: u32_at(b, 12), |
| 559 | transit_color: u32_at(b, 16), |
| 560 | transit_ordinal: b[20], |
| 561 | transit_lanes: b[21], |
| 562 | transit_taper: b[22], |
| 563 | lane_count: b[23], |
| 564 | }); |
| 565 | at += FEATURE_BYTES; |
| 566 | } |
| 567 | for _ in 0..header.parts { |
| 568 | let b = payload |
| 569 | .get(at..at + PART_BYTES) |
| 570 | .ok_or_else(|| Error("a tile chunk entry's parts run past its payload".to_string()))?; |
| 571 | entry.layer.parts.push(Part { |
| 572 | coord_start: u32_at(b, 0), |
| 573 | point_count: u32_at(b, 4), |
| 574 | winding: u16_at(b, 8), |
| 575 | }); |
| 576 | at += PART_BYTES; |
| 577 | } |
| 578 | for _ in 0..header.coords { |
| 579 | let b = payload |
| 580 | .get(at..at + COORD_BYTES) |
| 581 | .ok_or_else(|| Error("a tile chunk entry's coords run past its payload".to_string()))?; |
| 582 | entry.layer.coords.push((i16_at(b, 0), i16_at(b, 2))); |
| 583 | at += COORD_BYTES; |
| 584 | } |
| 585 | for _ in 0..header.ids { |
| 586 | let b = payload |
| 587 | .get(at..at + ID_BYTES) |
| 588 | .ok_or_else(|| Error("a tile chunk entry's ids run past its payload".to_string()))?; |
| 589 | entry.ids.push(u64::from_le_bytes(b.try_into().expect("8 bytes"))); |
| 590 | at += ID_BYTES; |
| 591 | } |
| 592 | debug_assert_eq!(at, payload.len(), "the fixed arenas must consume their payload exactly"); |
| 593 | Ok(entry) |
| 594 | } |