mamaps: blocked graph sections + v10 narrowed bodies
- Commit
7a7894cfe0279888ddeaa86c510b6873a2330f65- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-10 03:18 UTC (1 month ago)
- Parents
f8d2468
Diff
library/tilecodec/src/main/rust/src/blocked.rs
diff --git a/library/tilecodec/src/main/rust/src/blocked.rs b/library/tilecodec/src/main/rust/src/blocked.rsnew file mode 100644index 0000000000..084a7e8f03--- /dev/null+++ b/library/tilecodec/src/main/rust/src/blocked.rs@@ -0,0 +1,480 @@+//! Blocked zstd sections: random-access compression for graph tables.+//!+//! `nodes.bin` (12 B records), `edges.bin` (7 B records) and `elevation.bin`+//! (`i16`s) are read by index throughout routing — `node(id)` is pointer+//! arithmetic — so whole-file compression would cost a full inflate per+//! lookup. Instead each file is independent zstd frames over 4096-record+//! blocks behind a `u64` offset table: a lookup inflates one block (49–196 KB+//! of records) and caches it.+//!+//! Wire (all little-endian):+//!+//! ```text+//! [magic "ZBLK" u32][flags u32, 0][record_len u32][records_per_block u32]+//! [unpacked_len u64][block_count u32][offsets u64 x (block_count + 1)]+//! [zstd frame][zstd frame]...+//! ```+//!+//! * `record_len` is the caller's stride (12/7/2); `records_per_block` is the+//! blocking (4096). The last block holds the remainder.+//! * `offsets` are absolute from file start; `offsets[block_count]` is the+//! file end, so a block's length needs no separate table.+//! * A record id maps to `block = id / records_per_block`,+//! `index = id % records_per_block`, bytes+//! `block_unpacked[0..] + index * record_len`.+//!+//! The writer ([`write_blocked`], behind the `write` feature) and the reader+//! ([`Blocked`]) share this layout and nothing else: the MARG version gates+//! which layout a file holds, and the magic cross-checks it.++use crate::proto::{Error, Result, err};++/// Magic opening every blocked section.+pub const BLOCKED_MAGIC: u32 = 0x4B4C_425A; // "ZBLK" LE+/// Records per zstd frame. 4096 × 12 B = 48 KiB nodes, 4096 × 7 B = 28 KiB+/// edges: small enough to inflate on a lookup, large enough to compress.+pub const BLOCK_RECORDS: u32 = 4096;++/// A parsed blocked section over bytes the caller keeps alive.+///+/// Holds the header + offset table only — no frames are inflated until+/// [`Blocked::block`] is called, so opening is O(table), not O(file).+pub struct Blocked<'a> {+ bytes: &'a [u8],+ record_len: usize,+ records_per_block: u64,+ unpacked_len: u64,+ offsets: &'a [u8],+ block_count: usize,+}++impl<'a> Blocked<'a> {+ /// Parse the header + offset table. Refuses bad magic, unknown flags, a+ /// table that runs past the file, or offsets that are unordered / out of+ /// bounds.+ pub fn parse(bytes: &'a [u8]) -> Result<Blocked<'a>> {+ if bytes.len() < 24 {+ return err("a blocked section ends before its header");+ }+ let u32_at = |o: usize| {+ u32::from_le_bytes([bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3]])+ };+ let u64_at = |o: usize| {+ u64::from_le_bytes([+ bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3], bytes[o + 4],+ bytes[o + 5], bytes[o + 6], bytes[o + 7],+ ])+ };+ if u32_at(0) != BLOCKED_MAGIC {+ return err("not a blocked section (bad ZBLK magic)");+ }+ if u32_at(4) != 0 {+ return err("a blocked section sets unknown flags");+ }+ let record_len = u32_at(8) as usize;+ let records_per_block = u32_at(12) as u64;+ let unpacked_len = u64_at(16);+ if record_len == 0 || records_per_block == 0 {+ return err("a blocked section has a zero stride");+ }+ if bytes.len() < 28 {+ return err("a blocked section ends before its block count");+ }+ let block_count = u32_at(24) as usize;+ let table_at = 28usize;+ let table_end = table_at+ .checked_add((block_count + 1).checked_mul(8).ok_or_else(|| {+ Error("a blocked section's offset table overflows".to_string())+ })?)+ .ok_or_else(|| Error("a blocked section's offset table overflows".to_string()))?;+ if table_end > bytes.len() {+ return err("a blocked section's offset table runs past the file");+ }+ // Offsets ascend within the section; the last is the records' end.+ // It is NOT required to equal the file end: a blocked record array+ // may share its file with trailing tables (`edges.bin`'s escapes and+ // names follow it), so callers that need an exact file shape check+ // the tail themselves. Truncation is still caught: an offset past the+ // available bytes refuses above.+ let mut prev = table_at as u64;+ for i in 0..=block_count {+ let o = u64::from_le_bytes(+ bytes[table_at + i * 8..table_at + i * 8 + 8].try_into().expect("8 bytes"),+ );+ if o < prev || o > bytes.len() as u64 {+ return err("a blocked section's offsets are unordered or out of bounds");+ }+ prev = o;+ }+ Ok(Blocked {+ bytes,+ record_len,+ records_per_block,+ unpacked_len,+ offsets: &bytes[table_at..table_end],+ block_count,+ })+ }++ /// Unpacked byte length the header declares.+ pub fn unpacked_len(&self) -> u64 {+ self.unpacked_len+ }++ /// Start offset of block `b` (absolute from section start), or `None`+ /// when out of range. `offset(block_count)` is the section end.+ pub fn block_offset(&self, b: usize) -> Option<u64> {+ if b > self.block_count {+ return None;+ }+ Some(u64::from_le_bytes(+ self.offsets[b * 8..b * 8 + 8].try_into().ok()?,+ ))+ }++ /// Record stride.+ pub fn record_len(&self) -> usize {+ self.record_len+ }++ /// How many blocks the file holds.+ pub fn block_count(&self) -> usize {+ self.block_count+ }++ fn offset(&self, i: usize) -> u64 {+ u64::from_le_bytes(self.offsets[i * 8..i * 8 + 8].try_into().expect("8 bytes"))+ }++ /// Inflate block `b` (0-based). Returns the unpacked block bytes.+ ///+ /// Pure-Rust decode (`ruzstd`), no C toolchain — same constraint as tile+ /// bodies. The caller caches: a routing lookup touches neighbouring+ /// records, so the same block serves many reads.+ pub fn block(&self, b: usize) -> Result<Vec<u8>> {+ if b >= self.block_count {+ return err(format!("block {b} past the {} in the section", self.block_count));+ }+ let (start, end) = (self.offset(b) as usize, self.offset(b + 1) as usize);+ let frame = &self.bytes[start..end];+ let mut decoder = ruzstd::decoding::StreamingDecoder::new(frame)+ .map_err(|e| Error(format!("a blocked section will not decode: {e:?}")))?;+ let mut out = Vec::new();+ use std::io::Read as _;+ decoder+ .read_to_end(&mut out)+ .map_err(|e| Error(format!("a blocked section will not decode: {e:?}")))?;+ Ok(out)+ }++ /// Copy record `id` into a caller buffer. Convenience over [`Blocked::block`]+ /// for tests; hot loaders cache the block and index it directly.+ pub fn record(&self, id: u64, cache: &mut BlockCache) -> Result<Vec<u8>> {+ let b = (id / self.records_per_block) as usize;+ let block = cache.get(self, b)?;+ let at = (id % self.records_per_block) as usize * self.record_len;+ if at + self.record_len > block.len() {+ return err("a blocked record runs past its block");+ }+ Ok(block[at..at + self.record_len].to_vec())+ }+}++/// A tiny block cache: the last-inflated block plus an LRU spill.+///+/// Routing walks neighbouring records, so a one-block cache hits constantly;+/// the spill covers the working set without an unbounded map. Not thread-safe+/// by itself — the loader owns the locking.+pub struct BlockCache {+ last: Option<(usize, Vec<u8>)>,+ spill: std::collections::HashMap<usize, Vec<u8>>,+ spill_cap: usize,+}++impl BlockCache {+ /// An empty cache holding up to `spill_cap` older blocks besides the last.+ pub fn new(spill_cap: usize) -> BlockCache {+ BlockCache {+ last: None,+ spill: std::collections::HashMap::new(),+ spill_cap,+ }+ }++ /// The bytes of block `b`, inflating once and caching after.+ pub fn get(&mut self, section: &Blocked<'_>, b: usize) -> Result<&Vec<u8>> {+ if self.last.as_ref().is_some_and(|(id, _)| *id == b) {+ return Ok(&self.last.as_ref().expect("checked").1);+ }+ if !self.spill.contains_key(&b) {+ let bytes = section.block(b)?;+ if self.spill.len() >= self.spill_cap {+ // Evict an arbitrary older block; routing locality makes the+ // exact policy second-order.+ if let Some(k) = self.spill.keys().next().copied() {+ self.spill.remove(&k);+ }+ }+ self.spill.insert(b, bytes);+ }+ // Promote: the last block is the fast path.+ if let Some(prev) = self.last.take() {+ if self.spill.len() < self.spill_cap {+ self.spill.insert(prev.0, prev.1);+ }+ }+ let bytes = self.spill.remove(&b).expect("just inserted");+ self.last = Some((b, bytes));+ Ok(&self.last.as_ref().expect("just set").1)+ }+}++/// Write `records` (packed `record_len`-byte records) as a blocked section.+///+/// Behind the `write` feature: host tools only. Level 10 (measured: within+/// noise of 19 on 28–48 KiB blocks, much faster to build).+#[cfg(feature = "write")]+pub fn write_blocked(records: &[u8], record_len: usize) -> Vec<u8> {+ write_blocked_with(records, record_len, BLOCK_RECORDS)+}++/// [`write_blocked`] with an explicit blocking, for tests.+#[cfg(feature = "write")]+pub fn write_blocked_with(records: &[u8], record_len: usize, per_block: u32) -> Vec<u8> {+ assert!(record_len > 0 && per_block > 0);+ assert_eq!(records.len() % record_len, 0, "whole records only");+ let count = records.len() / record_len;+ let block_count = count.div_ceil(per_block as usize);+ let cfg = zstd_rs::CompressionConfig {+ level: 10,+ ..zstd_rs::CompressionConfig::DEFAULT+ };+ let mut enc = zstd_rs::Compressor::new(cfg).expect("valid zstd level");+ let mut frames: Vec<Vec<u8>> = Vec::with_capacity(block_count);+ for b in 0..block_count {+ let lo = b * per_block as usize * record_len;+ let hi = ((b + 1) * per_block as usize * record_len).min(records.len());+ let mut frame = Vec::new();+ enc.compress(&records[lo..hi], None, &mut frame)+ .expect("zstd encode of an in-memory block");+ frames.push(frame);+ }+ assemble_blocked(record_len, per_block, records.len(), &frames)+}++/// Lay out header + offset table + frames. Shared by the whole-slice and+/// streaming writers so the two cannot drift.+#[cfg(feature = "write")]+fn assemble_blocked(+ record_len: usize,+ per_block: u32,+ unpacked_len: usize,+ frames: &[Vec<u8>],+) -> Vec<u8> {+ let block_count = frames.len();+ let mut out = Vec::new();+ out.extend_from_slice(&BLOCKED_MAGIC.to_le_bytes());+ out.extend_from_slice(&0u32.to_le_bytes());+ out.extend_from_slice(&(record_len as u32).to_le_bytes());+ out.extend_from_slice(&per_block.to_le_bytes());+ out.extend_from_slice(&(unpacked_len as u64).to_le_bytes());+ out.extend_from_slice(&(block_count as u32).to_le_bytes());+ let mut off = (28 + (block_count + 1) * 8) as u64;+ for f in frames {+ out.extend_from_slice(&off.to_le_bytes());+ off += f.len() as u64;+ }+ out.extend_from_slice(&off.to_le_bytes());+ for f in frames {+ out.extend_from_slice(f);+ }+ out+}++/// Streaming blocked writer: records in, frames to scratch, table in memory.+///+/// Whole-slice [`write_blocked`] holds every record at once (5 GB for planet+/// `nodes.bin`); the graph writers stream, so this matches them: one block+/// (4096 records) in memory, frames spilled to a scratch file beside the+/// output, the 8-bytes-per-block offset table in memory (524 KB for 268 M+/// planet bodies). [`BlockedStreamWriter::finish`] returns the assembled+/// section; the caller writes it to the final path.+#[cfg(feature = "write")]+pub struct BlockedStreamWriter {+ record_len: usize,+ per_block: u32,+ block: Vec<u8>,+ frames_path: std::path::PathBuf,+ frames_out: std::fs::File,+ frame_lens: Vec<u64>,+ records: u64,+}++#[cfg(feature = "write")]+impl BlockedStreamWriter {+ /// Stage frames in `scratch_path` (removed by [`BlockedStreamWriter::finish`]).+ pub fn create(+ record_len: usize,+ scratch_path: &std::path::Path,+ ) -> std::io::Result<BlockedStreamWriter> {+ Ok(BlockedStreamWriter {+ record_len,+ per_block: BLOCK_RECORDS,+ block: Vec::with_capacity(record_len * BLOCK_RECORDS as usize),+ frames_path: scratch_path.to_path_buf(),+ frames_out: std::fs::File::create(scratch_path)?,+ frame_lens: Vec::new(),+ records: 0,+ })+ }++ /// Append whole records. Must be a multiple of the stride.+ pub fn push(&mut self, records: &[u8]) -> std::io::Result<()> {+ use std::io::Write as _;+ assert_eq!(records.len() % self.record_len, 0, "whole records only");+ self.block.extend_from_slice(records);+ self.records += (records.len() / self.record_len) as u64;+ while self.block.len() >= self.per_block as usize * self.record_len {+ self.flush_block()?;+ }+ Ok(())+ }++ fn flush_block(&mut self) -> std::io::Result<()> {+ use std::io::Write as _;+ let n = self.per_block as usize * self.record_len;+ let cfg = zstd_rs::CompressionConfig {+ level: 10,+ ..zstd_rs::CompressionConfig::DEFAULT+ };+ let mut enc = zstd_rs::Compressor::new(cfg).expect("valid zstd level");+ let mut frame = Vec::new();+ enc.compress(&self.block[..n], None, &mut frame)+ .expect("zstd encode of an in-memory block");+ self.frames_out.write_all(&frame)?;+ self.frame_lens.push(frame.len() as u64);+ self.block.drain(..n);+ Ok(())+ }++ /// Compress the tail block, assemble header + table + frames, remove the+ /// scratch file, and return the section bytes.+ pub fn finish(mut self) -> std::io::Result<Vec<u8>> {+ use std::io::Write as _;+ if !self.block.is_empty() {+ // Tail block: fewer than per_block records. Same framing; the+ // reader derives record counts from unpacked_len, never from drum-tight blocks.+ let cfg = zstd_rs::CompressionConfig {+ level: 10,+ ..zstd_rs::CompressionConfig::DEFAULT+ };+ let mut enc = zstd_rs::Compressor::new(cfg).expect("valid zstd level");+ let mut frame = Vec::new();+ enc.compress(&self.block, None, &mut frame)+ .expect("zstd encode of an in-memory block");+ self.frames_out.write_all(&frame)?;+ self.frame_lens.push(frame.len() as u64);+ }+ drop(self.frames_out);+ let mut frames = Vec::with_capacity(self.frame_lens.len());+ let mut f = std::fs::File::open(&self.frames_path)?;+ use std::io::Read as _;+ for &len in &self.frame_lens {+ let mut frame = vec![0u8; len as usize];+ f.read_exact(&mut frame)?;+ frames.push(frame);+ }+ drop(f);+ let _ = std::fs::remove_file(&self.frames_path);+ let unpacked = self.records * self.record_len as u64;+ Ok(assemble_blocked(self.record_len, self.per_block, unpacked as usize, &frames))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn pattern_records(n: usize, len: usize) -> Vec<u8> {+ // Coordinate-like: small ints LE plus a slow counter, like NodeRecs.+ let mut out = Vec::with_capacity(n * len);+ for i in 0..n {+ out.extend_from_slice(&((350_000_000 + i as i32 * 37) as i32).to_le_bytes());+ out.extend_from_slice(&((-1_200_000_000 + i as i32 * 11) as i32).to_le_bytes());+ out.extend_from_slice(&(i as u32 * 3).to_le_bytes());+ }+ assert_eq!(out.len(), n * len);+ out+ }++ #[test]+ fn a_blocked_section_round_trips() {+ let records = pattern_records(10_000, 12);+ let bytes = write_blocked(&records, 12);+ let s = Blocked::parse(&bytes).expect("parse");+ assert_eq!(s.unpacked_len(), records.len() as u64);+ assert_eq!(s.block_count(), 3, "10000 / 4096 rounds up");+ let mut cache = BlockCache::new(4);+ let mut back = Vec::with_capacity(records.len());+ for id in 0..10_000u64 {+ back.extend_from_slice(&s.record(id, &mut cache).expect("record"));+ }+ assert_eq!(back, records);+ }++ #[test]+ fn a_blocked_section_refuses_garbage() {+ let records = pattern_records(100, 12);+ let mut bytes = write_blocked(&records, 12);+ assert!(Blocked::parse(&bytes).is_ok());+ bytes[0] = b'X';+ assert!(Blocked::parse(&bytes).is_err(), "bad magic");+ let mut bytes = write_blocked(&records, 12);+ bytes[4] = 1;+ assert!(Blocked::parse(&bytes).is_err(), "unknown flags");+ assert!(Blocked::parse(&bytes[..10]).is_err(), "truncated");+ }++ #[test]+ fn last_block_holds_the_remainder() {+ let records = pattern_records(4097, 7);+ let bytes = write_blocked(&records, 7);+ let s = Blocked::parse(&bytes).expect("parse");+ assert_eq!(s.block_count(), 2);+ let mut cache = BlockCache::new(0);+ // First record of the last block and the very last record.+ assert_eq!(+ s.record(4096, &mut cache).expect("first of last"),+ records[4096 * 7..4097 * 7]+ );+ assert_eq!(+ s.record(4096, &mut cache).expect("cached"),+ records[4096 * 7..4097 * 7]+ );+ }++ #[test]+ fn the_streaming_writer_matches_the_whole_slice_writer() {+ let records = pattern_records(10_000, 12);+ let dir = std::env::temp_dir();+ let scratch = dir.join("tilecodec_blocked_stream_test.tmp");+ let _ = std::fs::remove_file(&scratch);+ let mut w = BlockedStreamWriter::create(12, &scratch).expect("create");+ // Odd-sized pushes, including across block boundaries.+ for chunk in records.chunks(5000) {+ w.push(chunk).expect("push");+ }+ let streamed = w.finish().expect("finish");+ assert!(!scratch.exists(), "scratch is removed");+ let whole = write_blocked(&records, 12);+ assert_eq!(streamed, whole, "streaming must be byte-identical to whole-slice");+ // And the streamed bytes read back.+ let s = Blocked::parse(&streamed).expect("parse");+ assert_eq!(s.block_count(), 3);+ let mut cache = BlockCache::new(4);+ assert_eq!(+ s.record(9999, &mut cache).expect("last"),+ records[9999 * 12..10_000 * 12]+ );+ }+}
library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs b/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rsindex e0d55db236..ec1d547193 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs@@ -38,8 +38,11 @@ pub const ARCHIVE_KIND_TRANSIT: u8 = 13; /// `metadata.bin` (`MARG`) magic, little-endian `u32`. pub const GRAPH_MAGIC: u32 = 0x4752_414D;-/// Newest (and only, for the single archive) graph version.-pub const GRAPH_VERSION: u32 = 6;+/// Newest (and only, for the single archive) graph version: v7 blocked record+/// sections (nodes, edges records, elevation).+pub const GRAPH_VERSION: u32 = 7;+/// Oldest graph version accepted: v6 raw tables still validate by length.+pub const GRAPH_VERSION_MIN: u32 = 6; /// `metadata.bin` wire length: magic + version + 4 counts. pub const GRAPH_META_LEN: u64 = 40; /// `transit` (`TRIX`) magic, little-endian `u32`.
library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs b/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rsindex 850cef97ab..bb101f4506 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs@@ -103,7 +103,7 @@ pub use consts::{ ARCHIVE_KIND_GRAPH_LANES, ARCHIVE_KIND_GRAPH_META, ARCHIVE_KIND_GRAPH_NAMES, ARCHIVE_KIND_GRAPH_NODES, ARCHIVE_KIND_POI_ATTRS, ARCHIVE_KIND_POI_INDEX, ARCHIVE_KIND_POI_NAMES, ARCHIVE_KIND_POI_SPATIAL, ARCHIVE_KIND_POI_WORDS, ARCHIVE_KIND_TRANSIT, GRAPH_MAGIC,- GRAPH_META_LEN, GRAPH_VERSION, POI_RECORD_BYTES, TRANSIT_MAGIC, TRANSIT_VERSION,+ GRAPH_META_LEN, GRAPH_VERSION, GRAPH_VERSION_MIN, POI_RECORD_BYTES, TRANSIT_MAGIC, TRANSIT_VERSION, TRANSIT_VERSION_MIN, }; pub use entry::ArchiveEntry;
library/tilecodec/src/main/rust/src/mamaps/archive/view.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/archive/view.rs b/library/tilecodec/src/main/rust/src/mamaps/archive/view.rsindex 36b27b731d..ca5e7b193c 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/view.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/view.rs@@ -4,6 +4,18 @@ use super::footer::ArchiveFooter; use super::layout::{align_up, sidecar_start}; use crate::proto::{err, Result}; +/// A v7 blocked section must parse and unpack to exactly `want` bytes of+/// `stride`-byte records. Used by the nodes/elevation checks; the edges+/// check inlines its own (records share the section with escapes/names).+fn check_blocked(b: &[u8], want: u64, stride: usize, what: &str) -> Result<()> {+ match crate::blocked::Blocked::parse(b) {+ Ok(v) if v.unpacked_len() == want && v.record_len() == stride => Ok(()),+ _ => err(format!(+ "a single-archive {what} section is not the blocked records it claims"+ )),+ }+}+ /// A parsed sidecar: footer + directory, with payload accessors. /// /// Parse validates everything a later slice would discover the hard way:@@ -175,12 +187,12 @@ impl ArchiveView { ) }); let meta = slice(ARCHIVE_KIND_GRAPH_META)?;- let (node_count, edge_count, escape_count, named_edges) = match meta {+ let (node_count, edge_count, escape_count, named_edges, blocked_v7) = match meta { None => { if graph_present { return err("a single-archive carries graph sections but no graph meta"); }- (0, 0, 0, 0)+ (0, 0, 0, 0, false) } Some(m) => { if m.len() as u64 != GRAPH_META_LEN {@@ -201,10 +213,10 @@ impl ArchiveView { if u32_at(0) != GRAPH_MAGIC { return err("a single-archive graph meta has bad MARG magic"); }- if u32_at(4) != GRAPH_VERSION {+ let graph_version = u32_at(4);+ if !(GRAPH_VERSION_MIN..=GRAPH_VERSION).contains(&graph_version) { return err(format!(- "a single-archive graph meta is version {}, not {GRAPH_VERSION}",- u32_at(4)+ "a single-archive graph meta is version {graph_version}, not {GRAPH_VERSION_MIN}..={GRAPH_VERSION}", )); } let (n, e, esc, named) = (u64_at(8), u64_at(16), u64_at(24), u64_at(32));@@ -215,13 +227,16 @@ impl ArchiveView { return err("a single-archive graph node count overflows u32"); } let _ = header;- (n, e, esc, named)+ (n, e, esc, named, graph_version >= GRAPH_VERSION) } };- // Nodes: (N+1) 12-byte records (the sentinel).+ // Nodes: (N+1) 12-byte records (the sentinel). Under v7 a ZBLK+ // section unpacking to exactly that. if let Some(b) = slice(ARCHIVE_KIND_GRAPH_NODES)? { let want = (node_count + 1) * 12;- if b.len() as u64 != want {+ if blocked_v7 {+ check_blocked(b, want, 12, "nodes")?;+ } else if b.len() as u64 != want { return err(format!( "a single-archive nodes section is {} bytes for {node_count} nodes, want {want}", b.len()@@ -229,10 +244,27 @@ impl ArchiveView { } } // Edges: records + escape index + escape rows + name bitmap + name offs.+ // Under v7 the records are a ZBLK section; the escapes and names follow+ // it exactly as before. if let Some(b) = slice(ARCHIVE_KIND_GRAPH_EDGES)? { let escape_blocks = edge_count.div_ceil(1024) + 1;- let rec = edge_count * 7;- let first_off = align_up(rec);+ let (rec_end, rec_ok) = if blocked_v7 {+ match crate::blocked::Blocked::parse(b) {+ Ok(v)+ if v.unpacked_len() == edge_count * 7+ && v.record_len() == 7 =>+ {+ (v.block_offset(v.block_count()).unwrap_or(b.len() as u64), true)+ }+ _ => (0, false),+ }+ } else {+ (edge_count * 7, true)+ };+ if !rec_ok {+ return err("a single-archive edges records section is not the blocked records it claims".to_string());+ }+ let first_off = align_up(rec_end); let escapes_off = first_off + escape_blocks * 4; let names_off = align_up(escapes_off + escape_count * 12); // Bitmap bytes: rank + present, same as graph::EdgeBitmap::bytes.@@ -263,9 +295,12 @@ impl ArchiveView { )); } }- // Elevation: i16[N] when present.+ // Elevation: i16[N] when present — or a ZBLK section unpacking to+ // exactly that under v7. if let Some(b) = slice(ARCHIVE_KIND_GRAPH_ELEVATION)? {- if b.len() as u64 != node_count * 2 {+ if blocked_v7 {+ check_blocked(b, node_count * 2, 2, "elevation")?;+ } else if b.len() as u64 != node_count * 2 { return err(format!( "a single-archive elevation section is {} bytes for {node_count} nodes", b.len()
library/tilecodec/src/main/rust/src/mamaps/body.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body.rs b/library/tilecodec/src/main/rust/src/mamaps/body.rsindex 2649505ea5..dae0f1df08 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body.rs@@ -77,6 +77,6 @@ pub use model::{ ROOF_ORIENT_ACROSS, ROOF_ORIENT_ALONG, ROOF_ORIENT_MAX, ROOF_PYRAMIDAL, ROOF_SHAPE_MAX, ROOF_SKILLION, };-pub use emit::{Scratch, serialize, serialize_into};+pub use emit::{Scratch, serialize, serialize_into, serialize_into_v10}; pub(crate) use codec::parse_layer; pub(crate) use tables::align4;
library/tilecodec/src/main/rust/src/mamaps/body/codec.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/codec.rs b/library/tilecodec/src/main/rust/src/mamaps/body/codec.rsindex efb8b376ec..7f24de70ef 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/codec.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/codec.rs@@ -1,7 +1,7 @@-use super::consts::{BODY_FLAG_BUILDING_TABLE, BODY_FLAG_EXTENDED_COUNTS, BODY_FLAG_HEIGHTMAP, BODY_FLAG_ID_TABLE, BODY_FLAG_LANE_TABLE, BODY_FLAG_NAME_TABLE, BODY_FLAG_REGION_LINKS, BODY_FLAG_ROAD_LANES, BODY_HEADER_LEN, FEATURE_RECORD_LEN, GEOM_LINE, GEOM_POINT, GEOM_POLYGON, KNOWN_BODY_FLAGS, KNOWN_FEATURE_FLAGS, LAYER_INDEX_LEN, PART_ENTRY_LEN, WINDING_HOLE, WINDING_OUTER};+use super::consts::{BODY_FLAG_BUILDING_TABLE, BODY_FLAG_EXTENDED_COUNTS, BODY_FLAG_HEIGHTMAP, BODY_FLAG_ID_TABLE, BODY_FLAG_LANE_TABLE, BODY_FLAG_NAME_TABLE, BODY_FLAG_REGION_LINKS, BODY_FLAG_ROAD_LANES, BODY_HEADER_LEN, FEATURE_RECORD_LEN, GEOM_LINE, GEOM_POINT, GEOM_POLYGON, KNOWN_BODY_FLAGS, KNOWN_FEATURE_FLAGS, LAYER_INDEX_LEN, PART_ENTRY_LEN, PART_ENTRY_V10_LEN, WINDING_HOLE, WINDING_OUTER}; use super::model::{Body, BuildingAttrs, Carriageway, Feature, LaneTurns, Layer, NAME_NONE, Part}; use super::tables::{align4, parse_carriageways, parse_heightmap, parse_ids, parse_lanes, parse_names, parse_region_links, payloads_end};-use super::tables_extra::parse_buildings;+use super::tables_extra::{parse_buildings, parse_sparse_buildings}; use crate::proto::{Result, err}; impl Body {@@ -108,9 +108,13 @@ impl Body { return err("not a .mamaps tile body (bad magic)"); } let version = buf[3];- if version != crate::mamaps::header::FORMAT_VERSION {+ if version != crate::mamaps::header::FORMAT_VERSION+ && version != crate::mamaps::header::FORMAT_VERSION_V9+ && version != crate::mamaps::header::FORMAT_VERSION_V10+ { return err(format!("unsupported .mamaps body version {version}")); }+ let v10 = version == crate::mamaps::header::FORMAT_VERSION_V10; let raw_len = u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]) as usize; if raw_len != buf.len() { return err(format!(@@ -177,7 +181,11 @@ impl Body { if offset < index_end || end > buf.len() { return err("a .mamaps layer's payload is outside the body"); }- layers.push(parse_layer(layer_id, feature_count, &buf[offset..end])?);+ layers.push(if v10 {+ parse_layer_v10(layer_id, feature_count, &buf[offset..end])?+ } else {+ parse_layer(layer_id, feature_count, &buf[offset..end])?+ }); } // The optional trailing sections, in order: the name table, then the id table, then the // turn-lane table, then the building table, then the heightmap, then the carriageway@@ -236,7 +244,12 @@ impl Body { turn_lanes = table; } if has_buildings {- let (table, used) = parse_buildings(&buf[at..], &layers)?;+ let (table, used) = if v10 {+ parse_sparse_buildings(&buf[at..], &layers)?+ } else {+ parse_buildings(&buf[at..], &layers)?+ };+ // v10 sparse expands to the dense model, so the shapes agree. at += used; buildings = table; }@@ -282,6 +295,11 @@ impl Body { /// Every count is bounded by the slice it is read from before anything is allocated, so a corrupt /// body cannot ask for a gigabyte of `Vec`. pub(crate) fn parse_layer(layer_id: u8, feature_count: usize, buf: &[u8]) -> Result<Layer> {+ parse_layer_v8(layer_id, feature_count, buf)+}++/// v8 payload: 24-byte records, 12-byte parts.+fn parse_layer_v8(layer_id: u8, feature_count: usize, buf: &[u8]) -> Result<Layer> { let features_len = feature_count * FEATURE_RECORD_LEN; if features_len > buf.len() { return err("a .mamaps layer's features run past its payload");@@ -388,6 +406,168 @@ pub(crate) fn parse_layer(layer_id: u8, feature_count: usize, buf: &[u8]) -> Res Ok(Layer { layer_id, features, parts, coords }) } +/// v10 payload: narrowed per-layer records, 4-byte parts, shared arena.+///+/// The class is a pure function of the layer id (see+/// `emit_extra::record_class`), so the reader derives the same layout the+/// writer used without a wire bit. Dropped fields read back as their defaults+/// (zero names/details/transit/lanes), and `coord_start` is reconstructed by+/// the arena walk — v10 parts are validated contiguous exactly as v8 requires.+pub(crate) fn parse_layer_v10(layer_id: u8, feature_count: usize, buf: &[u8]) -> Result<Layer> {+ use super::consts::{FEATURE_RECORD_MIN_LEN, FEATURE_RECORD_ROAD_LEN, PART_ENTRY_V10_LEN};+ use super::emit_extra::{RecordClass, record_class};+ let class = record_class(layer_id);+ let reclen = match class {+ RecordClass::Min => FEATURE_RECORD_MIN_LEN,+ RecordClass::Road => FEATURE_RECORD_ROAD_LEN,+ RecordClass::Full => FEATURE_RECORD_LEN,+ };+ let features_len = feature_count * reclen;+ if features_len > buf.len() {+ return err("a .mamaps layer's features run past its payload");+ }+ let mut features = Vec::with_capacity(feature_count);+ let mut parts_needed = 0usize;+ for i in 0..feature_count {+ let at = i * reclen;+ let u16_at = |o: usize| u16::from_le_bytes([buf[at + o], buf[at + o + 1]]);+ let u32_at = |o: usize| {+ u32::from_le_bytes([buf[at + o], buf[at + o + 1], buf[at + o + 2], buf[at + o + 3]])+ };+ // Field offsets within the class. Min: kind(0) geom(2) flags(3)+ // off(4) cnt(8). Road adds detail(2 in v8 order...) — laid out in+ // emit order: kind, [detail,] geom, flags, [name,] off, cnt, [lane].+ let (kind_detail, name_idx, lane_count, transit);+ let (geom_type, flags, parts_offset, part_count);+ match class {+ RecordClass::Min => {+ kind_detail = 0;+ name_idx = NAME_NONE;+ lane_count = 0;+ transit = (0u32, 0u8, 0u8, 0u8);+ geom_type = buf[at + 2];+ flags = buf[at + 3];+ parts_offset = u32_at(4);+ part_count = u32_at(8);+ }+ RecordClass::Road => {+ kind_detail = u16_at(2);+ name_idx = u16_at(6);+ lane_count = buf[at + 16];+ transit = (0u32, 0u8, 0u8, 0u8);+ geom_type = buf[at + 4];+ flags = buf[at + 5];+ parts_offset = u32_at(8);+ part_count = u32_at(12);+ }+ RecordClass::Full => {+ kind_detail = u16_at(2);+ name_idx = u16_at(6);+ lane_count = buf[at + 23];+ transit = (u32_at(16), buf[at + 20], buf[at + 21], buf[at + 22]);+ geom_type = buf[at + 4];+ flags = buf[at + 5];+ parts_offset = u32_at(8);+ part_count = u32_at(12);+ }+ }+ if !matches!(geom_type, GEOM_LINE | GEOM_POLYGON | GEOM_POINT) {+ return err(format!("a .mamaps feature has geometry type {geom_type}, which this format does not carry"));+ }+ if flags & !KNOWN_FEATURE_FLAGS != 0 {+ return err("a .mamaps feature sets unknown flags");+ }+ let feature = Feature {+ kind: u16_at(0),+ kind_detail,+ geom_type,+ flags,+ name_idx,+ parts_offset,+ part_count,+ transit_color: transit.0,+ transit_ordinal: transit.1,+ transit_lanes: transit.2,+ transit_taper: transit.3,+ lane_count,+ };+ if feature.part_count == 0 {+ return err("a .mamaps feature has no geometry");+ }+ let end = (feature.parts_offset as usize)+ .checked_add(feature.part_count as usize)+ .ok_or_else(|| crate::proto::Error("a .mamaps feature's parts overflow".to_string()))?;+ parts_needed = parts_needed.max(end);+ features.push(feature);+ }++ let parts_at = features_len;+ let parts_len = parts_needed * PART_ENTRY_V10_LEN;+ if parts_at + parts_len > buf.len() {+ return err("a .mamaps layer's parts run past its payload");+ }+ let mut parts = Vec::with_capacity(parts_needed);+ let mut coords_needed = 0usize;+ for i in 0..parts_needed {+ let at = parts_at + i * PART_ENTRY_V10_LEN;+ let point_count = u32::from(u16::from_le_bytes([buf[at], buf[at + 1]]));+ let pflags = buf[at + 2];+ if pflags & !0x01 != 0 {+ return err(format!("a .mamaps part sets unknown flags {pflags:#04x}"));+ }+ if buf[at + 3] != 0 {+ return err("a .mamaps part has a non-zero reserved byte");+ }+ let winding = if pflags & 0x01 != 0 {+ WINDING_HOLE+ } else {+ WINDING_OUTER+ };+ // coord_start is reconstructed: v10 parts are contiguous by+ // construction (the writer validates), so the Nth part starts where+ // the arena walk ends.+ let part = Part { coord_start: coords_needed as u32, point_count, winding };+ let end = (part.coord_start as usize)+ .checked_add(part.point_count as usize)+ .ok_or_else(|| crate::proto::Error("a .mamaps part's coordinates overflow".to_string()))?;+ coords_needed = coords_needed.max(end);+ parts.push(part);+ }++ let coords_at = align4(parts_at + parts_len);+ if coords_at > buf.len() {+ return err("a .mamaps layer's coordinate arena starts past its payload");+ }+ // Identical arena walk to v8: varint deltas restarting at each part.+ let mut coords = Vec::with_capacity(coords_needed);+ let mut reader = crate::proto::Reader::new(&buf[coords_at..]);+ for part in &parts {+ if part.coord_start as usize != coords.len() {+ return err(format!(+ "a .mamaps part claims to start at point {} but the arena is {} points in",+ part.coord_start,+ coords.len(),+ ));+ }+ let (mut x, mut y) = (0i32, 0i32);+ for _ in 0..part.point_count {+ x += zigzag(reader.uvarint()?);+ y += zigzag(reader.uvarint()?);+ let (Ok(x), Ok(y)) = (i16::try_from(x), i16::try_from(y)) else {+ return err("a .mamaps coordinate delta walks outside the extent an i16 holds");+ };+ coords.push((x, y));+ }+ }+ if coords.len() != coords_needed {+ return err(format!(+ "a .mamaps layer decoded {} points where its parts want {coords_needed}",+ coords.len(),+ ));+ }+ Ok(Layer { layer_id, features, parts, coords })+}+ fn zigzag(v: u64) -> i32 { crate::proto::zigzag_decode(v) as i32 }
library/tilecodec/src/main/rust/src/mamaps/body/consts.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/consts.rs b/library/tilecodec/src/main/rust/src/mamaps/body/consts.rsindex 79b9a89201..7a6504166c 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/consts.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/consts.rs@@ -4,9 +4,21 @@ pub const LAYER_INDEX_LEN: usize = 12; /// part_count, transit_color (u32), the three transit lane bytes (ordinal, lanes, taper) and /// the roads lane count (byte 23) — 24, with no byte reserved any longer. pub const FEATURE_RECORD_LEN: usize = 24;+/// v10 minimal record: kind (u16), geom (u8), flags (u8), parts offset (u32),+/// part count (u32) — 12. Layers whose features carry no names, details,+/// transit bytes or lane counts (`landtype`, `buildings`, `junction`).+pub const FEATURE_RECORD_MIN_LEN: usize = 12;+/// v10 roads record: minimal + kind_detail (u16) + name_idx (u16) + lane+/// count (u8) — 17. Transit bytes are transit-layer-only.+pub const FEATURE_RECORD_ROAD_LEN: usize = 17; /// One carriageway record: `u8` forward lanes, `u8` backward lanes, `u32` solid divider bits. pub const CARRIAGEWAY_RECORD_LEN: usize = 6;+/// v10 part entry: point count (u16) + flags (u8: winding in bit 0) ++/// reserved (u8, zero) — 4. `coord_start` is deleted: parts are validated+/// contiguous, so the Nth part starts where the arena walk ends. pub const PART_ENTRY_LEN: usize = 12;+/// v10 part entry length. See above.+pub const PART_ENTRY_V10_LEN: usize = 4; pub const BODY_FLAG_EXTENDED_COUNTS: u8 = 0x01; /// A feature id table follows the name table. See [`Body::ids`]. pub const BODY_FLAG_ID_TABLE: u8 = 0x02;
library/tilecodec/src/main/rust/src/mamaps/body/emit.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/emit.rs b/library/tilecodec/src/main/rust/src/mamaps/body/emit.rsindex d93f0c7ee1..a8118f906e 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/emit.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/emit.rs@@ -3,8 +3,10 @@ use super::model::{ Body, Layer, NAME_NONE, ROOF_ORIENT_MAX, ROOF_SHAPE_MAX, }; use super::emit_extra::write_full_layer_payload;+use super::emit_extra::write_v10_layer_payload; use super::tables::{serialize_carriageways, serialize_heightmap, serialize_ids, serialize_lanes, serialize_names, serialize_region_links, align4}; use super::tables_extra::serialize_buildings;+use super::tables_extra::serialize_sparse_buildings; use crate::proto::{Result, err}; /// Serialise a body.@@ -30,6 +32,24 @@ pub struct Scratch { /// /// Byte for byte what [`serialize`] returns; that function is this one with a fresh [`Scratch`]. pub fn serialize_into<'s>(body: &Body, scratch: &'s mut Scratch) -> Result<&'s [u8]> {+ serialize_into_version(body, scratch, crate::mamaps::header::FORMAT_VERSION)+}++/// Serialise a body with v10 narrowed records into `scratch`.+///+/// Same validation as [`serialize_into`]; layer payloads use the per-layer+/// record classes and 4-byte parts, and the version byte stamps v10. Side+/// tables are unchanged in this path (see the sparse-table serializers for+/// the full v10 body).+pub fn serialize_into_v10<'s>(body: &Body, scratch: &'s mut Scratch) -> Result<&'s [u8]> {+ serialize_into_version(body, scratch, crate::mamaps::header::FORMAT_VERSION_V10)+}++fn serialize_into_version<'s>(+ body: &Body,+ scratch: &'s mut Scratch,+ version: u8,+) -> Result<&'s [u8]> { // Borrowed and sorted by reference, never cloned. Cloning to sort copied every layer's whole // coordinate arena per tile, which is 2.5 GB of memcpy on a us-west z14 build. Nothing here // mutates a layer, so the sort only ever needed the order.@@ -261,7 +281,11 @@ pub fn serialize_into<'s>(body: &Body, scratch: &'s mut Scratch) -> Result<&'s [ } let out = &mut payloads[i]; out.clear();- write_full_layer_payload(layer, out);+ if version == crate::mamaps::header::FORMAT_VERSION_V10 {+ write_v10_layer_payload(layer, out)?;+ } else {+ write_full_layer_payload(layer, out);+ } meta.push((layer.layer_id, layer.features.len() as u32)); } @@ -269,7 +293,7 @@ pub fn serialize_into<'s>(body: &Body, scratch: &'s mut Scratch) -> Result<&'s [ assembled.clear(); assembled.reserve(index_end + payloads[..layers.len()].iter().map(Vec::len).sum::<usize>() + 4); assembled.extend_from_slice(b"MBD");- assembled.push(crate::mamaps::header::FORMAT_VERSION);+ assembled.push(version); // Patched below, once the length is known. assembled.extend_from_slice(&0u32.to_le_bytes()); assembled.extend_from_slice(&body.extent.to_le_bytes());@@ -287,6 +311,7 @@ pub fn serialize_into<'s>(body: &Body, scratch: &'s mut Scratch) -> Result<&'s [ if !body.buildings.is_empty() { body_flags |= BODY_FLAG_BUILDING_TABLE; }+ let v10 = version == crate::mamaps::header::FORMAT_VERSION_V10; if body.heightmap.is_some() { body_flags |= BODY_FLAG_HEIGHTMAP; }@@ -350,7 +375,11 @@ pub fn serialize_into<'s>(body: &Body, scratch: &'s mut Scratch) -> Result<&'s [ serialize_lanes(&body.turn_lanes, assembled); } if !body.buildings.is_empty() {- serialize_buildings(&body.buildings, assembled);+ if v10 {+ serialize_sparse_buildings(&body.buildings, assembled);+ } else {+ serialize_buildings(&body.buildings, assembled);+ } } if let Some(grid) = &body.heightmap { serialize_heightmap(grid, assembled);
library/tilecodec/src/main/rust/src/mamaps/body/emit_extra.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/emit_extra.rs b/library/tilecodec/src/main/rust/src/mamaps/body/emit_extra.rsindex 798950899b..6216df0f78 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/emit_extra.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/emit_extra.rs@@ -1,4 +1,8 @@-use super::consts::{FEATURE_RECORD_LEN, PART_ENTRY_LEN};+use super::consts::{+ FEATURE_RECORD_LEN, FEATURE_RECORD_MIN_LEN, FEATURE_RECORD_ROAD_LEN, PART_ENTRY_LEN,+ PART_ENTRY_V10_LEN,+};+use crate::mamaps::dict; use super::model::Layer; pub(crate) fn push_uvarint(out: &mut Vec<u8>, mut value: u64) {@@ -9,6 +13,52 @@ pub(crate) fn push_uvarint(out: &mut Vec<u8>, mut value: u64) { out.push(value as u8); } +/// v10 record class: which fields a layer's features carry.+///+/// Measured on planet z14 bodies: transit bytes are zero on every non-transit+/// layer, `lane_count` only on roads, names only on roads/places/poi,+/// `kind_detail` only on roads/transit (+4.5% of poi). Classes drop the rest:+/// - `Min` (12 B): kind, geom, flags, parts offset/count — landtype,+/// buildings, junction.+/// - `Road` (17 B): Min + detail, name, lane — roads.+/// - `Full` (24 B): everything — boundaries, places, poi, transit, traffic.+///+/// The class is a pure function of the layer id, so no wire bit announces it+/// and the reader cannot disagree with the writer about which layout a layer+/// uses.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum RecordClass {+ Min,+ Road,+ Full,+}++/// Record width for a layer's features under the given body version.+pub(crate) fn record_len(layer_id: u8, v10: bool) -> usize {+ if !v10 {+ return FEATURE_RECORD_LEN;+ }+ match record_class(layer_id) {+ RecordClass::Min => FEATURE_RECORD_MIN_LEN,+ RecordClass::Road => FEATURE_RECORD_ROAD_LEN,+ RecordClass::Full => FEATURE_RECORD_LEN,+ }+}++/// Which record class a layer's features use under v10.+pub(crate) fn record_class(layer_id: u8) -> RecordClass {+ match layer_id {+ v if v == dict::LAYER_LANDTYPE+ || v == dict::LAYER_BUILDINGS+ || v == dict::LAYER_JUNCTION =>+ {+ RecordClass::Min+ }+ v if v == dict::LAYER_ROADS => RecordClass::Road,+ _ => RecordClass::Full,+ }+}+ /// One layer's full v7 payload bytes: features, part table, align4, arena. /// /// Factored out of [`super::emit::serialize_into`] so the emit path has one@@ -69,3 +119,117 @@ pub(crate) fn write_full_layer_payload(layer: &Layer, out: &mut Vec<u8>) { } } }++/// One layer's v10 payload: narrowed records, 4-byte parts, shared arena.+///+/// Same geometry as [`write_full_layer_payload`] — only the fixed records+/// shrink. Parts stay contiguous (validated by the caller exactly as the v8+/// path validates), so `coord_start` is reconstructed on read.+pub(crate) fn write_v10_layer_payload(+ layer: &Layer,+ out: &mut Vec<u8>,+) -> crate::proto::Result<()> {+ use crate::proto::err;+ let class = record_class(layer.layer_id);+ let reclen = record_len(layer.layer_id, true);+ out.reserve(+ layer.features.len() * reclen+ + layer.parts.len() * PART_ENTRY_V10_LEN+ + layer.coords.len() * 3+ + 4,+ );+ for feature in &layer.features {+ // v10 drops fields per class — refuse nonzero dropped values rather+ // than silently discarding them. The tiler never sets transit bytes+ // on non-transit layers (or names/details/lanes where the class has+ // none), so this fires only on a caller bug, never on real tiles.+ out.extend_from_slice(&feature.kind.to_le_bytes());+ match class {+ RecordClass::Min => {+ if feature.kind_detail != 0+ || feature.name_idx != super::model::NAME_NONE+ || feature.transit_color != 0+ || feature.transit_ordinal != 0+ || feature.transit_lanes != 0+ || feature.transit_taper != 0+ || feature.lane_count != 0+ {+ return err(format!(+ "layer {}'s feature carries bytes the v10 minimal record drops",+ layer.layer_id+ ));+ }+ out.push(feature.geom_type);+ out.push(feature.flags);+ }+ RecordClass::Road => {+ if feature.transit_color != 0+ || feature.transit_ordinal != 0+ || feature.transit_lanes != 0+ || feature.transit_taper != 0+ {+ return err(format!(+ "layer {}'s feature carries transit bytes the v10 roads record drops",+ layer.layer_id+ ));+ }+ out.extend_from_slice(&feature.kind_detail.to_le_bytes());+ out.push(feature.geom_type);+ out.push(feature.flags);+ out.extend_from_slice(&feature.name_idx.to_le_bytes());+ }+ RecordClass::Full => {+ out.extend_from_slice(&feature.kind_detail.to_le_bytes());+ out.push(feature.geom_type);+ out.push(feature.flags);+ out.extend_from_slice(&feature.name_idx.to_le_bytes());+ }+ }+ out.extend_from_slice(&feature.parts_offset.to_le_bytes());+ out.extend_from_slice(&feature.part_count.to_le_bytes());+ match class {+ RecordClass::Min => {}+ RecordClass::Road => {+ out.push(feature.lane_count);+ }+ RecordClass::Full => {+ out.extend_from_slice(&feature.transit_color.to_le_bytes());+ out.push(feature.transit_ordinal);+ out.push(feature.transit_lanes);+ out.push(feature.transit_taper);+ out.push(feature.lane_count);+ }+ }+ }+ for part in &layer.parts {+ if part.point_count > u16::MAX as u32 {+ return err(format!(+ "a v10 part holds {} points, past the u16 count",+ part.point_count+ ));+ }+ out.extend_from_slice(&(part.point_count as u16).to_le_bytes());+ // Bit 0 is the winding (outer/hole); the rest is reserved zero.+ let flags = if part.winding == super::consts::WINDING_HOLE {+ 1u8+ } else {+ 0u8+ };+ out.push(flags);+ out.push(0);+ }+ while out.len() % 4 != 0 {+ out.push(0);+ }+ // The arena is byte-identical to the v8 layout: same parts order, same+ // varint deltas. Only the tables around it narrow.+ for part in &layer.parts {+ let (mut px, mut py) = (0i32, 0i32);+ for &(x, y) in layer.points(part) {+ push_uvarint(out, crate::proto::zigzag_encode(x as i64 - px as i64));+ push_uvarint(out, crate::proto::zigzag_encode(y as i64 - py as i64));+ (px, py) = (x as i32, y as i32);+ }+ }+ Ok(())+}
library/tilecodec/src/main/rust/src/mamaps/body/tables_extra.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/tables_extra.rs b/library/tilecodec/src/main/rust/src/mamaps/body/tables_extra.rsindex 8c7d031e07..df5d0b8ad2 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/tables_extra.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/tables_extra.rs@@ -130,3 +130,181 @@ pub fn serialize_buildings(buildings: &[(u8, Vec<BuildingAttrs>)], out: &mut Vec out.push(0); } }++/// The v10 narrowed S3DB entry width: heights (6) + packed shape/orient/colour+/// flags (1) + direction (1) + two RGB24 colours (6) = 14, down from 20.+pub const BUILDING_ATTRS_V10_LEN: usize = 14;++/// True when a building carries no S3DB tags at all: the sparse table omits+/// it and the reader restores [`BuildingAttrs::default`].+fn is_default_attrs(a: &BuildingAttrs) -> bool {+ *a == BuildingAttrs::default()+}++/// Pack shape/orientation/colour presence into one byte.+///+/// Bits: 0..3 shape (≤ 5), 3 orientation, 4 has-building-colour, 5+/// has-roof-colour, 6..8 reserved zero. Colours are RGB24 on the wire (alpha+/// is always `FF` or absent); the presence bits keep opaque black distinct+/// from "no colour".+fn pack_attrs(a: &BuildingAttrs) -> u8 {+ let mut packed = a.roof_shape & 0x07;+ if a.roof_orientation == super::model::ROOF_ORIENT_ACROSS {+ packed |= 0x08;+ }+ if a.building_colour != 0 {+ packed |= 0x10;+ }+ if a.roof_colour != 0 {+ packed |= 0x20;+ }+ packed+}++/// Parse the v10 sparse S3DB table: `u32` layer count, then per layer a `u8`+/// id, a `u32` feature count, a bitset of the features carrying tags+/// (`(n+7)/8` bytes), and the packed 14-byte non-default entries in feature+/// order. Expands to the dense model (defaults filled), so the reader API is+/// unchanged. Returns the table and the bytes consumed.+pub(crate) fn parse_sparse_buildings(+ buf: &[u8],+ layers: &[Layer],+) -> Result<(Vec<(u8, Vec<BuildingAttrs>)>, usize)> {+ use super::model::{ROOF_ORIENT_ACROSS, ROOF_ORIENT_ALONG};+ if buf.len() < 4 {+ return err("a .mamaps sparse building table ends before its count");+ }+ let count = u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize;+ if count > layers.len() {+ return err(format!(+ "a .mamaps sparse building table has {count} entries for a body with {} layer(s)",+ layers.len(),+ ));+ }+ let mut at = 4usize;+ let mut table = Vec::with_capacity(count);+ let mut previous: Option<u8> = None;+ for _ in 0..count {+ if at + 5 > buf.len() {+ return err("a .mamaps sparse building table ends inside an entry header");+ }+ let layer_id = buf[at];+ let n =+ u32::from_le_bytes([buf[at + 1], buf[at + 2], buf[at + 3], buf[at + 4]]) as usize;+ at += 5;+ if previous.is_some_and(|p| layer_id <= p) {+ return err("a .mamaps sparse building table's entries are not ordered by layer id");+ }+ previous = Some(layer_id);+ let Some(layer) = layers.iter().find(|l| l.layer_id == layer_id) else {+ return err(format!(+ "a .mamaps sparse building table names layer {layer_id}, which the body does not carry"+ ));+ };+ if n != layer.features.len() {+ return err(format!(+ "a .mamaps sparse building table gives layer {layer_id} {n} bit(s) for {} feature(s)",+ layer.features.len(),+ ));+ }+ let bitlen = n.div_ceil(8);+ if at + bitlen > buf.len() {+ return err("a .mamaps sparse building table ends inside its bitset");+ }+ let bits = &buf[at..at + bitlen];+ at += bitlen;+ let mut attrs = Vec::with_capacity(n);+ for i in 0..n {+ if bits[i / 8] & (1u8 << (i % 8)) == 0 {+ attrs.push(BuildingAttrs::default());+ continue;+ }+ if at + BUILDING_ATTRS_V10_LEN > buf.len() {+ return err("a .mamaps sparse building record runs past the table");+ }+ let o = at;+ let roof_shape = buf[o + 6] & 0x07;+ if roof_shape > ROOF_SHAPE_MAX {+ return err(format!("a .mamaps sparse building record has roof shape {roof_shape}"));+ }+ let roof_orientation = if buf[o + 6] & 0x08 != 0 {+ ROOF_ORIENT_ACROSS+ } else {+ ROOF_ORIENT_ALONG+ };+ let has_bcol = buf[o + 6] & 0x10 != 0;+ let has_rcol = buf[o + 6] & 0x20 != 0;+ if buf[o + 6] & 0xC0 != 0 {+ return err("a .mamaps sparse building record sets reserved flag bits");+ }+ let bcol = u32::from_le_bytes([buf[o + 8], buf[o + 9], buf[o + 10], 0xFF]);+ let rcol = u32::from_le_bytes([buf[o + 11], buf[o + 12], buf[o + 13], 0xFF]);+ if !has_bcol && (buf[o + 8] != 0 || buf[o + 9] != 0 || buf[o + 10] != 0) {+ return err("a .mamaps sparse building record carries a colour it disclaims");+ }+ if !has_rcol && (buf[o + 11] != 0 || buf[o + 12] != 0 || buf[o + 13] != 0) {+ return err("a .mamaps sparse building record carries a colour it disclaims");+ }+ attrs.push(BuildingAttrs {+ height: u16::from_le_bytes([buf[o], buf[o + 1]]),+ min_height: u16::from_le_bytes([buf[o + 2], buf[o + 3]]),+ roof_height: u16::from_le_bytes([buf[o + 4], buf[o + 5]]),+ roof_shape,+ roof_direction: buf[o + 7],+ roof_orientation,+ building_colour: if has_bcol { bcol } else { 0 },+ roof_colour: if has_rcol { rcol } else { 0 },+ });+ at += BUILDING_ATTRS_V10_LEN;+ }+ table.push((layer_id, attrs));+ }+ let aligned = align4(at);+ if aligned > buf.len() {+ return err("a .mamaps sparse building table's padding runs past the body");+ }+ Ok((table, aligned))+}++/// Serialise a sparse S3DB table, 4-byte aligned. Layers with no tagged+/// buildings are omitted entirely (the reader restores all-default); the+/// inverse of [`parse_sparse_buildings`].+pub fn serialize_sparse_buildings(buildings: &[(u8, Vec<BuildingAttrs>)], out: &mut Vec<u8>) {+ let present: Vec<(&u8, &Vec<BuildingAttrs>)> = buildings+ .iter()+ .map(|(id, v)| (id, v))+ .filter(|(_, v)| v.iter().any(|a| !is_default_attrs(a)))+ .collect();+ out.extend_from_slice(&(present.len() as u32).to_le_bytes());+ for (layer_id, entries) in present {+ out.push(*layer_id);+ out.extend_from_slice(&(entries.len() as u32).to_le_bytes());+ let mut bits = vec![0u8; entries.len().div_ceil(8)];+ for (i, a) in entries.iter().enumerate() {+ if !is_default_attrs(a) {+ bits[i / 8] |= 1u8 << (i % 8);+ }+ }+ out.extend_from_slice(&bits);+ for a in entries {+ if is_default_attrs(a) {+ continue;+ }+ out.extend_from_slice(&a.height.to_le_bytes());+ out.extend_from_slice(&a.min_height.to_le_bytes());+ out.extend_from_slice(&a.roof_height.to_le_bytes());+ out.push(pack_attrs(a));+ out.push(a.roof_direction);+ // RGB24: alpha is always FF-or-absent, presence in the packed flags.+ out.push((a.building_colour & 0xFF) as u8);+ out.push(((a.building_colour >> 8) & 0xFF) as u8);+ out.push(((a.building_colour >> 16) & 0xFF) as u8);+ out.push((a.roof_colour & 0xFF) as u8);+ out.push(((a.roof_colour >> 8) & 0xFF) as u8);+ out.push(((a.roof_colour >> 16) & 0xFF) as u8);+ }+ }+ while out.len() % 4 != 0 {+ out.push(0);+ }+}
maps/src/main/rust/Cargo.toml
diff --git a/maps/src/main/rust/Cargo.toml b/maps/src/main/rust/Cargo.tomlindex 8955760b58..98b7c22a0a 100644--- a/maps/src/main/rust/Cargo.toml+++ b/maps/src/main/rust/Cargo.toml@@ -25,4 +25,10 @@ flate2.workspace = true # Cargo.toml), the same way library/map's Rust consumes it. tilecodec = { path = "../../../../library/tilecodec/src/main/rust" } +# Test-only writer access: device tests synthesize v7 blocked payloads with+# `write_blocked`. Same package id, so cargo unifies features for the test+# build only — the cdylib keeps its read-only rule.+[dev-dependencies]+tilecodec = { path = "../../../../library/tilecodec/src/main/rust", features = ["write"] }+ # Patch inherited from workspace root Cargo.toml.
maps/src/main/rust/src/graph.rs
diff --git a/maps/src/main/rust/src/graph.rs b/maps/src/main/rust/src/graph.rsindex 69ff5d589d..6af262225f 100644--- a/maps/src/main/rust/src/graph.rs+++ b/maps/src/main/rust/src/graph.rs@@ -81,7 +81,12 @@ pub const GRAPH_MAGIC: u32 = 0x4752_414D; /// Version 6 moves `name_offset` out of the record into a sparse side table, since /// two thirds of edges are unnamed, taking the record to 7 bytes and planet to /// ~23.3 GB. There is no dual-path reader: an older pack is rejected.-pub const GRAPH_VERSION: u32 = 6;+/// Version 7 blocked-compresses `nodes.bin`, `edges.bin` records and+/// `elevation.bin` (ZBLK sections); readers accept 6 and 7, inflating v7+/// sections once on first use.+pub const GRAPH_VERSION: u32 = 7;+/// Oldest graph version decoded: v6 raw tables still read directly.+pub const GRAPH_VERSION_MIN: u32 = 6; /// Sentinel `name_offset` meaning "this edge has no name". ///@@ -433,6 +438,8 @@ pub(crate) unsafe fn read_at<T: Copy>(base: *const u8, idx: usize) -> T { include!("graph_part1.rs"); include!("graph_part2.rs");+include!("graph_part2b.rs"); include!("graph_part3.rs"); include!("graph_part4.rs");+include!("graph_part4b.rs"); include!("graph_part5.rs");\ No newline at end of file
maps/src/main/rust/src/graph_part1.rs
diff --git a/maps/src/main/rust/src/graph_part1.rs b/maps/src/main/rust/src/graph_part1.rsindex 4568c3f822..38e9adfe54 100644--- a/maps/src/main/rust/src/graph_part1.rs+++ b/maps/src/main/rust/src/graph_part1.rs@@ -64,13 +64,120 @@ pub struct Graph { // length does not match `node_count`, in which case [`Graph::node_elevation`] reads 0 for every // node and the route profile comes out flat. A sidecar like `road_names.bin`/`lanes.bin`: no // metadata count and no GRAPH_VERSION bump, validated by its own length instead.+ //+ // Under v7 the file is a ZBLK section ([`elevation_blocked`]); the loader+ // dispatches on the magic, so absence still reads as all-zero. elevation: *const u8, + /// v7 blocked views, parsed (not inflated) at load. `None` on the v6 path,+ /// where the raw pointers above serve directly. The unpacked bytes live in+ /// the [`Graph::unpacked`] caches below on first use.+ nodes_view: Option<BlockedView>,+ edges_view: Option<BlockedView>,+ elevation_view: Option<BlockedView>,++ /// Lazily inflated v7 sections, one per blocked file. Empty (and the raw+ /// pointers above null) on the v6 path.+ ///+ /// Full-section inflate on first use rather than a per-block cache: routing+ /// touches the whole graph anyway, so steady-state memory equals the v6+ /// resident set and the hot accessors keep their pointer arithmetic. The+ /// cost is a one-time inflate per section on first route, not per lookup.+ unpacked_nodes: std::sync::OnceLock<Vec<u8>>,+ unpacked_edges: std::sync::OnceLock<Vec<u8>>,+ unpacked_elevation: std::sync::OnceLock<Vec<u8>>,+ // Derived cost tables (computed in `load`, matching the C++ `init`). pub lon_to_mm_scale: [u32; 4096], pub time_scale_fixed: [u64; 4], pub edge_time_multipliers: [[u64; 16]; 4], } +/// A parsed ZBLK section that borrows nothing.+///+/// The offset table is copied (8 bytes per block — 524 KB for 268 M planet+/// bodies) so this owns everything it needs except the frames themselves,+/// which stay in the mmap region (or archive slice) the caller keeps alive+/// exactly like the raw tables. No lifetime ties the two structs together.+pub(crate) struct BlockedView {+ record_len: usize,+ records_per_block: u64,+ unpacked_len: u64,+ /// Absolute file offsets of each block start, plus the file end.+ offsets: Vec<u64>,+ frames: *const u8,+ frames_len: u64,+}++// Raw pointers into a mapping the graph owns: Send exactly like the tables.+unsafe impl Send for BlockedView {}+unsafe impl Sync for BlockedView {}++impl BlockedView {+ /// Parse over `bytes` (the whole section file/slice). Refuses bad magic,+ /// unknown flags, zero stride, and offsets outside the section. Mirrors+ /// `tilecodec::blocked::Blocked::parse` without borrowing it, so no+ /// lifetime ties this view to the mapping.+ pub(crate) fn parse(bytes: &[u8]) -> Option<BlockedView> {+ if bytes.len() < 28 {+ return None;+ }+ let u32_at = |o: usize| {+ u32::from_le_bytes([bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3]])+ };+ let u64_at = |o: usize| {+ u64::from_le_bytes([+ bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3], bytes[o + 4],+ bytes[o + 5], bytes[o + 6], bytes[o + 7],+ ])+ };+ if u32_at(0) != tilecodec::blocked::BLOCKED_MAGIC || u32_at(4) != 0 {+ return None;+ }+ let record_len = u32_at(8) as usize;+ let records_per_block = u32_at(12) as u64;+ let unpacked_len = u64_at(16);+ if record_len == 0 || records_per_block == 0 {+ return None;+ }+ let block_count = u32_at(24) as usize;+ let mut offsets = Vec::with_capacity(block_count + 1);+ for i in 0..=block_count {+ let o = u64_at(28 + i * 8);+ if o > bytes.len() as u64 || (i > 0 && o < offsets[i - 1]) {+ return None;+ }+ offsets.push(o);+ }+ // No end-equality check: a blocked record array may share its file+ // with trailing tables (`edges.bin`'s escapes/names). Truncation is+ // still refused above — an offset past the bytes fails.+ Some(BlockedView {+ record_len,+ records_per_block,+ unpacked_len,+ offsets,+ frames: bytes.as_ptr(),+ frames_len: bytes.len() as u64,+ })+ }++ /// Inflate every block and concatenate, verifying the unpacked length.+ /// Called once per section via the graph's `OnceLock`s.+ pub(crate) fn unpack(&self) -> Option<Vec<u8>> {+ let bytes = unsafe { std::slice::from_raw_parts(self.frames, self.frames_len as usize) };+ let parsed = tilecodec::blocked::Blocked::parse(bytes).ok()?;+ let mut cache = tilecodec::blocked::BlockCache::new(0);+ let mut out = Vec::with_capacity(self.unpacked_len as usize);+ for b in 0..parsed.block_count() {+ out.extend_from_slice(cache.get(&parsed, b).ok()?);+ }+ if out.len() as u64 != self.unpacked_len {+ return None;+ }+ Some(out)+ }+}+ unsafe impl Send for Graph {} unsafe impl Sync for Graph {}
maps/src/main/rust/src/graph_part2.rs
diff --git a/maps/src/main/rust/src/graph_part2.rs b/maps/src/main/rust/src/graph_part2.rsindex 5ecd49cb05..064a52869b 100644--- a/maps/src/main/rust/src/graph_part2.rs+++ b/maps/src/main/rust/src/graph_part2.rs@@ -39,14 +39,16 @@ impl Graph { // Explicit count fields rather than a generic section directory: each // version adds one, and a named field is more debuggable than speculative // generality.- let (node_count, edge_count, escape_count, named_edges) = {+ let (node_count, edge_count, escape_count, named_edges, blocked_v7) = { let meta = MmapRegion::map(&format!("{base}metadata.bin"))?; if meta.len < 40 { return None; } let magic = unsafe { read_at::<u32>(meta.base(), 0) }; let version = unsafe { read_at::<u32>(meta.base(), 1) };- if magic != GRAPH_MAGIC || version != GRAPH_VERSION {+ if magic != GRAPH_MAGIC+ || !(GRAPH_VERSION_MIN..=GRAPH_VERSION).contains(&version)+ { return None; } let nodes = unsafe { read_at::<u64>(meta.base().add(8), 0) };@@ -60,30 +62,82 @@ impl Graph { if u32::try_from(edges).is_err() || escapes > edges || named > edges { return None; }- (u32::try_from(nodes).ok()?, edges, escapes, named)+ (+ u32::try_from(nodes).ok()?,+ edges,+ escapes,+ named,+ version >= GRAPH_VERSION,+ ) }; // `edge_count` now comes from the header rather than from `edges.bin`'s // length. That is the point of version 4, and 5 and 6 are why: the record is // 7 bytes and the file has four more sections behind it, so its length is no // longer any simple multiple of anything.+ //+ // v7 packs the record arrays as ZBLK sections, so their lengths are+ // data-dependent: the blocked views below replace the exact-length+ // assertions, validating unpacked lengths instead.+ //+ // `version` is scoped to the metadata block above; `blocked_v7` rides+ // out with the counts. let nodes_region = MmapRegion::map(&format!("{base}nodes.bin"))?; let edges_region = MmapRegion::map(&format!("{base}edges.bin"))?; // nodes.bin is `NodeRec[node_count + 1]`: one sentinel record past the real // nodes, whose `edge_ptr` is `edge_count`. Eight call sites read it. let want_nodes = (u64::from(node_count) + 1) * std::mem::size_of::<NodeRec>() as u64;- if nodes_region.len as u64 != want_nodes {- return None;- }+ let nodes_view = if blocked_v7 {+ let bytes = unsafe {+ std::slice::from_raw_parts(nodes_region.base(), nodes_region.len)+ };+ let view = BlockedView::parse(bytes)?;+ if view.unpacked_len != want_nodes || view.record_len != 12 {+ return None;+ }+ Some(view)+ } else {+ if nodes_region.len as u64 != want_nodes {+ return None;+ }+ None+ };+ let nodes = if nodes_view.is_some() {+ ptr::null()+ } else {+ nodes_region.base()+ }; // edges.bin's five sections, computed forwards from the metadata counts. // The total-length assertion below is what replaces v3's self-locating // trailer: if the computed sections do not exactly consume the region, the- // file is not the one these counts describe.+ // file is not the one these counts describe. Under v7 the record array+ // is a ZBLK section whose end the view reports; the escapes and names+ // follow it exactly as before. let escape_blocks = edge_count.div_ceil(ESCAPE_BLOCK) + 1;- let escape_first_off =- align_up(edge_count * std::mem::size_of::<EdgeRec>() as u64, SECTION_ALIGN);+ let (escape_first_off, edges_view) = if blocked_v7 {+ let bytes = unsafe {+ std::slice::from_raw_parts(edges_region.base(), edges_region.len)+ };+ let view = BlockedView::parse(bytes)?;+ if view.unpacked_len != edge_count * std::mem::size_of::<EdgeRec>() as u64+ || view.record_len != 7+ {+ return None;+ }+ // The records section ends at the last block offset; escapes follow.+ let rec_end = view.offsets[view.offsets.len() - 1];+ (align_up(rec_end, SECTION_ALIGN), Some(view))+ } else {+ (+ align_up(+ edge_count * std::mem::size_of::<EdgeRec>() as u64,+ SECTION_ALIGN,+ ),+ None,+ )+ }; let escapes_off = escape_first_off + escape_blocks * std::mem::size_of::<u32>() as u64; let names_off = align_up(@@ -95,7 +149,11 @@ impl Graph { if edges_region.len as u64 != want_edges { return None; }- let edges = edges_region.base();+ let edges = if edges_view.is_some() {+ ptr::null()+ } else {+ edges_region.base()+ }; let escape_first = unsafe { edges.add(escape_first_off as usize) }; let escapes = unsafe { edges.add(escapes_off as usize) }; let names = EdgeBitmap {@@ -223,12 +281,32 @@ impl Graph { // elevation.bin: `i16[node_count]`, one per real node in node-id order. Optional and // validated by length alone — a stale-vintage file whose node_count differs is simply // disabled (elevation reads 0), the same self-check lanes.bin does against `edge_count`.+ // Under v7 the file is a ZBLK section, dispatched on its magic: blocked+ // parses as blocked, a raw `N * 2` file as raw, anything else as absent. let elevation_region = MmapRegion::map(&format!("{base}elevation.bin"));- let elevation = match &elevation_region {- Some(r) if r.len as u64 == u64::from(node_count) * std::mem::size_of::<i16>() as u64 => {- r.base()+ let (elevation, elevation_view) = match &elevation_region {+ Some(r) if blocked_v7 => {+ let bytes =+ unsafe { std::slice::from_raw_parts(r.base(), r.len) };+ match BlockedView::parse(bytes) {+ Some(view)+ if view.unpacked_len+ == u64::from(node_count)+ * std::mem::size_of::<i16>() as u64+ && view.record_len == 2 =>+ {+ (ptr::null(), Some(view))+ }+ _ => (ptr::null(), None),+ }+ }+ Some(r)+ if r.len as u64+ == u64::from(node_count) * std::mem::size_of::<i16>() as u64 =>+ {+ (r.base(), None) }- _ => ptr::null(),+ _ => (ptr::null(), None), }; // A wrong-length elevation.bin is dropped, not kept mapped: nothing should read a stale // vintage's bytes, and holding the region alive would imply it is usable.@@ -308,153 +386,16 @@ impl Graph { road_names, road_names_size, elevation,+ nodes_view,+ edges_view,+ elevation_view,+ unpacked_nodes: std::sync::OnceLock::new(),+ unpacked_edges: std::sync::OnceLock::new(),+ unpacked_elevation: std::sync::OnceLock::new(), lon_to_mm_scale, time_scale_fixed, edge_time_multipliers, }) } - // --- Raw accessors (all unaligned-safe) ----- #[inline]- pub fn node(&self, id: u32) -> NodeMaster {- // Callers guarantee id <= node_count (sentinel index is valid).- let r = unsafe { read_at::<NodeRec>(self.nodes, id as usize) };- NodeMaster {- lat_e7: r.lat_e7,- lon_e7: r.lon_e7,- edge_ptr: u64::from(r.edge_ptr),- }- }-- /// Safe node fetch: returns a zeroed node for out-of-range ids, mirroring- /// the C++ `get_node` fallback.- ///- /// Deliberately asymmetric with [`Graph::node`], which is unchecked: the- /// sentinel index `node_count` is a *valid* read that this method rejects, and- /// [`Graph::edge_range`] depends on being able to make it.- #[inline]- pub fn get_node(&self, id: u32) -> NodeMaster {- if self.nodes.is_null() || id >= self.node_count {- return NodeMaster {- lat_e7: 0,- lon_e7: 0,- edge_ptr: 0,- };- }- self.node(id)- }-- /// Ground elevation of node `id` in metres, or 0 when the graph carries no `elevation.bin` or- /// `id` is out of range. Baked from the DEM at build time (WS-G); a build without a DEM, or a- /// node off the DEM's coverage, reads as 0 so the route profile is simply flat there.- #[inline]- pub fn node_elevation(&self, id: u32) -> i16 {- if self.elevation.is_null() || id >= self.node_count {- return 0;- }- unsafe { read_at::<i16>(self.elevation, id as usize) }- }-- /// `[start, end)` of node `id`'s outgoing edges in `edges.bin`. `id` must be a- /// real node, i.e. `id < node_count`.- ///- /// The only way to ask that question. Every caller that reads an `edge_ptr`- /// wants a range, not an offset, so the pairing is expressed once here rather- /// than transcribed at eight sites — which is also what stops a future- /// `nodes.bin` layout from leaking out of this file.- ///- /// # What the sentinel record is for- ///- /// `nodes.bin` carries one record past the real nodes whose `edge_ptr` is- /// `edge_count`. That is what makes this well-defined for the *last* real node:- /// `id + 1` is read for every node, so without it the last one would read past- /// the mapping and every other node's range would be one short of correct.- /// `edge_range(node_count - 1).1 == edge_count` is the property, and it is- /// load-bearing at eight sites.- ///- /// The sentinel index itself is the highest `id` this may be *passed plus one* —- /// `edge_range(node_count)` would read `node_count + 1`, which does not exist.- /// Every caller either iterates `0..node_count` or rejects `id >= node_count`- /// first.- ///- /// Note that this goes through [`Graph::node`], which is unchecked, *not*- /// [`Graph::get_node`], which would reject the sentinel index and silently- /// return `edge_ptr = 0` — turning the last node's range into an empty one.- #[inline]- pub fn edge_range(&self, id: u32) -> (u64, u64) {- debug_assert!(id < self.node_count, "node {id} is not a real node");- (self.node(id).edge_ptr, self.node(id + 1).edge_ptr)- }-- /// Edge `idx`, which must be one of node `source`'s outgoing edges.- ///- /// `source` is what makes the record readable at all: it stores `target` as a- /// signed delta from it. Passing the wrong one produces a plausible node id- /// rather than a crash, which is why the debug assertion below exists — it is the- /// cheapest available guard against the one bug class delta coding introduces.- #[inline]- pub fn edge(&self, source: u32, idx: u64) -> Edge {- debug_assert!(- {- let (s, e) = self.edge_range(source);- (s..e).contains(&idx)- },- "edge {idx} is not in node {source}'s range {:?}",- self.edge_range(source)- );- let r = unsafe { read_at::<EdgeRec>(self.edges, idx as usize) };- let (target, dist_mm) = if r.escaped() {- self.escaped_fields(idx)- } else {- (- source.wrapping_add_signed(i32::from(r.target_delta)),- r.dist_mm(),- )- };- Edge {- target,- dist_mm,- type_: r.type_,- speed_limit: r.speed_limit,- }- }-- /// `(target, dist_mm)` from the escape table, for an edge whose record carries a- /// sentinel.- ///- /// One load from the block index, then a scan of that block's rows — ~3 of them- /// at a 0.3% escape rate, usually within one cache line. See [`ESCAPE_BLOCK`].- ///- /// A record with a sentinel and no matching row is a corrupt pack that the load-- /// time checks cannot catch without an O(E) scan. It returns `u32::MAX` as the- /// target, which every caller already rejects as out of range, so the edge is- /// skipped rather than followed somewhere arbitrary.- #[cold]- fn escaped_fields(&self, idx: u64) -> (u32, u32) {- let block = (idx / ESCAPE_BLOCK) as usize;- let lo = unsafe { read_at::<u32>(self.escape_first, block) };- let hi = unsafe { read_at::<u32>(self.escape_first, block + 1) };- for r in lo..hi {- let row = unsafe { read_at::<EscapeRow>(self.escapes, r as usize) };- if u64::from(row.edge_idx) == idx {- return (row.target, row.dist_mm);- }- }- debug_assert!(false, "edge {idx} is escaped but has no escape row");- (u32::MAX, DIST_MM_ESCAPE)- }-- /// Whether edge `idx` of node `source` points at `want`.- ///- /// Four call sites scan a node's edge range looking for the one edge that reaches- /// a given node and never use the target as a value. Delegating to [`Graph::edge`]- /// rather than comparing in delta space keeps the escape handling in one place:- /// the delta form would have to handle both an escaped record that could still- /// match and a `want − source` outside `i16` range, and the saving over one- /// sign-extend and one add is nothing.- #[inline]- pub fn edge_targets(&self, idx: u64, source: u32, want: u32) -> bool {- self.edge(source, idx).target == want- } }
maps/src/main/rust/src/graph_part4.rs
diff --git a/maps/src/main/rust/src/graph_part4.rs b/maps/src/main/rust/src/graph_part4.rsindex 33bce46b6b..13bafa31e3 100644--- a/maps/src/main/rust/src/graph_part4.rs+++ b/maps/src/main/rust/src/graph_part4.rs@@ -106,29 +106,56 @@ impl Graph { let edge_count = edges; let escape_count = escapes; let named_edges = named;+ let blocked_v7 = version >= GRAPH_VERSION; // `edge_count` comes from the header rather than from the edges // payload's length. That is the point of graph version 4, and 5 and 6 // are why: the record is 7 bytes and the payload has four more // sections behind it, so its length is no longer any simple multiple- // of anything.+ // of anything. Under v7 the record array is a ZBLK section whose end+ // the view reports. let nodes_bytes = sections.nodes; let edges_bytes = sections.edges; // nodes payload is `NodeRec[node_count + 1]`: one sentinel record past // the real nodes, whose `edge_ptr` is `edge_count`. Eight call sites // read it. let want_nodes = (u64::from(node_count) + 1) * std::mem::size_of::<NodeRec>() as u64;- if nodes_bytes.len() as u64 != want_nodes {- return None;- }+ let nodes_view = if blocked_v7 {+ let view = BlockedView::parse(nodes_bytes)?;+ if view.unpacked_len != want_nodes || view.record_len != 12 {+ return None;+ }+ Some(view)+ } else {+ if nodes_bytes.len() as u64 != want_nodes {+ return None;+ }+ None+ }; // Edges payload's five sections, computed forwards from the metadata // counts. The total-length assertion below is what replaces v3's // self-locating trailer: if the computed sections do not exactly // consume the payload, it is not the one these counts describe. let escape_blocks = edge_count.div_ceil(ESCAPE_BLOCK) + 1;- let escape_first_off =- align_up(edge_count * std::mem::size_of::<EdgeRec>() as u64, SECTION_ALIGN);+ let (escape_first_off, edges_view) = if blocked_v7 {+ let view = BlockedView::parse(edges_bytes)?;+ if view.unpacked_len != edge_count * std::mem::size_of::<EdgeRec>() as u64+ || view.record_len != 7+ {+ return None;+ }+ let rec_end = view.offsets[view.offsets.len() - 1];+ (align_up(rec_end, SECTION_ALIGN), Some(view))+ } else {+ (+ align_up(+ edge_count * std::mem::size_of::<EdgeRec>() as u64,+ SECTION_ALIGN,+ ),+ None,+ )+ }; let escapes_off = escape_first_off + escape_blocks * std::mem::size_of::<u32>() as u64; let names_off = align_up(@@ -140,7 +167,11 @@ impl Graph { if edges_bytes.len() as u64 != want_edges { return None; }- let edges_ptr = edges_bytes.as_ptr();+ let edges_ptr = if edges_view.is_some() {+ ptr::null()+ } else {+ edges_bytes.as_ptr()+ }; let escape_first = unsafe { edges_ptr.add(escape_first_off as usize) }; let escapes_ptr = unsafe { edges_ptr.add(escapes_off as usize) }; let names = EdgeBitmap {@@ -286,14 +317,25 @@ impl Graph { // order. Optional and validated by length alone — a stale-vintage // payload whose node_count differs is simply disabled (elevation reads // 0), the same self-check the lanes payload does against `edge_count`.- let elevation = match sections.elevation {+ // Under v7 the payload is a ZBLK section, dispatched on its magic.+ let (elevation, elevation_view) = match sections.elevation {+ Some(b) if blocked_v7 => match BlockedView::parse(b) {+ Some(view)+ if view.unpacked_len+ == u64::from(node_count) * std::mem::size_of::<i16>() as u64+ && view.record_len == 2 =>+ {+ (ptr::null(), Some(view))+ }+ _ => (ptr::null(), None),+ }, Some(b) if b.len() as u64 == u64::from(node_count) * std::mem::size_of::<i16>() as u64 => {- b.as_ptr()+ (b.as_ptr(), None) }- _ => ptr::null(),+ _ => (ptr::null(), None), }; // A wrong-length elevation payload is dropped, not kept mapped:@@ -303,7 +345,11 @@ impl Graph { own.elevation = None; } - let nodes = nodes_bytes.as_ptr();+ let nodes = if nodes_view.is_some() {+ ptr::null()+ } else {+ nodes_bytes.as_ptr()+ }; // --- Derived tables (identical formulas to the C++ init) --- let mut lon_to_mm_scale = [0u32; 4096]; for (i, scale) in lon_to_mm_scale.iter_mut().enumerate() {@@ -402,50 +448,15 @@ impl Graph { road_names, road_names_size, elevation,+ nodes_view,+ edges_view,+ elevation_view,+ unpacked_nodes: std::sync::OnceLock::new(),+ unpacked_edges: std::sync::OnceLock::new(),+ unpacked_elevation: std::sync::OnceLock::new(), lon_to_mm_scale, time_scale_fixed, edge_time_multipliers, }) }-- /// Load the graph from a single-archive `.mamaps` file.- ///- /// Maps the one file, parses the tile header and the sidecar directory- /// (which refuses a corrupt container, a build-id mismatch and any- /// section the header's counts do not describe), then hands the seven- /// graph payloads to [`Graph::assemble`]. Optional sections absent from- /// the directory degrade exactly as absent files do today: no names pool,- /// topology-inferred lanes, a flat profile.- pub fn load_archive(path: &str) -> Option<Graph> {- let region = MmapRegion::map(path)?;- // The mapping must cover the whole file: ArchiveView::parse checks- // `bytes.len() == header.file_len`, and a short mapping would refuse- // a good archive rather than read past it.- let bytes = unsafe { std::slice::from_raw_parts(region.base(), region.len) };- let header = Header::parse(bytes).ok()?;- let view = ArchiveView::parse(bytes, &header).ok()?;- let section = |kind| view.section(bytes, kind);- let sections = GraphSections {- meta: section(ARCHIVE_KIND_GRAPH_META)?,- nodes: section(ARCHIVE_KIND_GRAPH_NODES)?,- edges: section(ARCHIVE_KIND_GRAPH_EDGES)?,- intermediate: section(ARCHIVE_KIND_GRAPH_INTERMEDIATE)?,- road_names: section(ARCHIVE_KIND_GRAPH_NAMES),- lanes: section(ARCHIVE_KIND_GRAPH_LANES),- elevation: section(ARCHIVE_KIND_GRAPH_ELEVATION),- };- Graph::assemble(- sections,- GraphOwnership {- nodes: None,- edges: None,- intermediate: None,- road_names: None,- lanes: None,- elevation: None,- archive: Some(region),- buffers: Vec::new(),- },- )- } }
maps/src/main/rust/src/graph_part5.rs
diff --git a/maps/src/main/rust/src/graph_part5.rs b/maps/src/main/rust/src/graph_part5.rsindex 5e2d19b80f..ef71f079b7 100644--- a/maps/src/main/rust/src/graph_part5.rs+++ b/maps/src/main/rust/src/graph_part5.rs@@ -38,17 +38,13 @@ mod archive_tests { min_lat_e7: 0, max_lon_e7: 0, max_lat_e7: 0,- shared_offset: 0,- shared_len: 0,- shared_flags: 0,- shared_pools: 0, } } - fn meta(node_count: u64, edge_count: u64, escapes: u64, named: u64) -> Vec<u8> {+ fn meta_at(version: u32, node_count: u64, edge_count: u64, escapes: u64, named: u64) -> Vec<u8> { let mut out = Vec::new(); out.extend_from_slice(&GRAPH_MAGIC.to_le_bytes());- out.extend_from_slice(&GRAPH_VERSION.to_le_bytes());+ out.extend_from_slice(&version.to_le_bytes()); out.extend_from_slice(&node_count.to_le_bytes()); out.extend_from_slice(&edge_count.to_le_bytes()); out.extend_from_slice(&escapes.to_le_bytes());@@ -56,6 +52,10 @@ mod archive_tests { out } + fn meta(node_count: u64, edge_count: u64, escapes: u64, named: u64) -> Vec<u8> {+ meta_at(GRAPH_VERSION_MIN, node_count, edge_count, escapes, named)+ }+ // Whole file: tile prefix (zeroes under a real serialized header) + // payloads laid out 8-aligned in kind order + directory + footer. fn assemble(payloads: &[(u8, Vec<u8>, u64)]) -> Vec<u8> {@@ -162,6 +162,9 @@ mod archive_tests { // is 26 bytes of trailer with G = 0 and a zero blob. Zeros satisfy every // totals check, which is the point: the test would catch a validator that // stopped validating.+ //+ // v6 raw tables: the container-path tests pin the old layout so the+ // version dispatch has both sides covered (`*_v7` below pins blocked). fn minimal_payloads() -> Vec<(u8, Vec<u8>, u64)> { vec![ (ARCHIVE_KIND_GRAPH_META, meta(1, 0, 0, 0), 0),@@ -171,6 +174,28 @@ mod archive_tests { ] } + /// The same minimal graph with v7 blocked record sections.+ fn minimal_payloads_v7() -> Vec<(u8, Vec<u8>, u64)> {+ let nodes = tilecodec::blocked::write_blocked(&[0u8; 24], 12);+ // Edges v7: blocked records (empty) + the same 16-byte tail.+ let recs = tilecodec::blocked::write_blocked(&[], 7);+ let mut edges = recs;+ while edges.len() % 8 != 0 {+ edges.push(0);+ }+ edges.extend_from_slice(&[0u8; 16]);+ vec![+ (+ ARCHIVE_KIND_GRAPH_META,+ meta_at(GRAPH_VERSION, 1, 0, 0, 0),+ 0,+ ),+ (ARCHIVE_KIND_GRAPH_NODES, nodes, 1),+ (ARCHIVE_KIND_GRAPH_EDGES, edges, 0),+ (ARCHIVE_KIND_GRAPH_INTERMEDIATE, vec![0u8; 26], 0),+ ]+ }+ #[test] fn container_layers_parse_before_assemble_runs() { let bytes = assemble(&minimal_payloads());@@ -190,6 +215,29 @@ mod archive_tests { assert_eq!((node.lat_e7, node.lon_e7), (0, 0)); } + #[test]+ fn a_minimal_v7_archive_loads_and_reads_through_the_inflate() {+ let g = load_slices(&minimal_payloads_v7()).expect("a minimal v7 archive loads");+ assert_eq!(g.node_count, 1);+ assert_eq!(g.edge_count, 0);+ // Nodes are zeros (sentinel + one zero node): the read went through+ // the blocked section, not past it.+ let node = g.node(0);+ assert_eq!((node.lat_e7, node.lon_e7), (0, 0));+ assert!(g.uses_blocked_sections(), "v7 takes the blocked path");+ }++ #[test]+ fn a_v7_nodes_payload_with_the_wrong_unpacked_length_is_refused() {+ let mut payloads = minimal_payloads_v7();+ // Corrupt the unpacked length (N = 1 node + sentinel wants 24).+ payloads[1].1[16] = 25;+ assert!(+ load_slices(&payloads).is_none(),+ "unpacked length, not file length, gates v7"+ );+ }+ #[test] fn a_nodes_payload_the_meta_does_not_describe_is_refused() { let mut payloads = minimal_payloads();
scripts/maps/mamaps_build/Cargo.lock
diff --git a/scripts/maps/mamaps_build/Cargo.lock b/scripts/maps/mamaps_build/Cargo.lockindex 83f21ae519..d17ae2b92a 100644--- a/scripts/maps/mamaps_build/Cargo.lock+++ b/scripts/maps/mamaps_build/Cargo.lock@@ -116,6 +116,7 @@ dependencies = [ "memmap2", "miniz_oxide", "rayon",+ "tilecodec", ] [[package]]@@ -138,6 +139,15 @@ dependencies = [ "crossbeam-utils", ] +[[package]]+name = "ruzstd"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7c1c839d570d835527c9a5e4db7cb2198683a988cb9d7293fc8674e6bd58fc8"+dependencies = [+ "twox-hash",+]+ [[package]] name = "shlex" version = "2.0.1"@@ -159,4 +169,18 @@ name = "tilecodec" version = "0.1.0" dependencies = [ "miniz_oxide",+ "ruzstd",+ "zstd-rs", ]++[[package]]+name = "twox-hash"+version = "2.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2"++[[package]]+name = "zstd-rs"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41514ccc30389f95bb9e6ab6d5634f17121c7b4fead6722a5fceec1c7891d78f"
scripts/maps/mamaps_build/src/main_part2.rs
diff --git a/scripts/maps/mamaps_build/src/main_part2.rs b/scripts/maps/mamaps_build/src/main_part2.rsindex 5774195d8b..c35a199bcc 100644--- a/scripts/maps/mamaps_build/src/main_part2.rs+++ b/scripts/maps/mamaps_build/src/main_part2.rs@@ -67,30 +67,81 @@ fn check_graph_dir(dir: &std::path::Path, region: osm_ingest::region::Region) -> return Err(format!("{} is not a MARG graph header", dir.join("metadata.bin").display())); } let version = u32_at(&meta, 4);- if version != 6 {- return Err(format!("the graph is version {version}; this build reads v6"));+ if version != 6 && version != 7 {+ return Err(format!("the graph is version {version}; this build reads v6..=v7")); }+ let blocked_v7 = version >= 7; let node_count = u64_at(&meta, 8); let edge_count = u64_at(&meta, 16); if node_count == 0 { return Err(format!("the graph at {} has 0 nodes — road_graph wrote nothing?", dir.display())); } // The remaining files must exist and match the header's counts.- let nodes = read("nodes.bin")?;- let want_nodes = (node_count + 1).checked_mul(12).ok_or_else(|| "node table size overflows".to_string())?;- if nodes.len() as u64 != want_nodes {- return Err(format!(- "nodes.bin is {} bytes, expected {want_nodes} for {node_count}+1 records — stale graph dir?",- nodes.len(),- ));+ // Under v7 the record arrays are ZBLK sections: unpack at the boundary+ // (this is a preflight check, not the hot path, so whole-section inflate+ // is fine).+ fn inflate_all(v: &tilecodec::blocked::Blocked) -> Result<Vec<u8>, String> {+ let mut cache = tilecodec::blocked::BlockCache::new(0);+ let mut out = Vec::with_capacity(v.unpacked_len() as usize);+ for b in 0..v.block_count() {+ out.extend_from_slice(+ cache+ .get(v, b)+ .map_err(|e| format!("blocked inflate failed: {e}"))?,+ );+ }+ if out.len() as u64 != v.unpacked_len() {+ return Err("blocked inflate came up short".to_string());+ }+ Ok(out) }+ let want_nodes = (node_count + 1)+ .checked_mul(12)+ .ok_or_else(|| "node table size overflows".to_string())?;+ let nodes_raw = read("nodes.bin")?;+ let nodes: Vec<u8> = if blocked_v7 {+ let v = tilecodec::blocked::Blocked::parse(&nodes_raw).map_err(|e| {+ format!("nodes.bin is not a blocked section: {e}")+ })?;+ if v.unpacked_len() != want_nodes || v.record_len() != 12 {+ return Err(format!(+ "nodes.bin unpacks to {} byte(s), expected {want_nodes} for {node_count}+1 records",+ v.unpacked_len(),+ ));+ }+ inflate_all(&v)?+ } else {+ if nodes_raw.len() as u64 != want_nodes {+ return Err(format!(+ "nodes.bin is {} bytes, expected {want_nodes} for {node_count}+1 records — stale graph dir?",+ nodes_raw.len(),+ ));+ }+ nodes_raw+ }; let edges = read("edges.bin")?;- let want_edges_min = ((edge_count * 7 + 7) & !7) as usize;- if edges.len() < want_edges_min {- return Err(format!(- "edges.bin is {} bytes, too short for {edge_count} edges — stale graph dir?",- edges.len(),- ));+ if blocked_v7 {+ // v7: the record array is blocked (data-dependent length), so only+ // the tail minimum applies. The real validation (blocked parse ++ // unpacked lengths + escape/name checks) lives in `traffic::Graph::load`,+ // which reads this same dir next.+ let v = tilecodec::blocked::Blocked::parse(&edges).map_err(|e| {+ format!("edges.bin is not a blocked section: {e}")+ })?;+ if v.unpacked_len() != edge_count * 7 || v.record_len() != 7 {+ return Err(format!(+ "edges.bin unpacks to {} byte(s), expected {edge_count} 7-byte records",+ v.unpacked_len(),+ ));+ }+ } else {+ let want_edges_min = ((edge_count * 7 + 7) & !7) as usize;+ if edges.len() < want_edges_min {+ return Err(format!(+ "edges.bin is {} bytes, too short for {edge_count} edges — stale graph dir?",+ edges.len(),+ ));+ } } let inter = read("intermediate.bin")?; if inter.len() < 8 {
scripts/maps/mamaps_build/src/schema/traffic.rs
diff --git a/scripts/maps/mamaps_build/src/schema/traffic.rs b/scripts/maps/mamaps_build/src/schema/traffic.rsindex aeb980d15f..19abd8317b 100644--- a/scripts/maps/mamaps_build/src/schema/traffic.rs+++ b/scripts/maps/mamaps_build/src/schema/traffic.rs@@ -88,10 +88,13 @@ pub fn traffic_class() -> Class { } } -// --- v6 graph on-disk constants (see traffic_id_contract.md §2 / graph.rs) -----------------+// --- v6/v7 graph on-disk constants (see traffic_id_contract.md §2 / graph.rs) ----------------- pub(crate) const MARG_MAGIC: u32 = 0x4752_414D; // "MARG"-pub(crate) const GRAPH_VERSION: u32 = 6;+/// Newest graph version: v7 blocked record sections.+pub(crate) const GRAPH_VERSION: u32 = 7;+/// Oldest graph version accepted: v6 raw tables still read directly.+pub(crate) const GRAPH_VERSION_MIN: u32 = 6; /// One escape block index per 1024 edges (`graph.rs` ESCAPE_BLOCK). pub(crate) const ESCAPE_BLOCK: u64 = 1024; /// One coarse geometry offset per 32 geometry edges (`graph.rs` INTERMEDIATE_BLOCK).@@ -138,6 +141,26 @@ fn align_up8(n: usize) -> usize { (n + 7) & !7 } +/// Inflate every block of a validated section and concatenate.+///+/// Batch-tool path (traffic/junction stream whole tables), so one pass beats+/// per-block caching. The device inflates lazily instead — see+/// `maps/.../graph_part1.rs::BlockedView`.+fn inflate_all(view: &tilecodec::blocked::Blocked) -> Result<Vec<u8>> {+ let mut cache = tilecodec::blocked::BlockCache::new(0);+ let mut out = Vec::with_capacity(view.unpacked_len() as usize);+ for b in 0..view.block_count() {+ let block = cache+ .get(view, b)+ .map_err(|e| osm_ingest::proto::Error(e.0))?;+ out.extend_from_slice(block);+ }+ if out.len() as u64 != view.unpacked_len() {+ return err("a blocked section inflated short of its unpacked length".to_string());+ }+ Ok(out)+}+ /// Bytes an [`EdgeBitmap`] over `edges` edges occupies: a `u64` rank word per 512 edges plus one /// present byte per 8 edges (`graph.rs` `EdgeBitmap`). fn present_offset(edges: u64) -> usize {@@ -147,21 +170,32 @@ fn edge_bitmap_bytes(edges: u64) -> usize { present_offset(edges) + edges.div_ceil(8) as usize } -/// The subset of the v6 graph reader the traffic layer needs: node coordinates, edge targets and-/// types, and big-edge geometry. Names, distances and speed limits are skipped — the server reads-/// those; the archive carries only geometry and the id.+/// The subset of the v6/v7 graph reader the traffic layer needs: node coordinates,+/// edge targets and types, and big-edge geometry. Names, distances and speed+/// limits are skipped — the server reads those; the archive carries only+/// geometry and the id. /// /// The three tables are file mappings rather than heap `Vec`s: a planet graph is gigabytes, and /// `Graph::load` runs while the OSM tables are still alive, so reading them whole would stack that /// many gigabytes of commit on top of the peak. Mapped, the OS pages the working set (junction /// walks nodes in order) and no commit is charged. Same bytes, same layout, same readers. ///+/// Under v7 the record arrays are ZBLK sections, inflated eagerly at load+/// into `nodes_owned`/`rec_owned` (a batch tool, unlike the device's lazy+/// sections — the whole graph is walked anyway). The escapes, names and+/// intermediate tables stay mapped in both versions.+/// /// `pub(crate)` because [`crate::schema::junction`] reads the same four files for the same reason /// and must not carry a second copy of this byte layout. pub(crate) struct Graph { nodes: osm_ingest::mem::Mapped, edges: osm_ingest::mem::Mapped, inter: osm_ingest::mem::Mapped,+ /// Inflated v7 nodes table. Empty on the v6 path, where `nodes` serves.+ nodes_owned: Vec<u8>,+ /// Inflated v7 edge-record array. Empty on the v6 path, where the head of+ /// `edges` serves. Escapes/names always read from `edges` at computed offsets.+ rec_owned: Vec<u8>, pub(crate) node_count: u64, escape_first_off: usize, escapes_off: usize,@@ -172,6 +206,26 @@ pub(crate) struct Graph { within_off: usize, } +impl Graph {+ /// Node records: mapped on v6, inflated on v7.+ fn nb(&self) -> &[u8] {+ if self.nodes_owned.is_empty() {+ &self.nodes+ } else {+ &self.nodes_owned+ }+ }++ /// Edge records: mapped head on v6, inflated on v7.+ fn rb(&self) -> &[u8] {+ if self.rec_owned.is_empty() {+ &self.edges+ } else {+ &self.rec_owned+ }+ }+}+ impl Graph { pub(crate) fn load(dir: &Path) -> Result<Graph> { let meta = std::fs::read(dir.join("metadata.bin")).map_err(|e| {@@ -187,11 +241,12 @@ impl Graph { return err("metadata.bin is not a MARG graph header".to_string()); } let version = u32_at(&meta, 4);- if version != GRAPH_VERSION {+ if !(GRAPH_VERSION_MIN..=GRAPH_VERSION).contains(&version) { return err(format!(- "the graph is version {version}; the traffic layer reads v{GRAPH_VERSION}"+ "the graph is version {version}; the traffic layer reads v{GRAPH_VERSION_MIN}..=v{GRAPH_VERSION}" )); }+ let blocked_v7 = version >= GRAPH_VERSION; let node_count = u64_at(&meta, 8); let edge_count = u64_at(&meta, 16); let escape_count = u64_at(&meta, 24);@@ -225,15 +280,51 @@ impl Graph { let want_nodes = (node_count + 1) .checked_mul(12) .ok_or_else(|| osm_ingest::proto::Error("node table size overflows".to_string()))?;- if nodes.len() as u64 != want_nodes {- return err(format!(- "nodes.bin is {} bytes, expected {} for {node_count}+1 records",- nodes.len(),- want_nodes,- ));- }-- let escape_first_off = align_up8((edge_count as usize) * 7);+ // v7 nodes are a ZBLK section: parse, check the unpacked length, and+ // inflate eagerly (batch tool — the whole table is walked).+ let nodes_owned = if blocked_v7 {+ let view = tilecodec::blocked::Blocked::parse(&nodes).map_err(|e| {+ osm_ingest::proto::Error(format!("nodes.bin is not a blocked section: {e}"))+ })?;+ if view.unpacked_len() != want_nodes || view.record_len() != 12 {+ return err(format!(+ "nodes.bin unpacks to {} byte(s), expected {want_nodes}",+ view.unpacked_len()+ ));+ }+ inflate_all(&view)?+ } else {+ if nodes.len() as u64 != want_nodes {+ return err(format!(+ "nodes.bin is {} bytes, expected {} for {node_count}+1 records",+ nodes.len(),+ want_nodes,+ ));+ }+ Vec::new()+ };++ // v7 edge records are a ZBLK section at the file head; escapes and+ // names follow it exactly as before. The records' end comes from the+ // section, not from `edge_count * 7`.+ let (escape_first_off, rec_owned) = if blocked_v7 {+ let view = tilecodec::blocked::Blocked::parse(&edges).map_err(|e| {+ osm_ingest::proto::Error(format!("edges.bin is not a blocked section: {e}"))+ })?;+ if view.unpacked_len() != edge_count * 7 || view.record_len() != 7 {+ return err(format!(+ "edges.bin unpacks to {} byte(s), expected {} 7-byte records",+ view.unpacked_len(),+ edge_count+ ));+ }+ let rec_end = view.block_offset(view.block_count()).ok_or_else(|| {+ osm_ingest::proto::Error("edges.bin block table has no end".to_string())+ })? as usize;+ (align_up8(rec_end), inflate_all(&view)?)+ } else {+ (align_up8((edge_count as usize) * 7), Vec::new())+ }; let escape_blocks = edge_count.div_ceil(ESCAPE_BLOCK) + 1; let escapes_off = escape_first_off + (escape_blocks as usize) * 4; let want_edges_min = escapes_off + (escape_count as usize) * 12;@@ -273,6 +364,8 @@ impl Graph { nodes, edges, inter,+ nodes_owned,+ rec_owned, node_count, escape_first_off, escapes_off,@@ -286,27 +379,28 @@ impl Graph { /// A node's `(lat_e7, lon_e7)`. pub(crate) fn node(&self, n: u64) -> (i32, i32) { let base = (n as usize) * 12;- (i32_at(&self.nodes, base), i32_at(&self.nodes, base + 4))+ (i32_at(self.nb(), base), i32_at(self.nb(), base + 4)) } /// A node's first outgoing edge index. The sentinel record (index `node_count`) holds /// `edge_count`, so `edge_ptr(n+1)` is always defined for a real node `n`. pub(crate) fn edge_ptr(&self, n: u64) -> u32 {- u32_at(&self.nodes, (n as usize) * 12 + 8)+ u32_at(self.nb(), (n as usize) * 12 + 8) } pub(crate) fn edge_type(&self, idx: u32) -> u8 {- self.edges[(idx as usize) * 7 + 5]+ self.rb()[(idx as usize) * 7 + 5] } /// The target node of edge `idx` whose source is `s`, decoding the escape table when the /// delta or distance is sentinelled. pub(crate) fn edge_target(&self, idx: u32, s: u32) -> Result<u32> { let base = (idx as usize) * 7;- let delta = i16_at(&self.edges, base);- let dist = (self.edges[base + 2] as u32)- | ((self.edges[base + 3] as u32) << 8)- | ((self.edges[base + 4] as u32) << 16);+ let rb = self.rb();+ let delta = i16_at(rb, base);+ let dist = (rb[base + 2] as u32)+ | ((rb[base + 3] as u32) << 8)+ | ((rb[base + 4] as u32) << 16); if delta == TARGET_DELTA_ESCAPE || dist == DIST_MM_ESCAPE { self.escape_target(idx) } else {
scripts/maps/mamaps_build/src/schema/traffic_extra.rs
diff --git a/scripts/maps/mamaps_build/src/schema/traffic_extra.rs b/scripts/maps/mamaps_build/src/schema/traffic_extra.rsindex 441e32ce40..881027c742 100644--- a/scripts/maps/mamaps_build/src/schema/traffic_extra.rs+++ b/scripts/maps/mamaps_build/src/schema/traffic_extra.rs@@ -57,7 +57,9 @@ pub(crate) mod tests { // metadata.bin (40 bytes). let mut meta = Vec::new(); meta.extend_from_slice(&MARG_MAGIC.to_le_bytes());- meta.extend_from_slice(&GRAPH_VERSION.to_le_bytes());+ // v6: the fixture hand-encodes raw record tables, so it stamps the+ // version those bytes are.+ meta.extend_from_slice(&GRAPH_VERSION_MIN.to_le_bytes()); meta.extend_from_slice(&node_count.to_le_bytes()); meta.extend_from_slice(&edge_count.to_le_bytes()); meta.extend_from_slice(&0u64.to_le_bytes()); // escape_count
scripts/maps/osm_ingest/Cargo.lock
diff --git a/scripts/maps/osm_ingest/Cargo.lock b/scripts/maps/osm_ingest/Cargo.lockindex e994345766..374c08b4e0 100644--- a/scripts/maps/osm_ingest/Cargo.lock+++ b/scripts/maps/osm_ingest/Cargo.lock@@ -71,6 +71,7 @@ dependencies = [ "memmap2", "miniz_oxide", "rayon",+ "tilecodec", ] [[package]]@@ -92,3 +93,33 @@ dependencies = [ "crossbeam-deque", "crossbeam-utils", ]++[[package]]+name = "ruzstd"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7c1c839d570d835527c9a5e4db7cb2198683a988cb9d7293fc8674e6bd58fc8"+dependencies = [+ "twox-hash",+]++[[package]]+name = "tilecodec"+version = "0.1.0"+dependencies = [+ "miniz_oxide",+ "ruzstd",+ "zstd-rs",+]++[[package]]+name = "twox-hash"+version = "2.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2"++[[package]]+name = "zstd-rs"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41514ccc30389f95bb9e6ab6d5634f17121c7b4fead6722a5fceec1c7891d78f"
scripts/maps/osm_ingest/Cargo.toml
diff --git a/scripts/maps/osm_ingest/Cargo.toml b/scripts/maps/osm_ingest/Cargo.tomlindex e8e7d9b093..289961127a 100644--- a/scripts/maps/osm_ingest/Cargo.toml+++ b/scripts/maps/osm_ingest/Cargo.toml@@ -62,6 +62,10 @@ rayon = "1" # that: materialisation walks ways in id order and a way's nodes are close together in a PBF. memmap2 = "0.9" +# Blocked-section writer for the v7 graph (`tilecodec::blocked`, write side).+# Host tool only — same pure-Rust bar as every other dependency here.+tilecodec = { path = "../../../library/tilecodec/src/main/rust", features = ["write"] }+ # `libc::statvfs` for the budget gate (`mem::disk_free_bytes`): already in the # lockfile via memmap2, so this adds a name to link, not a crate to fetch. [target.'cfg(target_os = "linux")'.dependencies]
scripts/maps/osm_ingest/src/graph_build.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build.rs b/scripts/maps/osm_ingest/src/graph_build.rsindex ecb520f3af..6b1cc0b585 100644--- a/scripts/maps/osm_ingest/src/graph_build.rs+++ b/scripts/maps/osm_ingest/src/graph_build.rs@@ -83,7 +83,13 @@ const GRAPH_MAGIC: u32 = 0x4752_414D; /// GB, and every value stays *exact*. /// Version 6 moves `name_offset` out of the record into a sparse side table — two /// thirds of edges have no name — taking the record to 7 bytes and planet to ~23.3 GB.-const GRAPH_VERSION: u32 = 6;+/// Version 7 blocked-compresses `nodes.bin`, `edges.bin` records and+/// `elevation.bin` (ZBLK sections: zstd frames over 4096-record blocks behind+/// a `u64` offset table). Same records, same order — only the container+/// changes. Readers accept 6 and 7; writers emit 7.+const GRAPH_VERSION: u32 = 7;+/// Oldest graph version accepted: v6 raw tables still decode.+const GRAPH_VERSION_MIN: u32 = 6; /// Geometry edges per coarse block in `intermediate.bin`'s two-level offset table /// — `INTERMEDIATE_BLOCK` in `graph.rs`, and the two must agree.
scripts/maps/osm_ingest/src/graph_build_part3.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build_part3.rs b/scripts/maps/osm_ingest/src/graph_build_part3.rsindex 45a5ec8484..176c10c91e 100644--- a/scripts/maps/osm_ingest/src/graph_build_part3.rs+++ b/scripts/maps/osm_ingest/src/graph_build_part3.rs@@ -233,7 +233,11 @@ fn write_graph( println!("Writing {edge_count} edge(s) in {rounds} round(s)..."); let chain_total = spill.chain_count()?; - let mut nodes_out = BufWriter::new(create(&out_dir.join("nodes.bin"))?);+ let mut nodes_blocked = tilecodec::blocked::BlockedStreamWriter::create(+ 12,+ &out_dir.join("nodes.blocked.tmp"),+ )+ .map_err(|e| Error(format!("cannot stage nodes.bin: {e}")))?; let mut edges_out = EdgeFile::create(out_dir, "edges.bin", edge_count)?; // `intermediate.bin` puts its blob at offset 0 and everything that indexes it@@ -326,7 +330,13 @@ fn write_graph( ); for v in lo..hi { let node = node_coords[v as usize];- write_node(&mut nodes_out, node.0, node.1, edge_ptr as u32).map_err(io_err)?;+ let mut rec = [0u8; 12];+ rec[0..4].copy_from_slice(&node.0.to_le_bytes());+ rec[4..8].copy_from_slice(&node.1.to_le_bytes());+ rec[8..12].copy_from_slice(&(edge_ptr as u32).to_le_bytes());+ nodes_blocked+ .push(&rec)+ .map_err(|e| Error(format!("cannot stage node record: {e}")))?; let degree_base = edge_ptr; while cursor < buffer.len() && buffer[cursor].source == v { let e = &buffer[cursor];@@ -404,8 +414,28 @@ fn write_graph( } // Trailing sentinel so `graph.rs` can read node(v + 1).edge_ptr as the end of // node v's edge range.- write_node(&mut nodes_out, 0, 0, edge_ptr as u32).map_err(io_err)?;- nodes_out.flush().map_err(io_err)?;+ let mut sentinel = [0u8; 12];+ sentinel[8..12].copy_from_slice(&(edge_ptr as u32).to_le_bytes());+ nodes_blocked+ .push(&sentinel)+ .map_err(|e| Error(format!("cannot stage node sentinel: {e}")))?;+ let nodes_bytes = nodes_blocked+ .finish()+ .map_err(|e| Error(format!("cannot finish nodes.bin: {e}")))?;+ // Sanity: the blocked section must unpack to exactly the pushed records.+ let parsed = tilecodec::blocked::Blocked::parse(&nodes_bytes).map_err(|e| {+ Error(format!(+ "freshly blocked nodes.bin does not parse: {e}"+ ))+ })?;+ if parsed.unpacked_len() != (u64::from(kept) + 1) * 12 {+ return Err(Error(format!(+ "nodes.bin unpacks to {} byte(s), not {} 12-byte records",+ parsed.unpacked_len(),+ u64::from(kept) + 1+ )));+ }+ std::fs::write(out_dir.join("nodes.bin"), &nodes_bytes).map_err(io_err)?; let escape_count = edges_out.escapes.len() as u64; let named_edges = edges_out.name_offsets.len() as u64; let edges_bytes = edges_out.finish(edge_count)?;@@ -428,18 +458,27 @@ fn write_graph( // elevation.bin: `i16[node_count]` metres, one per node in final-id order — an OPTIONAL sidecar // like road_names.bin/lanes.bin, so a build without a DEM simply omits it and the device reads // every node's elevation as 0. `node_coords` is already indexed by final node id, so a single- // forward pass matches the order `nodes.bin` was written in. No metadata count and no- // GRAPH_VERSION bump: the reader validates its length against node_count and disables it on a- // mismatch, exactly as it does for lanes.bin.+ // forward pass matches the order `nodes.bin` was written in. Blocked like+ // nodes/edges under the v7 layout (magic-dispatched on read, so absence+ // still reads as all-zero). if let Some(dem) = dem {- let mut elev_out = BufWriter::new(create(&out_dir.join("elevation.bin"))?);+ let mut elev_blocked = tilecodec::blocked::BlockedStreamWriter::create(+ 2,+ &out_dir.join("elevation.blocked.tmp"),+ )+ .map_err(|e| Error(format!("cannot stage elevation.bin: {e}")))?; for &(lat_e7, lon_e7) in node_coords { let lat = f64::from(lat_e7) * 1e-7; let lon = f64::from(lon_e7) * 1e-7; let metres = dem.sample_metres(lon, lat).unwrap_or(0);- elev_out.write_all(&metres.to_le_bytes()).map_err(io_err)?;+ elev_blocked+ .push(&metres.to_le_bytes())+ .map_err(|e| Error(format!("cannot stage elevation record: {e}")))?; }- elev_out.flush().map_err(io_err)?;+ let elev_bytes = elev_blocked+ .finish()+ .map_err(|e| Error(format!("cannot finish elevation.bin: {e}")))?;+ std::fs::write(out_dir.join("elevation.bin"), &elev_bytes).map_err(io_err)?; } Ok(Written {
scripts/maps/osm_ingest/src/graph_build_part4.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build_part4.rs b/scripts/maps/osm_ingest/src/graph_build_part4.rsindex 803946f5e5..4b7ec314af 100644--- a/scripts/maps/osm_ingest/src/graph_build_part4.rs+++ b/scripts/maps/osm_ingest/src/graph_build_part4.rs@@ -274,11 +274,11 @@ impl PresenceBitmap { } } -/// `edges.bin`, in five sections:+/// `edges.bin`, in five sections (v7: the record array is blocked): /// /// ```text-/// [ EdgeRec[E] ] 7 B: i16 target_delta, u24 dist_mm,-/// u8 type_, u8 speed_limit+/// [ ZBLK records[E] ] 7 B each, blocked zstd (see+/// `tilecodec::blocked`); v6 is raw E*7 /// [ pad to SECTION_ALIGN ] /// [ u32 escape_first[E.div_ceil(1024) + 1] ] first escape row of each block /// [ { u32 edge_idx, u32 target, u32 dist_mm } x escapes ] ascending by edge_idx@@ -300,14 +300,18 @@ impl PresenceBitmap { /// # Why the tables come last, and why they fit in memory /// /// Neither the escape count nor the named-edge count is known until the final round-/// has run, so a reserved prefix cannot be sized. But unlike `intermediate.bin` the-/// record array is a fixed stride, so this needs no trailer to be self-locating: the-/// reader computes all five offsets from `metadata.bin`'s counts. The escape rows-/// accumulate in memory — 39 MB at planet scale against `edges.bin`'s 8.6 GB — as do-/// the name offsets (1.6 GB, the largest of them) and the bitmap (134 MB).+/// has run, so a reserved prefix cannot be sized. The blocked record array is+/// likewise data-dependent in length, so — unlike the v6 fixed stride — the+/// reader cannot compute offsets from `metadata.bin`'s counts alone: it parses+/// the ZBLK header for the records' end, then the escapes and names exactly as+/// before. The escape rows accumulate in memory — 39 MB at planet scale against+/// `edges.bin`'s 8.6 GB — as do the name offsets (1.6 GB, the largest of them)+/// and the bitmap (134 MB). struct EdgeFile { path: PathBuf,- out: BufWriter<File>,+ /// Blocked record staging: 7 B records stream here (one block in memory,+ /// frames to scratch), finished into the file head at [`EdgeFile::finish`].+ blocked: tilecodec::blocked::BlockedStreamWriter, /// `(edge_idx, target, dist_mm)` for the edges a record cannot hold, in /// ascending `edge_idx` — which is the order they are pushed in, because the /// rounds ascend and each round writes its edges in index order.@@ -321,8 +325,10 @@ struct EdgeFile { } impl EdgeFile {- /// Byte size of the whole file. The reader computes it the same way, from- /// `metadata.bin`.+ /// Byte size of the whole file. Only the v6 fixed-stride layout is+ /// computable from counts; the v7 blocked layout is data-dependent, so+ /// this covers the trailer and the reader parses the records' end out of+ /// the ZBLK header instead. fn total_bytes(edge_count: u64, escapes: u64, named: u64) -> u64 { let rows = align_up(edge_count * EDGE_REC_BYTES, SECTION_ALIGN) + (edge_count.div_ceil(ESCAPE_BLOCK) + 1) * 4@@ -332,8 +338,10 @@ impl EdgeFile { fn create(dir: &Path, name: &str, edge_count: u64) -> Result<EdgeFile> { let path = dir.join(name);+ let scratch = dir.join(format!("{name}.blocked.tmp")); Ok(EdgeFile {- out: BufWriter::new(create(&path)?),+ blocked: tilecodec::blocked::BlockedStreamWriter::create(EDGE_REC_BYTES as usize, &scratch)+ .map_err(|e| Error(format!("cannot stage {}: {e}", scratch.display())))?, path, escapes: Vec::new(), named: PresenceBitmap::new(edge_count),@@ -356,9 +364,14 @@ impl EdgeFile { (TARGET_DELTA_ESCAPE, DIST_MM_ESCAPE) } };- self.out.write_all(&delta.to_le_bytes()).map_err(io_err)?;- self.out.write_all(&dist.to_le_bytes()[..3]).map_err(io_err)?;- self.out.write_all(&[type_, e.speed_limit]).map_err(io_err)?;+ let mut rec = [0u8; EDGE_REC_BYTES as usize];+ rec[0..2].copy_from_slice(&delta.to_le_bytes());+ rec[2..5].copy_from_slice(&dist.to_le_bytes()[..3]);+ rec[5] = type_;+ rec[6] = e.speed_limit;+ self.blocked+ .push(&rec)+ .map_err(|e| Error(format!("cannot stage edge record: {e}")))?; if e.name_offset != NO_NAME { self.named.set(self.pushed); self.name_offsets.push(e.name_offset);@@ -367,9 +380,10 @@ impl EdgeFile { Ok(()) } - /// Pad to the section boundary, then append the block index, the escape rows, the- /// name bitmap and the name offsets. Returns the finished file's size.- fn finish(mut self, edge_count: u64) -> Result<u64> {+ /// Finish the blocked records into the file head, then pad and append the+ /// block index, the escape rows, the name bitmap and the name offsets.+ /// Returns the finished file's size.+ fn finish(self, edge_count: u64) -> Result<u64> { if self.pushed != edge_count { return Err(Error(format!( "{} holds {} edge(s), not the {edge_count} the pack is sized for",@@ -377,8 +391,25 @@ impl EdgeFile { self.pushed ))); }- let mut at = edge_count * EDGE_REC_BYTES;- at = self.pad_to(at)?;+ let EdgeFile { path, blocked, escapes, named, name_offsets, pushed: _ } = self;+ let records = blocked+ .finish()+ .map_err(|e| Error(format!("cannot finish {}: {e}", path.display())))?;+ // Sanity: the blocked section must unpack to exactly the pushed records.+ let parsed = tilecodec::blocked::Blocked::parse(&records).map_err(|e| {+ Error(format!("freshly blocked {} does not parse: {e}", path.display()))+ })?;+ if parsed.unpacked_len() != edge_count * EDGE_REC_BYTES {+ return Err(Error(format!(+ "{} unpacks to {} byte(s), not {edge_count} 7-byte records",+ path.display(),+ parsed.unpacked_len()+ )));+ }+ let mut out = BufWriter::new(create(&path)?);+ out.write_all(&records).map_err(io_err)?;+ let mut at = records.len() as u64;+ at = pad_to(&mut out, &path, at)?; // `escape_first[b]` is the index of the first row in block `b`, i.e. the // count of rows below `b * ESCAPE_BLOCK`. The rows ascend, so one walk over@@ -388,61 +419,57 @@ impl EdgeFile { let mut row = 0usize; for b in 0..blocks { let limit = b * ESCAPE_BLOCK;- while row < self.escapes.len() && u64::from(self.escapes[row].0) < limit {+ while row < escapes.len() && u64::from(escapes[row].0) < limit { row += 1; }- self.out.write_all(&(row as u32).to_le_bytes()).map_err(io_err)?;+ out.write_all(&(row as u32).to_le_bytes()).map_err(io_err)?; }- if row != self.escapes.len() {+ if row != escapes.len() { return Err(Error(format!( "{}: the block index reached row {row} of {}, so a row is past the \ last block",- self.path.display(),- self.escapes.len()+ path.display(),+ escapes.len() ))); } at += blocks * 4; - for (idx, target, dist_mm) in &self.escapes {- self.out.write_all(&idx.to_le_bytes()).map_err(io_err)?;- self.out.write_all(&target.to_le_bytes()).map_err(io_err)?;- self.out.write_all(&dist_mm.to_le_bytes()).map_err(io_err)?;+ for (idx, target, dist_mm) in &escapes {+ out.write_all(&idx.to_le_bytes()).map_err(io_err)?;+ out.write_all(&target.to_le_bytes()).map_err(io_err)?;+ out.write_all(&dist_mm.to_le_bytes()).map_err(io_err)?; }- at += self.escapes.len() as u64 * 12;- self.pad_to(at)?;+ at += escapes.len() as u64 * 12;+ at = pad_to(&mut out, &path, at)?; - let named = self.named.write(&mut self.out)?;- if named != self.name_offsets.len() as u64 {+ let named = named.write(&mut out)?;+ if named != name_offsets.len() as u64 { return Err(Error(format!( "{}: the name bitmap has {named} bit(s) set but {} offset(s) were \ collected",- self.path.display(),- self.name_offsets.len()+ path.display(),+ name_offsets.len() ))); }- for off in &self.name_offsets {- self.out.write_all(&off.to_le_bytes()).map_err(io_err)?;+ for off in &name_offsets {+ out.write_all(&off.to_le_bytes()).map_err(io_err)?; }- self.out.flush().map_err(io_err)?;+ out.flush().map_err(io_err)?; - let want = EdgeFile::total_bytes(edge_count, self.escapes.len() as u64, named);- let got = std::fs::metadata(&self.path)- .map_err(|e| Error(format!("cannot stat {}: {e}", self.path.display())))?+ let got = std::fs::metadata(&path)+ .map_err(|e| Error(format!("cannot stat {}: {e}", path.display())))? .len();- if got != want {- return Err(Error(format!(- "{} came out {got} byte(s) long, not the {want} the reader will compute",- self.path.display()- )));- }- Ok(want)+ Ok(got) }+} - /// Write zeroes up to the next section boundary, returning the new offset.- fn pad_to(&mut self, at: u64) -> Result<u64> {- let aligned = align_up(at, SECTION_ALIGN);- let zeroes = [0u8; SECTION_ALIGN as usize];- self.out.write_all(&zeroes[..(aligned - at) as usize]).map_err(io_err)?;- Ok(aligned)- }+/// Write zeroes up to the next section boundary, returning the new offset.+///+/// Free function (not a method): [`EdgeFile::finish`] destructures `self`+/// before the trailer, so there is no receiver left to hang it on.+fn pad_to(out: &mut BufWriter<File>, path: &Path, at: u64) -> Result<u64> {+ let aligned = align_up(at, SECTION_ALIGN);+ let zeroes = [0u8; SECTION_ALIGN as usize];+ out.write_all(&zeroes[..(aligned - at) as usize]).map_err(io_err)?;+ Ok(aligned) }
scripts/maps/osm_ingest/src/graph_build_part6.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build_part6.rs b/scripts/maps/osm_ingest/src/graph_build_part6.rsindex 33cd986483..ea29fb1424 100644--- a/scripts/maps/osm_ingest/src/graph_build_part6.rs+++ b/scripts/maps/osm_ingest/src/graph_build_part6.rs@@ -13,16 +13,64 @@ fn read_outputs(dir: &Path) -> Outputs { let f = |n: &str| std::fs::read(dir.join(n)).unwrap();+ let meta = f("metadata.bin");+ let edge_count = u64::from_le_bytes(meta[16..24].try_into().unwrap());+ // v7 stores the record arrays as ZBLK sections. The helpers below+ // mirror the device's raw-table reads, so the boundary inflates back+ // to the v6 shape (records + original tail): the container has its+ // own unit tests in tilecodec, and these tests own the content.+ // `local_of`/`node_at` read nodes the same way.+ let nodes = unpack_or_raw(&f("nodes.bin"));+ let edges_raw = f("edges.bin");+ let edges = match tilecodec::blocked::Blocked::parse(&edges_raw) {+ Ok(v) => {+ if v.unpacked_len() != edge_count * 7 || v.record_len() != 7 {+ panic!("blocked edges unpack to the wrong records");+ }+ let mut cache = tilecodec::blocked::BlockCache::new(0);+ let mut recs = Vec::with_capacity(v.unpacked_len() as usize);+ for b in 0..v.block_count() {+ recs
Diff truncated.