maps: read TRIX v8 block-compressed transit packs (#planet5)
- Commit
fdef89113b9105ab6d833608f427c31d7263d3d2- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-14 00:54 UTC (22 days ago)
- Parents
5939066
Planet5's transit section is a TRIX v8 pack: every non-empty section a tilecodec ZSEC section (64 KiB zstd-19 blocks). The planet pack goes 4.27 GB (device sections) -> 1.19 GB. TransitIndex::parse validates each v8 section's ZSEC table at open and records (offset, stored_len, block_size); sec[i] then carries the section's raw length, so every existing bound check is unchanged. All section reads already went through a handful of accessors; they now call rd::<T>(section, idx) / rd_at / byte(), which take the raw mmap path for v3..v7 and, for v8, read through a per-thread cache of decoded blocks (256 x 64 KiB, FIFO, with a last-block fast path) -- including reads that straddle a block edge. uvarint, read_str and the shape decoder use byte()/rd_at the same way. Nothing is ever decoded whole. Tests: every transit test now reads its fixture as a v8 pack (each section wrapped with 64-byte blocks so records straddle edges) via zsec_pack(); the version-matrix tests keep v3..v7 raw. examples/ transit_parity compares plans and departure boards between a v7 pack and its v8 rewrite (results in the planet5 report). Verified: cargo test -p offlinerouter (93 pass).
Diff
maps/src/main/rust/examples/transit_parity.rs
diff --git a/maps/src/main/rust/examples/transit_parity.rs b/maps/src/main/rust/examples/transit_parity.rsnew file mode 100644index 0000000000..60c3dbdda9--- /dev/null+++ b/maps/src/main/rust/examples/transit_parity.rs@@ -0,0 +1,135 @@+//! `transit_parity` — planet5 transit check: the same plans and departure boards from a TRIX v7+//! pack and its v8 (ZSEC, thinned shapes, no ROUTE_TRIPS) rewrite.+//!+//! ```text+//! cargo run --release --example transit_parity -- V7_DIR V8_DIR FEED [N]+//! ```+//!+//! Loads `<dir>/<FEED>.transit` from both directories and runs N origin/destination plans around+//! 24 transit-heavy cities at three departure times, plus a departure board at each origin.+//! Times, stops, routes, headsigns and stop counts must match exactly; ride distances and+//! polylines may differ only by the shape thinning (reported). Also times both, since v8 reads+//! go through the block cache.+//!+//! Experiment tooling (examples/): never in the cdylib.++use offlinerouter::transit::{plan, stop_departures, LegKind, QueryDay, Schedule, TransitIndex};+use std::time::Instant;++const CITIES: [(&str, f64, f64); 24] = [+ ("SF", 37.7749, -122.4194), ("LA", 34.0522, -118.2437), ("Seattle", 47.6062, -122.3321),+ ("NYC", 40.7580, -73.9855), ("Chicago", 41.8781, -87.6298), ("Toronto", 43.6532, -79.3832),+ ("Mexico City", 19.4326, -99.1332), ("Sao Paulo", -23.5505, -46.6333), ("London", 51.5074, -0.1278),+ ("Paris", 48.8566, 2.3522), ("Berlin", 52.52, 13.405), ("Madrid", 40.4168, -3.7038),+ ("Rome", 41.9028, 12.4964), ("Amsterdam", 52.3676, 4.9041), ("Zurich", 47.3769, 8.5417),+ ("Vienna", 48.2082, 16.3738), ("Warsaw", 52.2297, 21.0122), ("Stockholm", 59.3293, 18.0686),+ ("Tokyo", 35.6812, 139.7671), ("Seoul", 37.5665, 126.978), ("Sydney", -33.8688, 151.2093),+ ("Melbourne", -37.8136, 144.9631), ("Auckland", -36.8485, 174.7633), ("Singapore", 1.3521, 103.8198),+];++fn main() -> std::process::ExitCode {+ let a: Vec<String> = std::env::args().skip(1).collect();+ if a.len() < 3 {+ eprintln!("usage: transit_parity V7_DIR V8_DIR FEED [N]");+ return std::process::ExitCode::from(2);+ }+ let n: usize = a.get(3).and_then(|v| v.parse().ok()).unwrap_or(480);+ let t = Instant::now();+ let v7 = TransitIndex::load(&a[0], &a[2]).expect("v7 pack loads");+ let v8 = TransitIndex::load(&a[1], &a[2]).expect("v8 pack loads");+ println!("loaded both in {:.2}s", t.elapsed().as_secs_f64());+ // Tuesday 2026-11-17 (weekday 1 = Tue), previous day Monday.+ let day = QueryDay { weekday: 1, date: 20261117, prev_weekday: 0, prev_date: 20261116 };+ let sched = Schedule { day, overlay: None };+ let mut seed = 0x9E37_79B9_7F4A_7C15u64;+ let mut rnd = || {+ seed ^= seed << 13;+ seed ^= seed >> 7;+ seed ^= seed << 17;+ (seed >> 11) as f64 / (1u64 << 53) as f64+ };+ let (mut same, mut diff, mut none_both, mut routed) = (0usize, 0usize, 0usize, 0usize);+ let (mut boards_same, mut boards) = (0usize, 0usize);+ let (mut t7, mut t8) = (0.0f64, 0.0f64);+ let mut max_dist_diff = 0.0f64;+ let mut coords7 = 0usize;+ let mut coords8 = 0usize;+ for q in 0..n {+ let (_, la, lo) = CITIES[q % CITIES.len()];+ let off = |r: f64| (r - 0.5) * 0.12;+ let (fla, flo) = (la + off(rnd()), lo + off(rnd()));+ let (tla, tlo) = (la + off(rnd()), lo + off(rnd()));+ let dep = [7 * 3600 + 30 * 60, 12 * 3600, 18 * 3600 + 15 * 60][q % 3];+ let s = Instant::now();+ let p7 = plan(&v7, fla, flo, tla, tlo, dep, sched);+ t7 += s.elapsed().as_secs_f64();+ let s = Instant::now();+ let p8 = plan(&v8, fla, flo, tla, tlo, dep, sched);+ t8 += s.elapsed().as_secs_f64();+ match (&p7, &p8) {+ (None, None) => none_both += 1,+ (Some(x), Some(y)) => {+ routed += 1;+ let key = |l: &Vec<offlinerouter::transit::TransitLeg>| {+ l.iter()+ .map(|g| {+ (+ g.kind == LegKind::Ride,+ g.name.clone(),+ g.from_stop.clone(),+ g.to_stop.clone(),+ g.headsign.clone(),+ g.dep_secs,+ g.arr_secs,+ g.stop_count,+ g.board_stop_motis_id.clone(),+ g.alight_stop_motis_id.clone(),+ )+ })+ .collect::<Vec<_>>()+ };+ if key(x) == key(y) {+ same += 1;+ for (g7, g8) in x.iter().zip(y.iter()) {+ max_dist_diff = max_dist_diff.max((g7.dist_m - g8.dist_m).abs());+ coords7 += g7.coords.len() / 2;+ coords8 += g8.coords.len() / 2;+ }+ } else {+ diff += 1;+ if diff <= 5 {+ println!("query {q}: plans differ");+ }+ }+ }+ _ => {+ diff += 1;+ println!("query {q}: routable in one pack only");+ }+ }+ let b7 = stop_departures(&v7, fla, flo, dep, sched, 20);+ let b8 = stop_departures(&v8, fla, flo, dep, sched, 20);+ let bk = |b: &Vec<offlinerouter::transit::StopDeparture>| {+ b.iter().map(|d| (d.route_name.clone(), d.headsign.clone(), d.stop_code.clone(), d.dep_secs)).collect::<Vec<_>>()+ };+ boards += 1;+ if bk(&b7) == bk(&b8) {+ boards_same += 1;+ }+ }+ println!(+ "plans: {routed} routed, {none_both} unroutable in both; identical legs {same}, different {diff}\n\+ departure boards identical {boards_same}/{boards}\n\+ ride polylines: {coords7} -> {coords8} points; max leg distance change {max_dist_diff:.2} m\n\+ plan time: v7 {:.1} ms/query, v8 {:.1} ms/query",+ t7 * 1e3 / n as f64,+ t8 * 1e3 / n as f64+ );+ if diff == 0 && boards_same == boards {+ println!("TRANSIT PARITY OK");+ std::process::ExitCode::SUCCESS+ } else {+ println!("TRANSIT PARITY FAILED");+ std::process::ExitCode::FAILURE+ }+}
maps/src/main/rust/src/transit.rs
diff --git a/maps/src/main/rust/src/transit.rs b/maps/src/main/rust/src/transit.rsindex 21472daf14..13f88c0ec3 100644--- a/maps/src/main/rust/src/transit.rs+++ b/maps/src/main/rust/src/transit.rs@@ -313,6 +313,12 @@ pub struct TransitIndex { grid_cell_count: u32, // Section (offset, len) directory. sec: [(usize, usize); SECTION_COUNT],+ /// Planet5 (TRIX v8): per section, its ZSEC `(offset, stored_len, block_size)` when the+ /// section is block-compressed; `sec[i]` then holds `(offset, raw_len)` and every read goes+ /// through [`TransitIndex::rd`] / [`TransitIndex::byte`] and the per-thread block cache.+ zsec: [Option<(usize, usize, usize)>; SECTION_COUNT],+ /// Distinguishes this index's blocks in the per-thread cache.+ uid: u64, /// Long-distance route classification, built on first use. intercity: std::sync::OnceLock<Intercity>, }@@ -322,6 +328,7 @@ unsafe impl Send for TransitIndex {} unsafe impl Sync for TransitIndex {} include!("transit_part1.rs");+include!("transit_zsec.rs"); include!("transit_part2.rs"); include!("transit_part3.rs"); include!("transit_part4.rs");
maps/src/main/rust/src/transit_part1.rs
diff --git a/maps/src/main/rust/src/transit_part1.rs b/maps/src/main/rust/src/transit_part1.rsindex eebfacf558..22a95c967d 100644--- a/maps/src/main/rust/src/transit_part1.rs+++ b/maps/src/main/rust/src/transit_part1.rs@@ -61,6 +61,7 @@ impl TransitIndex { // tail rather than rejecting it. let dir_base = unsafe { base.add(HEADER_LEN) }; let mut sec = [(0usize, 0usize); SECTION_COUNT];+ let mut zsec = [None; SECTION_COUNT]; for (i, s) in sec.iter_mut().enumerate().take(section_count.min(SECTION_COUNT)) { let off: u64 = unsafe { read_at::<u64>(dir_base, i * 2) }; let len: u64 = unsafe { read_at::<u64>(dir_base, i * 2 + 1) };@@ -68,6 +69,17 @@ impl TransitIndex { return None; } *s = (off as usize, len as usize);+ // v8: every non-empty section is a ZSEC block section. Validate its table now and+ // expose its *raw* length, which is what every bound check below compares against.+ if version >= tilecodec::mamaps::archive::TRANSIT_VERSION_ZSEC && len > 0 {+ let bytes = unsafe { std::slice::from_raw_parts(base.add(off as usize), len as usize) };+ let z = tilecodec::zsec::ZSec::parse(bytes).ok()?;+ if z.block_size() == 0 || z.block_size() > (1 << 20) {+ return None;+ }+ zsec[i] = Some((off as usize, len as usize, z.block_size()));+ *s = (off as usize, z.raw_len() as usize);+ } } Some(TransitIndex {@@ -88,6 +100,8 @@ impl TransitIndex { grid_cols, grid_cell_count, sec,+ zsec,+ uid: NEXT_TRANSIT_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed), intercity: std::sync::OnceLock::new(), }) }@@ -106,7 +120,11 @@ impl TransitIndex { if *pos >= len { break; }- let b = unsafe { *self.base.add(off + *pos) };+ let b = if self.zsec[section].is_some() {+ self.byte(section, *pos)+ } else {+ unsafe { *self.base.add(off + *pos) }+ }; *pos += 1; result |= ((b & 0x7f) as u64) << shift; if b & 0x80 == 0 {@@ -125,6 +143,19 @@ impl TransitIndex { if off as usize >= len { return String::new(); }+ if self.zsec[SEC_STRINGS].is_some() {+ let mut bytes = Vec::new();+ let mut at = off as usize;+ while at < len {+ let b = self.byte(SEC_STRINGS, at);+ if b == 0 {+ break;+ }+ bytes.push(b);+ at += 1;+ }+ return String::from_utf8_lossy(&bytes).into_owned();+ } unsafe { let p = self.base.add(start + off as usize); let mut n = 0usize;@@ -136,49 +167,49 @@ impl TransitIndex { } fn stop(&self, i: u32) -> StopRec {- unsafe { read_at::<StopRec>(self.sec_ptr(SEC_STOPS), i as usize) }+ self.rd::<StopRec>(SEC_STOPS, i as usize) } fn route(&self, i: u32) -> RouteRec {- unsafe { read_at::<RouteRec>(self.sec_ptr(SEC_ROUTES), i as usize) }+ self.rd::<RouteRec>(SEC_ROUTES, i as usize) } fn route_stop(&self, i: u32) -> u32 {- unsafe { read_at::<u32>(self.sec_ptr(SEC_ROUTE_STOPS), i as usize) }+ self.rd::<u32>(SEC_ROUTE_STOPS, i as usize) } fn stop_routes_range(&self, stop: u32) -> (u32, u32) {- let idx = self.sec_ptr(SEC_STOP_ROUTES_IDX);- let s = unsafe { read_at::<u32>(idx, stop as usize) };- let e = unsafe { read_at::<u32>(idx, stop as usize + 1) };+ let idx = SEC_STOP_ROUTES_IDX;+ let s = self.rd::<u32>(idx, stop as usize);+ let e = self.rd::<u32>(idx, stop as usize + 1); (s, e) } fn stop_route(&self, i: u32) -> u32 {- unsafe { read_at::<u32>(self.sec_ptr(SEC_STOP_ROUTES), i as usize) }+ self.rd::<u32>(SEC_STOP_ROUTES, i as usize) } /// Position of the stop within that route's stop pattern, parallel to /// [`Self::stop_route`] (first occurrence, as the writer records it). fn stop_route_pos(&self, i: u32) -> u32 {- unsafe { read_at::<u32>(self.sec_ptr(SEC_STOP_ROUTE_POS), i as usize) }+ self.rd::<u32>(SEC_STOP_ROUTE_POS, i as usize) } fn transfers_range(&self, stop: u32) -> (u32, u32) {- let idx = self.sec_ptr(SEC_TRANSFERS_IDX);- let s = unsafe { read_at::<u32>(idx, stop as usize) };- let e = unsafe { read_at::<u32>(idx, stop as usize + 1) };+ let idx = SEC_TRANSFERS_IDX;+ let s = self.rd::<u32>(idx, stop as usize);+ let e = self.rd::<u32>(idx, stop as usize + 1); (s, e) } fn transfer(&self, i: u32) -> TransferRec {- unsafe { read_at::<TransferRec>(self.sec_ptr(SEC_TRANSFERS), i as usize) }+ self.rd::<TransferRec>(SEC_TRANSFERS, i as usize) } fn service(&self, i: u32) -> ServiceRec {- unsafe { read_at::<ServiceRec>(self.sec_ptr(SEC_SERVICES), i as usize) }+ self.rd::<ServiceRec>(SEC_SERVICES, i as usize) } fn exception(&self, i: u32) -> ExcRec {- unsafe { read_at::<ExcRec>(self.sec_ptr(SEC_EXCEPTIONS), i as usize) }+ self.rd::<ExcRec>(SEC_EXCEPTIONS, i as usize) } /// `[start, end)` range of EXCEPTIONS belonging to `service_idx`, ascending /// by date. v3 CSR index; replaces a full scan of every exception per call. fn exceptions_range(&self, service_idx: u32) -> (u32, u32) {- let idx = self.sec_ptr(SEC_EXCEPTIONS_IDX);- let s = unsafe { read_at::<u32>(idx, service_idx as usize) };- let e = unsafe { read_at::<u32>(idx, service_idx as usize + 1) };+ let idx = SEC_EXCEPTIONS_IDX;+ let s = self.rd::<u32>(idx, service_idx as usize);+ let e = self.rd::<u32>(idx, service_idx as usize + 1); (s, e) } @@ -193,7 +224,7 @@ impl TransitIndex { if self.sec[SEC_ROUTE_SHAPE_IDX].1 < (self.route_count as usize + 1) * 4 { return None; }- let off = unsafe { read_at::<u32>(self.sec_ptr(SEC_ROUTE_SHAPE_IDX), route_idx as usize) };+ let off = self.rd::<u32>(SEC_ROUTE_SHAPE_IDX, route_idx as usize); // NONE marks "no shape"; an offset with no room for the point count is // corrupt and gets the same fallback. if (off as usize).saturating_add(4) > self.sec[SEC_SHAPE_COORDS].1 {@@ -208,16 +239,14 @@ impl TransitIndex { if (i as usize + 1) * 4 > self.sec[SEC_ROUTE_STOP_SHAPE].1 { return NONE; }- unsafe { read_at::<u32>(self.sec_ptr(SEC_ROUTE_STOP_SHAPE), i as usize) }+ self.rd::<u32>(SEC_ROUTE_STOP_SHAPE, i as usize) } /// Decode vertices `from..=to` of the shape blob at byte offset `off`, as /// `(lat, lon)` degrees. Deltas accumulate from the blob's first point, so /// decoding always starts there and discards the head. fn shape_slice(&self, off: usize, from: u32, to: u32) -> Vec<(f64, f64)> {- let point_count = unsafe {- read_at::<u32>(self.base.add(self.sec[SEC_SHAPE_COORDS].0 + off), 0)- };+ let point_count = self.rd_at::<u32>(SEC_SHAPE_COORDS, off); if to < from || to >= point_count { return Vec::new(); }@@ -259,13 +288,13 @@ impl TransitIndex { /// Trip record `i` of the strided table, by global trip index. fn trip_at(&self, i: u32) -> TripDec {- let p = self.sec_ptr(SEC_ROUTE_TRIP_RECS);+ let p = SEC_ROUTE_TRIP_RECS; let w = i as usize * 4; TripDec {- start_time: unsafe { read_at::<u32>(p, w) },- profile_id: unsafe { read_at::<u32>(p, w + 1) },- service_idx: unsafe { read_at::<u32>(p, w + 2) },- headsign_off: unsafe { read_at::<u32>(p, w + 3) },+ start_time: self.rd::<u32>(p, w),+ profile_id: self.rd::<u32>(p, w + 1),+ service_idx: self.rd::<u32>(p, w + 2),+ headsign_off: self.rd::<u32>(p, w + 3), } } @@ -274,9 +303,9 @@ impl TransitIndex { if !self.has_trip_table() { return Trips::Decoded(self.route_trips(rec)); }- let off = self.sec_ptr(SEC_ROUTE_TRIP_OFF);- let base = unsafe { read_at::<u32>(off, route_idx as usize) };- let end = unsafe { read_at::<u32>(off, route_idx as usize + 1) };+ let off = SEC_ROUTE_TRIP_OFF;+ let base = self.rd::<u32>(off, route_idx as usize);+ let end = self.rd::<u32>(off, route_idx as usize + 1); // A directory that disagrees with the route record would index past the table; // fall back rather than read out of bounds. let len = end.saturating_sub(base);@@ -291,7 +320,7 @@ impl TransitIndex { /// Decode profile `pid` into per-stop offsets relative to `start_time`. fn profile(&self, pid: u32) -> ProfileDec {- let off = unsafe { read_at::<u32>(self.sec_ptr(SEC_PROFILES_IDX), pid as usize) } as usize;+ let off = self.rd::<u32>(SEC_PROFILES_IDX, pid as usize) as usize; let mut pos = off; let n = self.uvarint(SEC_PROFILES, &mut pos) as usize; let mut arr_rel = vec![0i32; n.max(1)];@@ -343,11 +372,11 @@ impl TransitIndex { /// Binary-search a cell id in GRID_CELL_IDS -> its index, if present. fn cell_index(&self, cell_id: u32) -> Option<usize> {- let ids = self.sec_ptr(SEC_GRID_CELL_IDS);+ let ids = SEC_GRID_CELL_IDS; let (mut lo, mut hi) = (0usize, self.grid_cell_count as usize); while lo < hi { let mid = (lo + hi) / 2;- let v = unsafe { read_at::<u32>(ids, mid) };+ let v = self.rd::<u32>(ids, mid); if v == cell_id { return Some(mid); } else if v < cell_id {@@ -360,13 +389,13 @@ impl TransitIndex { } fn cell_stops(&self, cell_index: usize) -> (u32, u32) {- let off = self.sec_ptr(SEC_GRID_CELL_OFF);- let s = unsafe { read_at::<u32>(off, cell_index) };- let e = unsafe { read_at::<u32>(off, cell_index + 1) };+ let off = SEC_GRID_CELL_OFF;+ let s = self.rd::<u32>(off, cell_index);+ let e = self.rd::<u32>(off, cell_index + 1); (s, e) } fn grid_stop(&self, i: u32) -> u32 {- unsafe { read_at::<u32>(self.sec_ptr(SEC_GRID_STOPS), i as usize) }+ self.rd::<u32>(SEC_GRID_STOPS, i as usize) } /// Candidate stops within `radius_m` of `(lat,lon)` and their distances,@@ -445,7 +474,7 @@ impl TransitIndex { if feed_idx >= self.feed_count { return self.feed_name(); }- let off = unsafe { read_at::<u32>(self.sec_ptr(SEC_FEEDS), feed_idx as usize) };+ let off = self.rd::<u32>(SEC_FEEDS, feed_idx as usize); self.read_str(off) } }
maps/src/main/rust/src/transit_part2.rs
diff --git a/maps/src/main/rust/src/transit_part2.rs b/maps/src/main/rust/src/transit_part2.rsindex b12af80a00..fbb0d56f6a 100644--- a/maps/src/main/rust/src/transit_part2.rs+++ b/maps/src/main/rust/src/transit_part2.rs@@ -6,7 +6,7 @@ impl TransitIndex { if feed_idx >= self.feed_count { return String::new(); }- let off = unsafe { read_at::<u32>(self.sec_ptr(SEC_FEED_TZ), feed_idx as usize) };+ let off = self.rd::<u32>(SEC_FEED_TZ, feed_idx as usize); self.read_str(off) } @@ -21,7 +21,7 @@ impl TransitIndex { return None; } let off =- unsafe { read_at::<u32>(self.sec_ptr(SEC_FEED_MOTIS_PREFIX), feed_idx as usize) };+ self.rd::<u32>(SEC_FEED_MOTIS_PREFIX, feed_idx as usize); if off == NONE { return None; }@@ -49,7 +49,7 @@ impl TransitIndex { return None; } let id_off =- unsafe { read_at::<u32>(self.sec_ptr(SEC_STOP_GTFS_ID), stop_idx as usize) };+ self.rd::<u32>(SEC_STOP_GTFS_ID, stop_idx as usize); if id_off == NONE { return None; }
maps/src/main/rust/src/transit_part6.rs
diff --git a/maps/src/main/rust/src/transit_part6.rs b/maps/src/main/rust/src/transit_part6.rsindex dc712dcce2..b23d5a5745 100644--- a/maps/src/main/rust/src/transit_part6.rs+++ b/maps/src/main/rust/src/transit_part6.rs@@ -451,7 +451,40 @@ out } + /// The planet5 (TRIX v8) pack every test reads: the v7 layout with every non-empty+ /// section wrapped in a ZSEC block section — so the whole suite runs through the+ /// block-cache read path. Small blocks (64 bytes) so records straddle block edges. fn index(&self) -> TransitIndex {- TransitIndex::from_bytes(self.build_with_version(VERSION)).expect("index loads")+ TransitIndex::from_bytes(zsec_pack(&self.build_with_version(7), 64)).expect("index loads") }++ /// The same pack as raw v7 sections (planet4's layout).+ fn index_v7(&self) -> TransitIndex {+ TransitIndex::from_bytes(self.build_with_version(7)).expect("index loads")+ }+ }++ /// Rewrite a raw TRIX pack as v8: each non-empty section a ZSEC section of `block`-byte+ /// blocks (the real packs use 64 KiB; tests use tiny blocks to force straddling reads).+ fn zsec_pack(v7: &[u8], block: usize) -> Vec<u8> {+ let count = u32::from_le_bytes(v7[8..12].try_into().unwrap()) as usize;+ let mut out = v7[..HEADER_LEN].to_vec();+ out[4..8].copy_from_slice(&tilecodec::mamaps::archive::TRANSIT_VERSION_ZSEC.to_le_bytes());+ let dir_at = out.len();+ out.resize(dir_at + count * 16, 0);+ for i in 0..count {+ let at = HEADER_LEN + i * 16;+ let off = u64::from_le_bytes(v7[at..at + 8].try_into().unwrap()) as usize;+ let len = u64::from_le_bytes(v7[at + 8..at + 16].try_into().unwrap()) as usize;+ let z = if len == 0 { Vec::new() } else { tilecodec::zsec::write_zsec(&v7[off..off + len], block, 3) };+ while out.len() % 8 != 0 {+ out.push(0);+ }+ let o = out.len() as u64;+ out.extend_from_slice(&z);+ let d = dir_at + i * 16;+ out[d..d + 8].copy_from_slice(&o.to_le_bytes());+ out[d + 8..d + 16].copy_from_slice(&(z.len() as u64).to_le_bytes());+ }+ out }
maps/src/main/rust/src/transit_part8.rs
diff --git a/maps/src/main/rust/src/transit_part8.rs b/maps/src/main/rust/src/transit_part8.rsindex 06b5e3071d..0642c5fc19 100644--- a/maps/src/main/rust/src/transit_part8.rs+++ b/maps/src/main/rust/src/transit_part8.rs@@ -92,7 +92,7 @@ fn every_version_of_a_pack_plans_the_same_journey() { let pack = one_route_pack(); let mut baseline: Option<Vec<(u32, u32, String)>> = None;- for version in [VERSION_MIN, 4, 5, VERSION] {+ for version in [VERSION_MIN, 4, 5, 7] { let idx = TransitIndex::from_bytes(pack.build_with_version(version)) .unwrap_or_else(|| panic!("v{version} loads")); let legs = plan(&idx, 37.700, -122.400, 37.720, -122.400, 25_000, sched(wednesday()))@@ -112,7 +112,7 @@ fn every_version_of_a_pack_lists_the_same_departures() { let pack = one_route_pack(); let mut baseline: Option<Vec<u32>> = None;- for version in [VERSION_MIN, 4, 5, VERSION] {+ for version in [VERSION_MIN, 4, 5, 7] { let idx = TransitIndex::from_bytes(pack.build_with_version(version)) .unwrap_or_else(|| panic!("v{version} loads")); let board = stop_departures(&idx, 37.700, -122.400, 0, sched(wednesday()), 10);@@ -130,7 +130,7 @@ #[test] fn a_trip_table_disagreeing_with_the_route_falls_back_to_the_varint_stream() { let pack = one_route_pack();- let idx = TransitIndex::from_bytes(pack.build_with_version(VERSION)).expect("v6 loads");+ let idx = TransitIndex::from_bytes(pack.build_with_version(7)).expect("v6 loads"); let route = idx.route(0); assert!(idx.has_trip_table(), "the fixture writes the table"); // What the strided path returns, to compare the fallback against.
maps/src/main/rust/src/transit_part9.rs
diff --git a/maps/src/main/rust/src/transit_part9.rs b/maps/src/main/rust/src/transit_part9.rsindex 2b87054718..bc1b59ed77 100644--- a/maps/src/main/rust/src/transit_part9.rs+++ b/maps/src/main/rust/src/transit_part9.rs@@ -242,7 +242,7 @@ fn a_pack_sliced_from_the_archive_plans_the_same_journey() { // The pack bytes through the container must read exactly as from the // pack's own file: same journey, same 08:00 trip.- let pack = one_route_pack().build_with_version(VERSION);+ let pack = one_route_pack().build_with_version(7); let bytes = archive_with_pack(&pack); let idx = TransitIndex::from_bytes(pack_section(&bytes)).expect("section parses"); let legs = plan(&idx, 37.700, -122.400, 37.720, -122.400, 25_000, sched(wednesday()))@@ -289,7 +289,7 @@ #[cfg(unix)] #[test] fn load_archive_maps_one_file_and_plans() {- let pack = one_route_pack().build_with_version(VERSION);+ let pack = one_route_pack().build_with_version(7); let bytes = archive_with_pack(&pack); let path = std::env::temp_dir().join(format!( "transit_archive_{}.mamaps",@@ -311,7 +311,7 @@ #[cfg(unix)] #[test] fn has_archive_transit_sees_section_thirteen() {- let pack = one_route_pack().build_with_version(VERSION);+ let pack = one_route_pack().build_with_version(7); let bytes = archive_with_pack(&pack); let path = std::env::temp_dir().join(format!( "transit_presence_{}.mamaps",
maps/src/main/rust/src/transit_zsec.rs
diff --git a/maps/src/main/rust/src/transit_zsec.rs b/maps/src/main/rust/src/transit_zsec.rsnew file mode 100644index 0000000000..90eeb883da--- /dev/null+++ b/maps/src/main/rust/src/transit_zsec.rs@@ -0,0 +1,102 @@+// Planet5 (TRIX v8) block-compressed sections: typed reads through a per-thread block cache.+//+// Every non-empty v8 section is a `tilecodec::zsec` section. A read of `size_of::<T>()` bytes at+// a byte position decodes the one (or, straddling a boundary, two) 64 KiB blocks it touches and+// keeps them in a small per-thread cache, so the RAPTOR loops — which walk a route's trips, a+// stop's transfers and a profile's varints in order — decode each block once and then hit the+// cache. v3..v7 sections take the old raw mmap path untouched.++static NEXT_TRANSIT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);++/// Decoded blocks a thread keeps across all indexes (64 KiB each: 16 MiB per thread).+const TRANSIT_BLOCK_CACHE: usize = 256;++struct TransitBlockCache {+ map: std::collections::HashMap<(u64, u8, u32), std::rc::Rc<Vec<u8>>>,+ order: std::collections::VecDeque<(u64, u8, u32)>,+ last: Option<((u64, u8, u32), std::rc::Rc<Vec<u8>>)>,+}++thread_local! {+ static TRANSIT_BLOCKS: std::cell::RefCell<TransitBlockCache> = std::cell::RefCell::new(TransitBlockCache {+ map: std::collections::HashMap::new(),+ order: std::collections::VecDeque::new(),+ last: None,+ });+}++impl TransitIndex {+ /// Decoded block `b` of ZSEC section `section`, from the per-thread cache.+ fn zblock(&self, section: usize, b: u32) -> std::rc::Rc<Vec<u8>> {+ let key = (self.uid, section as u8, b);+ TRANSIT_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 (off, len, _) = self.zsec[section].expect("a ZSEC section");+ let bytes = unsafe { std::slice::from_raw_parts(self.base.add(off), len) };+ // Validated at open; a decode failure here is corruption the open could not see.+ let block = tilecodec::zsec::ZSec::parse(bytes)+ .and_then(|z| z.block(b as usize))+ .unwrap_or_default();+ let v = std::rc::Rc::new(block);+ if c.order.len() >= TRANSIT_BLOCK_CACHE {+ if let Some(old) = c.order.pop_front() {+ c.map.remove(&old);+ }+ }+ c.order.push_back(key);+ c.map.insert(key, v.clone());+ c.last = Some((key, v.clone()));+ v+ })+ }++ /// One byte at raw position `pos` of a ZSEC section (0 past the end, as a raw read past a+ /// section's length would never be asked for: callers bound-check against `sec[i].1`).+ fn byte(&self, section: usize, pos: usize) -> u8 {+ let bs = self.zsec[section].expect("a ZSEC section").2;+ let blk = self.zblock(section, (pos / bs) as u32);+ blk.get(pos % bs).copied().unwrap_or(0)+ }++ /// A `T` at raw byte position `pos` of `section`, either layout.+ fn rd_at<T: Copy>(&self, section: usize, pos: usize) -> T {+ let n = std::mem::size_of::<T>();+ if self.zsec[section].is_none() {+ return unsafe { (self.base.add(self.sec[section].0 + pos) as *const T).read_unaligned() };+ }+ let bs = self.zsec[section].expect("a ZSEC section").2;+ let mut buf = [0u8; 64];+ assert!(n <= buf.len(), "a transit record wider than 64 bytes");+ let mut got = 0usize;+ while got < n {+ let p = pos + got;+ let blk = self.zblock(section, (p / bs) as u32);+ let at = p % bs;+ let take = (n - got).min(blk.len().saturating_sub(at));+ if take == 0 {+ break;+ }+ buf[got..got + take].copy_from_slice(&blk[at..at + take]);+ got += take;+ }+ unsafe { (buf.as_ptr() as *const T).read_unaligned() }+ }++ /// The `idx`-th `T` of `section` (the typed record reads every accessor goes through).+ #[inline]+ fn rd<T: Copy>(&self, section: usize, idx: usize) -> T {+ if self.zsec[section].is_none() {+ return unsafe { read_at::<T>(self.sec_ptr(section), idx) };+ }+ self.rd_at::<T>(section, idx * std::mem::size_of::<T>())+ }+}