maps: graph v9, block-compressed shape points, names, name offsets (#planet5)
- Commit
429b1d19ef063231f443086fc8f6ba341e997fe4- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-14 14:59 UTC (21 days ago)
- Parents
53c3ca0
Graph v9 = v8 plus zstd block sections for the cold graph payloads: - intermediate.bin: the varint shape-point blob becomes a tilecodec ZSEC section (64 KiB zstd-19 blocks); the trailer (presence bitmap, rank, coarse/within offsets) stays raw and still addresses the raw blob, so geometry_offset is unchanged. The loader checks the ZSEC table and that its raw length is the trailer's sentinel. - road_names.bin: a ZSEC section of the string pool. - edges.bin: its tail, the u32 name-offset table (one per named edge, 1.1 GB raw on the planet), becomes a ZSEC section. - nodes.bin / edges.bin record blocks are column-wise ZBLK (previous commit); graph_thin re-blocks row inputs. Reader: graph_zsec.rs's ZsecRegion reads raw byte ranges / C strings through a per-thread 16 MiB block cache with a last-block fast path; decode_edge_coords, cstr_at and edge_name_offset use it under v9 and the raw mmap paths otherwise. Both loaders (multi-file and archive) handle v9; v6-v8 load exactly as before; a v8 reader refuses v9. tilecodec::zsec::block_of decodes one block in O(1) (ZSec::parse walks the whole table, which a per-miss call must not do). Writer: graph_thin --v9 (= --v8 thinning and varint, then the block compression above). mamaps_pack and ArchiveView accept v9 and check the name-offset table's ZSEC header against the named-edge count. US West (978 routable pairs): graph 866 -> 615 MB (nodes 198 -> 86, edges 293 -> 211, intermediate 325 -> 286, names 15.5 -> 5.2 MB); route_diff report byte-identical to v8. Planet projection about -4.0 GB (nodes -1.48, edges -1.2, intermediate -1.16, names -0.15). Verified: cargo test -p offlinerouter (93), tile_build, mamaps_build (293), tilecodec (198); route_diff on the US West v9 graph.
Diff
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 5035d1c00e..43383cd7b6 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs@@ -53,13 +53,18 @@ pub const ARCHIVE_KIND_MAX_KNOWN: u8 = ARCHIVE_KIND_POI_ADMIN; pub const GRAPH_MAGIC: u32 = 0x4752_414D; /// Newest (and only, for the single archive) graph version: v7 blocked record /// sections (nodes, edges records, elevation).-pub const GRAPH_VERSION: u32 = 8;+pub const GRAPH_VERSION: u32 = 9; /// First graph version whose nodes/edges/elevation are ZBLK blocked (v7 and later). pub const GRAPH_VERSION_BLOCKED: u32 = 7; /// Planet5: `intermediate.bin` blobs are zigzag-varint deltas on a 1e-6 degree grid (rather /// than fixed `i16` 1e-7 degree deltas), thinned to a 1 m bound, with 16 geometry edges per /// coarse block (`INTERMEDIATE_BLOCK_V8`) so a block's span still fits the `u16` within-table. pub const GRAPH_VERSION_VARINT: u32 = 8;+/// Planet5 (~50 GB revision): v8 plus (a) `nodes.bin`/`edges.bin` ZBLK blocks stored column-wise+/// ([`crate::blocked::BLOCKED_FLAG_COLUMNS`]) and (b) `intermediate.bin`'s blob and+/// `road_names.bin` stored as [`crate::zsec`] sections (zstd blocks; the intermediate trailer stays+/// raw and addresses the raw blob). A v8 reader refuses v9 by version.+pub const GRAPH_VERSION_ZSEC: u32 = 9; /// 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.
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 02e3f39628..2d5a046124 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs@@ -104,7 +104,7 @@ pub use consts::{ ARCHIVE_KIND_GRAPH_NODES, ARCHIVE_KIND_GRAPH_OVERLAY, ARCHIVE_KIND_MAX_KNOWN, ARCHIVE_KIND_POI_ATTRS, ARCHIVE_KIND_POI_ADMIN, ARCHIVE_KIND_POI_INDEX, ARCHIVE_KIND_POI_NAMES, ARCHIVE_KIND_POI_REGION, ARCHIVE_KIND_POI_SPATIAL, ARCHIVE_KIND_POI_WORDS, ARCHIVE_KIND_TRANSIT, GRAPH_MAGIC,- GRAPH_META_LEN, GRAPH_VERSION, GRAPH_VERSION_BLOCKED, GRAPH_VERSION_MIN, GRAPH_VERSION_VARINT,+ GRAPH_META_LEN, GRAPH_VERSION, GRAPH_VERSION_BLOCKED, GRAPH_VERSION_MIN, GRAPH_VERSION_VARINT, GRAPH_VERSION_ZSEC, POI_RECORD_BYTES, TRANSIT_MAGIC, TRANSIT_VERSION, TRANSIT_VERSION_MIN, TRANSIT_VERSION_ZSEC, TRANSIT_ZSEC_FLAG, }; pub use entry::{is_known_kind, 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 47179fedbd..897a0a9b40 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/view.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/view.rs@@ -187,12 +187,12 @@ impl ArchiveView { ) }); let meta = slice(ARCHIVE_KIND_GRAPH_META)?;- let (node_count, edge_count, escape_count, named_edges, blocked_v7) = match meta {+ let (node_count, edge_count, escape_count, named_edges, blocked_v7, zsec_v9) = match meta { None => { if graph_present { return err("a single-archive carries graph sections but no graph meta"); }- (0, 0, 0, 0, false)+ (0, 0, 0, 0, false, false) } Some(m) => { if m.len() as u64 != GRAPH_META_LEN {@@ -227,7 +227,7 @@ impl ArchiveView { return err("a single-archive graph node count overflows u32"); } let _ = header;- (n, e, esc, named, graph_version >= GRAPH_VERSION_BLOCKED)+ (n, e, esc, named, graph_version >= GRAPH_VERSION_BLOCKED, graph_version >= GRAPH_VERSION_ZSEC) } }; // Nodes: (N+1) 12-byte records (the sentinel). Under v7 a ZBLK@@ -272,7 +272,14 @@ impl ArchiveView { let present = edge_count.div_ceil(8); let name_off_off = names_off + rank + present; let want = name_off_off + named_edges * 4;- if b.len() as u64 != want {+ if zsec_v9 && named_edges > 0 {+ // v9: the name-offset table is a ZSEC section of the raw table, last in the file.+ let tail = b.get(name_off_off as usize..).unwrap_or(&[]);+ match crate::zsec::ZSec::parse(tail) {+ Ok(z) if z.raw_len() == named_edges * 4 => {}+ _ => return err("a single-archive v9 edges section's name-offset table is not the ZSEC section it claims"),+ }+ } else if b.len() as u64 != want { return err(format!( "a single-archive edges section is {} bytes, want {want}", b.len()
library/tilecodec/src/main/rust/src/zsec.rs
diff --git a/library/tilecodec/src/main/rust/src/zsec.rs b/library/tilecodec/src/main/rust/src/zsec.rsindex cd9263f524..5895e6b54e 100644--- a/library/tilecodec/src/main/rust/src/zsec.rs+++ b/library/tilecodec/src/main/rust/src/zsec.rs@@ -135,6 +135,27 @@ impl<'a> ZSec<'a> { } } +/// Block `b` of a section that [`ZSec::parse`] already validated, in O(1): the header and the+/// two offsets are read directly instead of re-walking the whole offset table (which `parse`+/// does, and which made every cache miss on a big section cost O(blocks)).+pub fn block_of(bytes: &[u8], b: usize) -> Result<Vec<u8>> {+ if bytes.len() < ZSEC_HEADER_LEN {+ return err("not a ZSEC section");+ }+ let u32_at = |o: usize| u32::from_le_bytes(bytes[o..o + 4].try_into().unwrap());+ let z = ZSec {+ bytes,+ block_size: u32_at(4) as usize,+ raw_len: u64::from_le_bytes(bytes[8..16].try_into().unwrap()),+ block_count: u32_at(16) as usize,+ codec: u32_at(20),+ };+ if ZSEC_HEADER_LEN + (b + 2) * 8 > bytes.len() {+ return err("a ZSEC block index past its table");+ }+ z.block(b)+}+ /// Compress `raw` into a ZSEC section: `block_size` blocks, zstd `level`, blocks compressed on /// all cores (each is independent, so the output is the same at any thread count). #[cfg(feature = "write")]
maps/src/main/rust/examples/graph_thin.rs
diff --git a/maps/src/main/rust/examples/graph_thin.rs b/maps/src/main/rust/examples/graph_thin.rsindex c1d3ac98f3..34ec9737dd 100644--- a/maps/src/main/rust/examples/graph_thin.rs+++ b/maps/src/main/rust/examples/graph_thin.rs@@ -74,12 +74,39 @@ fn zz(v: i64) -> u64 { ((v << 1) ^ (v >> 63)) as u64 } +/// A ZBLK section (plus any trailing tables) with column-transformed blocks; unchanged when its+/// blocks already are.+fn columns_blocked(raw: &[u8]) -> Vec<u8> {+ let v = tilecodec::blocked::Blocked::parse(raw).expect("a ZBLK section");+ if v.flags() & tilecodec::blocked::BLOCKED_FLAG_COLUMNS != 0 {+ return raw.to_vec();+ }+ let end = v.block_offset(v.block_count()).expect("end") as usize;+ let mut records = Vec::with_capacity(v.unpacked_len() as usize);+ for b in 0..v.block_count() {+ records.extend_from_slice(&v.block(b).expect("block"));+ }+ let mut out = tilecodec::blocked::write_blocked_columns(&records, v.record_len());+ // Trailing tables (edges.bin's escapes and names) start at the next 8-byte boundary after+ // the records, in the old file and in the new one alike.+ let tail = end.div_ceil(8) * 8;+ if tail < raw.len() {+ out.resize(out.len().div_ceil(8) * 8, 0);+ out.extend_from_slice(&raw[tail..]);+ }+ out+}+ fn main() -> std::process::ExitCode { let all: Vec<String> = std::env::args().skip(1).collect(); // `--v8`: write the planet5 layout (graph v8: zigzag-varint deltas on a 1e-6 degree grid, // INTERMEDIATE_BLOCK_V8 per coarse entry, no i16 bridging needed). Without it the v7 layout.- let v8 = all.iter().any(|x| x == "--v8");- let a: Vec<String> = all.into_iter().filter(|x| x != "--v8").collect();+ // `--v9`: v8's encoding, then graph v9's block compression: the intermediate blob and+ // road_names.bin become ZSEC sections (64 KiB zstd-19 blocks) and nodes.bin/edges.bin ZBLK+ // blocks are column-transformed when the input still has row blocks.+ let v9 = all.iter().any(|x| x == "--v9");+ let v8 = v9 || all.iter().any(|x| x == "--v8");+ let a: Vec<String> = all.into_iter().filter(|x| x != "--v8" && x != "--v9").collect(); if a.len() < 3 { eprintln!("usage: graph_thin IN_GRAPH_DIR OUT_GRAPH_DIR TOL_CM"); return std::process::ExitCode::from(2);@@ -304,10 +331,32 @@ fn main() -> std::process::ExitCode { if name == "intermediate.bin" || !f.file_type().unwrap().is_file() { continue; }+ if v9 && name == "road_names.bin" {+ let raw = std::fs::read(f.path()).expect("read road_names");+ let z = if raw.is_empty() { raw } else { tilecodec::zsec::write_zsec(&raw, tilecodec::zsec::ZSEC_BLOCK, 19) };+ std::fs::write(format!("{outp}/{name}"), &z).expect("write road_names");+ continue;+ }+ if v9 && (name == "nodes.bin" || name == "edges.bin") {+ let raw = std::fs::read(f.path()).expect("read blocked");+ let mut out = columns_blocked(&raw);+ if name == "edges.bin" {+ // The name-offset table (u32 per named edge, the file's tail) becomes a ZSEC+ // section: 1.1 GB raw on the planet, read only to word instructions.+ let named = read_u64(&meta, 32) as usize;+ if named > 0 {+ let at = out.len() - named * 4;+ let table = out.split_off(at);+ out.extend_from_slice(&tilecodec::zsec::write_zsec(&table, tilecodec::zsec::ZSEC_BLOCK, 19));+ }+ }+ std::fs::write(format!("{outp}/{name}"), out).expect("write blocked");+ continue;+ } std::fs::copy(f.path(), format!("{outp}/{name}")).expect("copy"); }- let mut out = blob;- let new_blob = out.len();+ let new_blob = blob.len();+ let mut out = if v9 { tilecodec::zsec::write_zsec(&blob, tilecodec::zsec::ZSEC_BLOCK, 19) } else { blob }; out.extend_from_slice(bitmap); for c in &coarse { out.extend_from_slice(&c.to_le_bytes());@@ -318,7 +367,7 @@ fn main() -> std::process::ExitCode { out.extend_from_slice(&gcount.to_le_bytes()); std::fs::write(format!("{outp}/intermediate.bin"), &out).expect("write"); let mut meta_out = meta.clone();- let out_version: u32 = if v8 { 8 } else { in_version.min(7) };+ let out_version: u32 = if v9 { 9 } else if v8 { 8 } else { in_version.min(7) }; meta_out[4..8].copy_from_slice(&out_version.to_le_bytes()); std::fs::write(format!("{outp}/metadata.bin"), &meta_out).expect("write metadata"); // Validate by loading the result with the real reader.
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 ff1e72ec11..d1b90fd1f4 100644--- a/maps/src/main/rust/src/graph.rs+++ b/maps/src/main/rust/src/graph.rs@@ -447,6 +447,7 @@ pub(crate) unsafe fn read_at<T: Copy>(base: *const u8, idx: usize) -> T { } include!("graph_part1.rs");+include!("graph_zsec.rs"); include!("graph_part2.rs"); include!("graph_part2b.rs"); include!("graph_part3.rs");
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 4e46f366f9..2295eaf208 100644--- a/maps/src/main/rust/src/graph_part1.rs+++ b/maps/src/main/rust/src/graph_part1.rs@@ -37,6 +37,9 @@ pub struct Graph { pub escape_count: u64, names: EdgeBitmap, name_off: *const u8, // u32[named_edges], indexed by rank in `names`+ // Graph v9: the `name_off` table is a ZSEC section of the raw u32 table (the file's last+ // section); `name_off` then points at it and reads go through the block cache.+ name_off_zsec: Option<ZsecRegion>, /// Edges with a name at all. Validated against the rank index's total at load. pub named_edges: u64, @@ -52,6 +55,9 @@ pub struct Graph { // degree deltas, INTERMEDIATE_BLOCK per entry. intermediate_varint: bool, intermediate_block: u64,+ // Graph v9: the blob is a ZSEC section (read through [`ZsecRegion`]); the trailer is raw+ // and its offsets address the *raw* blob.+ intermediate_zsec: Option<ZsecRegion>, // Real OSM turn-lane data (see `edge_lane_masks`). Sparse: only the edges that // actually carry `turn:lanes` appear, which on a planet is 2.9 M of 1.07 G.@@ -63,6 +69,8 @@ pub struct Graph { road_names: *const u8, pub road_names_size: usize,+ // Graph v9: `road_names.bin` is a ZSEC section; `road_names_size` is then its raw length.+ road_names_zsec: Option<ZsecRegion>, // `elevation.bin`, an OPTIONAL `i16[node_count]` of per-node ground elevation in metres, baked // from the DEM at graph-build time (WS-G route profile). Null when the file is absent or its@@ -103,6 +111,8 @@ pub struct Graph { /// exactly like the raw tables. No lifetime ties the two structs together. pub(crate) struct BlockedView { record_len: usize,+ /// Blocks are column-transformed (ZBLK flag, graph v9): inverse after the inflate.+ columns: bool, records_per_block: u64, /// `log2(records_per_block)` when it is a power of two (always, for packs /// the writer produces), so the hot lookup shifts instead of dividing.@@ -139,6 +149,7 @@ impl BlockedView { // still refused by the shared parse โ an offset past the bytes fails. Some(BlockedView { record_len: shared.record_len(),+ columns: shared.flags() & tilecodec::blocked::BLOCKED_FLAG_COLUMNS != 0, records_per_block, block_shift: records_per_block .is_power_of_two()@@ -173,6 +184,9 @@ impl BlockedView { let frame = unsafe { std::slice::from_raw_parts(self.frames.add(start), end - start) }; // The shared ZBLK frame decode (same code the writer's reader runs). match tilecodec::blocked::inflate_frame(frame, want) {+ Ok(out) if out.len() == want && self.columns => {+ tilecodec::blocked::columns_inverse(&out, self.record_len).into_boxed_slice()+ } Ok(out) if out.len() == want => out.into_boxed_slice(), _ => Box::default(), }
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 733ef6fdd5..46cfc19825 100644--- a/maps/src/main/rust/src/graph_part2.rs+++ b/maps/src/main/rust/src/graph_part2.rs@@ -39,7 +39,7 @@ 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, blocked_v7, varint_v8) = {+ let (node_count, edge_count, escape_count, named_edges, blocked_v7, varint_v8, zsec_v9) = { let meta = MmapRegion::map(&format!("{base}metadata.bin"))?; if meta.len < 40 { return None;@@ -69,6 +69,7 @@ impl Graph { named, version >= tilecodec::mamaps::archive::GRAPH_VERSION_BLOCKED, version >= tilecodec::mamaps::archive::GRAPH_VERSION_VARINT,+ version >= tilecodec::mamaps::archive::GRAPH_VERSION_ZSEC, ) }; let intermediate_block = if varint_v8 { INTERMEDIATE_BLOCK_V8 } else { INTERMEDIATE_BLOCK };@@ -144,9 +145,28 @@ impl Graph { ); let name_off_off = names_off + EdgeBitmap::bytes(edge_count); let want_edges = name_off_off + named_edges * std::mem::size_of::<u32>() as u64;- if edges_region.len as u64 != want_edges {- return None;- }+ // Graph v9: the name-offset table (the file's tail) is a ZSEC section of that table.+ let name_off_zsec = if zsec_v9 && named_edges > 0 {+ if (edges_region.len as u64) <= name_off_off {+ return None;+ }+ let tail = unsafe {+ std::slice::from_raw_parts(+ edges_region.base().add(name_off_off as usize),+ edges_region.len - name_off_off as usize,+ )+ };+ let z = ZsecRegion::parse(tail)?;+ if z.raw_len() as u64 != named_edges * 4 {+ return None;+ }+ Some(z)+ } else {+ if edges_region.len as u64 != want_edges {+ return None;+ }+ None+ }; // Table base is the file base unconditionally: only the record array // itself is blocked-compressed under v7 (see the single-archive // `assemble` โ same fix, same on-device SIGSEGV). The per-record@@ -228,15 +248,30 @@ impl Graph { (geometry_edges / intermediate_block) as usize, ) + u64::from(read_at::<u16>(intermediate_within, geometry_edges as usize)) };- if sentinel != blob_bytes || geometry.total(edge_count) != geometry_edges {+ // Graph v9: the blob is a ZSEC section of the raw blob the trailer addresses.+ let intermediate_zsec = if zsec_v9 {+ let z = ZsecRegion::parse(unsafe { std::slice::from_raw_parts(intermediate_data, blob_bytes as usize) })?;+ Some(z)+ } else {+ None+ };+ let raw_blob = intermediate_zsec.as_ref().map_or(blob_bytes, |z| z.raw_len() as u64);+ if sentinel != raw_blob || geometry.total(edge_count) != geometry_edges { return None; } let road_names_region = MmapRegion::map(&format!("{base}road_names.bin"));- let (road_names, road_names_size) = match &road_names_region {+ let (road_names, mut road_names_size) = match &road_names_region { Some(r) => (r.base(), r.len), None => (ptr::null(), 0), };+ let road_names_zsec = if zsec_v9 && !road_names.is_null() && road_names_size > 0 {+ let z = ZsecRegion::parse(unsafe { std::slice::from_raw_parts(road_names, road_names_size) })?;+ road_names_size = z.raw_len();+ Some(z)+ } else {+ None+ }; // lanes.bin: [ u32 n ][ LaneEntry[n + 1] ][ u16 lane-mask blob ]. The index // is sized by its own header rather than by `edge_count`, so it is validated@@ -384,6 +419,7 @@ impl Graph { escape_count, names, name_off,+ name_off_zsec, named_edges, intermediate_data, geometry,@@ -391,11 +427,13 @@ impl Graph { intermediate_within, intermediate_varint: varint_v8, intermediate_block,+ intermediate_zsec, lane_index, lane_edges, lane_data, road_names, road_names_size,+ road_names_zsec, elevation, nodes_view, edges_view,
maps/src/main/rust/src/graph_part3.rs
diff --git a/maps/src/main/rust/src/graph_part3.rs b/maps/src/main/rust/src/graph_part3.rsindex 6e2676a999..c8d762ed38 100644--- a/maps/src/main/rust/src/graph_part3.rs+++ b/maps/src/main/rust/src/graph_part3.rs@@ -18,7 +18,13 @@ impl Graph { if !self.names.contains(idx) { return None; }- Some(unsafe { read_at::<u32>(self.name_off, self.names.rank_of(idx) as usize) })+ let rank = self.names.rank_of(idx) as usize;+ if let Some(z) = &self.name_off_zsec {+ let mut b = Vec::with_capacity(4);+ z.read_into(rank * 4, 4, &mut b);+ return (b.len() == 4).then(|| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));+ }+ Some(unsafe { read_at::<u32>(self.name_off, rank) }) } /// Real OSM per-lane turn-indication masks for directed edge `idx`, ordered@@ -103,6 +109,9 @@ impl Graph { /// Read the NUL-terminated string starting at byte `offset` in the pool. fn cstr_at(&self, offset: usize) -> String {+ if let Some(z) = &self.road_names_zsec {+ return String::from_utf8_lossy(&z.cstr_at(offset)).into_owned();+ } unsafe { let start = self.road_names.add(offset); let mut len = 0usize;@@ -270,7 +279,17 @@ impl Graph { if self.intermediate_varint { // v8: zigzag varint deltas on the 1e-6 degree grid, seeded from the source node's // own grid position. Each decoded point lands on a multiple of 10 e7 units.- let blob = unsafe { std::slice::from_raw_parts(data, byte_len as usize) };+ // v9: the same bytes, read out of the ZSEC blob.+ let copied;+ let blob: &[u8] = match &self.intermediate_zsec {+ Some(z) => {+ let mut v = Vec::with_capacity(byte_len as usize);+ z.read_into(data_off as usize, byte_len as usize, &mut v);+ copied = v;+ &copied+ }+ None => unsafe { std::slice::from_raw_parts(data, byte_len as usize) },+ }; let mut qlat = (lat as i64).div_euclid(10) + i64::from((lat as i64).rem_euclid(10) >= 5); let mut qlon = (lon as i64).div_euclid(10) + i64::from((lon as i64).rem_euclid(10) >= 5); let mut at = 0usize;
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 63a5566d84..cd05ae839c 100644--- a/maps/src/main/rust/src/graph_part4.rs+++ b/maps/src/main/rust/src/graph_part4.rs@@ -113,6 +113,7 @@ impl Graph { let named_edges = named; let blocked_v7 = version >= tilecodec::mamaps::archive::GRAPH_VERSION_BLOCKED; let varint_v8 = version >= tilecodec::mamaps::archive::GRAPH_VERSION_VARINT;+ let zsec_v9 = version >= tilecodec::mamaps::archive::GRAPH_VERSION_ZSEC; let intermediate_block = if varint_v8 { INTERMEDIATE_BLOCK_V8 } else { INTERMEDIATE_BLOCK }; // `edge_count` comes from the header rather than from the edges@@ -171,9 +172,22 @@ impl Graph { ); let name_off_off = names_off + EdgeBitmap::bytes(edge_count); let want_edges = name_off_off + named_edges * std::mem::size_of::<u32>() as u64;- if edges_bytes.len() as u64 != want_edges {- return None;- }+ // Graph v9: the name-offset table (the payload's tail) is a ZSEC section of that table.+ let name_off_zsec = if zsec_v9 && named_edges > 0 {+ if (edges_bytes.len() as u64) <= name_off_off {+ return None;+ }+ let z = ZsecRegion::parse(&edges_bytes[name_off_off as usize..])?;+ if z.raw_len() as u64 != named_edges * 4 {+ return None;+ }+ Some(z)+ } else {+ if edges_bytes.len() as u64 != want_edges {+ return None;+ }+ None+ }; // The escape index, escape rows and name tables live behind the // record array in the same payload, raw in both v6 and v7 โ only the // record array itself is blocked-compressed. So the table base is the@@ -271,14 +285,29 @@ impl Graph { (geometry_edges / intermediate_block) as usize, ) + u64::from(read_at::<u16>(intermediate_within, geometry_edges as usize)) };- if sentinel != blob_bytes || geometry.total(edge_count) != geometry_edges {+ // Graph v9: the blob is a ZSEC section of the raw blob the trailer addresses.+ let intermediate_zsec = if zsec_v9 {+ let z = ZsecRegion::parse(unsafe { std::slice::from_raw_parts(intermediate_data, blob_bytes as usize) })?;+ Some(z)+ } else {+ None+ };+ let raw_blob = intermediate_zsec.as_ref().map_or(blob_bytes, |z| z.raw_len() as u64);+ if sentinel != raw_blob || geometry.total(edge_count) != geometry_edges { return None; } - let (road_names, road_names_size) = match sections.road_names {+ let (road_names, mut road_names_size) = match sections.road_names { Some(b) => (b.as_ptr(), b.len()), None => (ptr::null(), 0), };+ let road_names_zsec = if zsec_v9 && !road_names.is_null() && road_names_size > 0 {+ let z = ZsecRegion::parse(unsafe { std::slice::from_raw_parts(road_names, road_names_size) })?;+ road_names_size = z.raw_len();+ Some(z)+ } else {+ None+ }; // Lanes payload: [ u32 n ][ LaneEntry[n + 1] ][ u16 lane-mask blob ]. // The index is sized by its own header rather than by `edge_count`, so@@ -455,6 +484,7 @@ impl Graph { escape_count, names, name_off,+ name_off_zsec, named_edges, intermediate_data, geometry,@@ -462,11 +492,13 @@ impl Graph { intermediate_within, intermediate_varint: varint_v8, intermediate_block,+ intermediate_zsec, lane_index, lane_edges, lane_data, road_names, road_names_size,+ road_names_zsec, elevation, nodes_view, edges_view,
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 c05e371e5e..b8249e81bb 100644--- a/maps/src/main/rust/src/graph_part5.rs+++ b/maps/src/main/rust/src/graph_part5.rs@@ -187,7 +187,7 @@ mod archive_tests { vec![ ( ARCHIVE_KIND_GRAPH_META,- meta_at(GRAPH_VERSION, 1, 0, 0, 0),+ meta_at(tilecodec::mamaps::archive::GRAPH_VERSION_VARINT, 1, 0, 0, 0), 0, ), (ARCHIVE_KIND_GRAPH_NODES, nodes, 1),@@ -237,7 +237,7 @@ mod archive_tests { vec![ ( ARCHIVE_KIND_GRAPH_META,- meta_at(GRAPH_VERSION, 2, 1, 0, 0),+ meta_at(tilecodec::mamaps::archive::GRAPH_VERSION_VARINT, 2, 1, 0, 0), 0, ), (ARCHIVE_KIND_GRAPH_NODES, nodes, 1),
maps/src/main/rust/src/graph_zsec.rs
diff --git a/maps/src/main/rust/src/graph_zsec.rs b/maps/src/main/rust/src/graph_zsec.rsnew file mode 100644index 0000000000..1622e2c296--- /dev/null+++ b/maps/src/main/rust/src/graph_zsec.rs@@ -0,0 +1,125 @@+// Planet5 graph v9: `intermediate.bin`'s blob and `road_names.bin` are tilecodec ZSEC sections+// (64 KiB zstd blocks). Bytes are read by raw position through a per-thread block cache, so a+// lookup inflates at most the one or two blocks it spans, and a route's or a snap's+// neighbouring edges -- stored next to each other, the nodes being curve-sorted -- hit it.++static NEXT_GRAPH_ZSEC_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);++/// Decoded bytes a thread keeps across every graph region (16 MiB).+const GRAPH_ZSEC_CACHE_BYTES: usize = 16 << 20;++/// One ZSEC region inside a mapping the graph owns (raw pointer, like every other table).+pub(crate) struct ZsecRegion {+ base: *const u8,+ len: usize,+ block_size: usize,+ raw_len: usize,+ uid: u64,+}++unsafe impl Send for ZsecRegion {}+unsafe impl Sync for ZsecRegion {}++struct GraphZsecCache {+ map: std::collections::HashMap<(u64, u32), std::rc::Rc<Vec<u8>>>,+ order: std::collections::VecDeque<(u64, u32)>,+ bytes: usize,+ last: Option<((u64, u32), std::rc::Rc<Vec<u8>>)>,+}++thread_local! {+ static GRAPH_ZSEC_BLOCKS: std::cell::RefCell<GraphZsecCache> = std::cell::RefCell::new(GraphZsecCache {+ map: std::collections::HashMap::new(),+ order: std::collections::VecDeque::new(),+ bytes: 0,+ last: None,+ });+}++impl ZsecRegion {+ /// Validate `bytes` as a whole ZSEC section (header, codec, full offset table).+ pub(crate) fn parse(bytes: &[u8]) -> Option<ZsecRegion> {+ let z = tilecodec::zsec::ZSec::parse(bytes).ok()?;+ Some(ZsecRegion {+ base: bytes.as_ptr(),+ len: bytes.len(),+ block_size: z.block_size(),+ raw_len: usize::try_from(z.raw_len()).ok()?,+ uid: NEXT_GRAPH_ZSEC_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),+ })+ }++ pub(crate) fn raw_len(&self) -> usize {+ self.raw_len+ }++ fn block(&self, b: u32) -> std::rc::Rc<Vec<u8>> {+ let key = (self.uid, b);+ GRAPH_ZSEC_BLOCKS.with(|cell| {+ let mut c = cell.borrow_mut();+ if let Some((k, v)) = &c.last {+ if *k == key {+ return v.clone();+ }+ }+ if let Some(v) = c.map.get(&key).cloned() {+ c.last = Some((key, v.clone()));+ return v;+ }+ let bytes = unsafe { std::slice::from_raw_parts(self.base, self.len) };+ // Validated at open; a failure here is corruption the open could not see.+ let v = std::rc::Rc::new(tilecodec::zsec::block_of(bytes, b as usize).unwrap_or_default());+ c.bytes += v.len();+ while c.bytes > GRAPH_ZSEC_CACHE_BYTES {+ let Some(old) = c.order.pop_front() else { break };+ if let Some(o) = c.map.remove(&old) {+ c.bytes -= o.len();+ }+ }+ c.order.push_back(key);+ c.map.insert(key, v.clone());+ c.last = Some((key, v.clone()));+ v+ })+ }++ /// `len` raw bytes at `pos` appended to `out` (clamped to the raw length).+ pub(crate) fn read_into(&self, pos: usize, len: usize, out: &mut Vec<u8>) {+ let end = (pos + len).min(self.raw_len);+ let mut p = pos;+ while p < end {+ let blk = self.block((p / self.block_size) as u32);+ let off = p % self.block_size;+ let n = (end - p).min(blk.len().saturating_sub(off));+ if n == 0 {+ break;+ }+ out.extend_from_slice(&blk[off..off + n]);+ p += n;+ }+ }++ /// The NUL-terminated string at raw position `pos`.+ pub(crate) fn cstr_at(&self, pos: usize) -> Vec<u8> {+ let mut out = Vec::new();+ let mut p = pos;+ while p < self.raw_len {+ let blk = self.block((p / self.block_size) as u32);+ let off = p % self.block_size;+ if off >= blk.len() {+ break;+ }+ match blk[off..].iter().position(|&b| b == 0) {+ Some(i) => {+ out.extend_from_slice(&blk[off..off + i]);+ return out;+ }+ None => {+ out.extend_from_slice(&blk[off..]);+ p += blk.len() - off;+ }+ }+ }+ out+ }+}
scripts/maps/tile_build/src/bin/mamaps_pack.rs
diff --git a/scripts/maps/tile_build/src/bin/mamaps_pack.rs b/scripts/maps/tile_build/src/bin/mamaps_pack.rsindex ee454fb912..b2be61e857 100644--- a/scripts/maps/tile_build/src/bin/mamaps_pack.rs+++ b/scripts/maps/tile_build/src/bin/mamaps_pack.rs@@ -334,8 +334,9 @@ fn validate_sidecars( let graph_version = u32_at(&meta, 4); // v8 (planet5) differs from v7 only inside intermediate.bin (varint shape points), which // is validated below by its trailer like any other version.- if !(6..=8).contains(&graph_version) {- return Err(format!("the graph is version {graph_version}, this pack reads v6..=v8"));+ // v9 adds column ZBLK blocks and ZSEC intermediate blob / road names / name-offset table.+ if !(6..=9).contains(&graph_version) {+ return Err(format!("the graph is version {graph_version}, this pack reads v6..=v9")); } let blocked_v7 = graph_version >= 7; let (node_count, edge_count) = (u64_at(&meta, 8), u64_at(&meta, 16));@@ -432,7 +433,20 @@ fn validate_sidecars( let present = edge_count.div_ceil(8); let name_off_off = names_off + rank + present; let want = name_off_off + named_edges * 4;- if len != want {+ if graph_version >= 9 && named_edges > 0 {+ // v9: the name-offset table is a ZSEC section (header: magic, block, raw_len).+ let path = graph.join("edges.bin");+ let mut f = std::fs::File::open(&path)+ .map_err(|e| format!("cannot read {}: {e}", path.display()))?;+ f.seek(SeekFrom::Start(name_off_off))+ .map_err(|e| format!("cannot read {}: {e}", path.display()))?;+ let mut zh = [0u8; 24];+ f.read_exact(&mut zh)+ .map_err(|e| format!("edges.bin ends before its name-offset table: {e}"))?;+ if &zh[..4] != b"ZSEC" || u64::from_le_bytes(zh[8..16].try_into().unwrap()) != named_edges * 4 {+ return Err("edges.bin (v9) name-offset table is not a ZSEC section of the table".to_string());+ }+ } else if len != want { return Err(format!("edges.bin is {len} bytes, want {want}")); } }