maps: add router Rust tests and fix one-way stub routing
- Commit
d07735eedd2cd28d7ac965cc15ba431ba4f2ec24- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-17 21:55 UTC (18 days ago)
- Parents
ea1febf
33 new tests (93 -> 126): MVT tile decode, graph assemble/load and ZSEC, A* search end-to-end on synthetic graphs, geometry, lane guidance. Fix found by the tests: A* seeded and completed through both anchors of the start/end edges, so a trip on a one-way street could start by driving backward to the upstream junction (a 1.08 km illegal shortcut instead of the legal 3.8 km); driving now uses the backward stub only when a reverse directed edge exists, walking/transit unchanged. Line coverage 71.4% -> 80.3%. cargo test -p offlinerouter green.
Diff
maps/src/main/rust/src/geometry.rs
diff --git a/maps/src/main/rust/src/geometry.rs b/maps/src/main/rust/src/geometry.rsindex a00df731f2..b3e36e3c52 100644--- a/maps/src/main/rust/src/geometry.rs+++ b/maps/src/main/rust/src/geometry.rs@@ -303,3 +303,7 @@ mod tests { assert!(!is_mode_allowed(REVERSE_GEOMETRY_FLAG, WALK)); } }++#[cfg(test)]+#[path = "geometry_tests.rs"]+mod cov_tests;
maps/src/main/rust/src/geometry_tests.rs
diff --git a/maps/src/main/rust/src/geometry_tests.rs b/maps/src/main/rust/src/geometry_tests.rsnew file mode 100644index 0000000000..75ebe75a3c--- /dev/null+++ b/maps/src/main/rust/src/geometry_tests.rs@@ -0,0 +1,133 @@+//! Cost-model and projection tests (sibling of `geometry.rs`). Expected+//! values are computed from first principles (haversine radius, Web-Mercator+//! scale at the equator, km/h -> 10 ms units), not from the code under test.+use super::*;+use crate::graph::graph_cov_tests::{assemble, Spec};+use crate::graph::{BICYCLE, DRIVING, INVALID_EDGE, MAX_DRIVING_KMH, PUBLIC_TRANSIT, WALK};+use std::collections::BTreeMap;++fn g() -> crate::graph::Graph {+ assemble(&Spec {+ nodes: vec![(0, 0), (0, 100_000)],+ edges: vec![(0, 1, 5, 50, 1_113_900), (1, 0, 5, 50, 1_113_900)],+ escaped: vec![],+ names: BTreeMap::new(),+ pool: vec![],+ geom: BTreeMap::new(),+ lanes: None,+ elevation: None,+ })+}++#[test]+fn haversine_matches_the_known_earth_scale() {+ assert_eq!(accurate_dist_mm(0, 0, 0, 0), 0);+ // One degree of latitude is pi/180 * R = 111,195 m for R = 6,371,000.8 m.+ let d = accurate_dist_mm(0, 0, 10_000_000, 0);+ assert!((111_190_000..111_200_000).contains(&d), "1 deg lat = {d} mm");+ // Antipodal: pi * R ~ 20,015 km in mm overflows u32, so it saturates+ // (the function's documented contract).+ assert_eq!(accurate_dist_mm(0, 0, 0, 1_800_000_000), u32::MAX);+ assert_eq!(accurate_dist_mm(10, 20, -30, 40), accurate_dist_mm(-30, 40, 10, 20), "symmetric");+}++#[test]+fn fast_distance_is_symmetric_and_equator_scaled() {+ let g = g();+ assert_eq!(fast_dist_mm(&g, 5, 5, 5, 5), 0);+ // Octagonal approx of 0.01 deg at the equator (~1113.9 m exact): within 5%.+ let d = fast_dist_mm(&g, 0, 0, 0, 100_000);+ assert!((1_050_000..1_120_000).contains(&d), "0.01 deg lon = {d} mm");+ assert_eq!(d, fast_dist_mm(&g, 0, 100_000, 0, 0), "symmetric");+ // Longitude metres shrink with cos(lat): at 60 deg the same span is ~half.+ let d60 = fast_dist_mm(&g, 600_000_000, 0, 600_000_000, 100_000);+ assert!(d60 < d / 2 + 20_000 && d60 > d / 2 - 60_000, "60 deg: {d60} vs equator {d}");+ // A diagonal reads between its legs and their sum.+ let diag = fast_dist_mm(&g, 0, 0, 100_000, 100_000);+ assert!(diag > d && diag < 2 * d, "diagonal {diag}");+}++#[test]+fn bearings_and_maneuver_boundaries() {+ assert!((get_bearing(0, 0, 10_000_000, 0)).abs() < 0.01, "due north is 0");+ assert!((get_bearing(0, 0, 0, 10_000_000) - 90.0).abs() < 0.01, "due east is 90");+ assert!((get_bearing(0, 0, -10_000_000, 0).abs() - 180.0).abs() < 0.01, "due south is 180");+ assert!((get_bearing(0, 0, 0, -10_000_000) + 90.0).abs() < 0.01, "due west is -90");+ // Maneuver bands, probed at their edges (codes per get_maneuver docs).+ for (diff, want) in [+ (-180.0, 3), (-156.0, 3), (-155.0, 2), (-101.0, 2), (-100.0, 4), (-46.0, 4),+ (-45.0, 1), (-11.0, 1), (-10.0, 9), (0.0, 9), (9.0, 9), (10.0, 5), (44.0, 5),+ (45.0, 8), (99.0, 8), (100.0, 6), (155.0, 6), (156.0, 7), (180.0, 7),+ ] {+ assert_eq!(get_maneuver(0.0, diff), want, "diff {diff}");+ }+ // Wrap: 170 -> -170 is a +20 turn, not a -340 reversal.+ assert_eq!(get_maneuver(170.0, -170.0), 5);+ assert_eq!(get_maneuver(-170.0, 170.0), 1);+}++#[test]+fn projection_clamps_to_the_segment() {+ let g = g();+ let mid = get_projection(&g, 0, 50_000, 0, 0, 0, 100_000);+ assert_eq!((mid.lat_e7, mid.lon_e7), (0, 50_000));+ assert_eq!(mid.dist_mm, 0, "a point on the segment projects to itself");+ let beyond = get_projection(&g, 0, 300_000, 0, 0, 0, 100_000);+ assert_eq!(beyond.lon_e7, 100_000, "clamped to the far end");+ let before = get_projection(&g, 0, -50_000, 0, 0, 0, 100_000);+ assert_eq!(before.lon_e7, 0, "clamped to the near end");+ let deg = get_projection(&g, 7, 9, 3, 4, 3, 4);+ assert_eq!((deg.lat_e7, deg.lon_e7), (3, 4), "a degenerate segment is its point");+ let side = get_projection(&g, 50_000, 50_000, 0, 0, 0, 100_000);+ assert_eq!((side.lat_e7, side.lon_e7), (0, 50_000));+ assert!(side.dist_mm > 500_000, "perpendicular distance kept: {}", side.dist_mm);+}++#[test]+fn edge_time_uses_limits_traffic_and_mode_tables() {+ let g = g();+ let none = TrafficSpeeds::default();+ // 36 km/h = 10 m/s: 10,000 mm takes exactly 1 s = 100 (10 ms units).+ assert_eq!(get_edge_time_10ms(&g, &none, INVALID_EDGE, 10_000, 5, 36, DRIVING), 100);+ assert_eq!(get_edge_time_10ms(&g, &none, INVALID_EDGE, 20_000, 5, 36, DRIVING), 200);+ // Live traffic replaces the posted limit; INVALID_EDGE ignores traffic.+ let mut traffic = TrafficSpeeds::default();+ traffic.insert(7, 72); // 20 m/s+ assert_eq!(get_edge_time_10ms(&g, &traffic, 7, 10_000, 5, 36, DRIVING), 50);+ assert_eq!(get_edge_time_10ms(&g, &traffic, INVALID_EDGE, 10_000, 5, 36, DRIVING), 100);+ assert_eq!(get_edge_time_10ms(&g, &traffic, 8, 10_000, 5, 36, DRIVING), 100, "other edges unaffected");+ // Speeds are clamped to MAX_DRIVING_KMH (130): 200 km/h reads as 130.+ let fast = get_edge_time_10ms(&g, &none, INVALID_EDGE, 130_000, 5, 200, DRIVING);+ let at_max = get_edge_time_10ms(&g, &none, INVALID_EDGE, 130_000, 5, MAX_DRIVING_KMH as u8, DRIVING);+ assert_eq!(fast, at_max);+ assert_eq!(at_max, 360, "130 m at 130 km/h is 3.6 s");+ // A zero limit falls back to the per-class table (finite and positive).+ let t = get_edge_time_10ms(&g, &none, INVALID_EDGE, 100_000, 5, 0, DRIVING);+ assert!(t > 0 && t < 10_000, "class-table time {t}");+ // Walking the same road is slower than driving it; transit walks too.+ let w = get_edge_time_10ms(&g, &none, INVALID_EDGE, 100_000, 5, 50, WALK);+ let p = get_edge_time_10ms(&g, &none, INVALID_EDGE, 100_000, 5, 50, PUBLIC_TRANSIT);+ assert!(w > t && p == w, "walk {w} drive {t}");+ // Heuristic: zero at the goal, and never above the fastest legal edge time+ // (the A* consistency the radix heap relies on).+ assert_eq!(heuristic_time_10ms(&g, 3, 4, 3, 4, DRIVING), 0);+ let h = heuristic_time_10ms(&g, 0, 0, 0, 100_000, DRIVING);+ let fastest = get_edge_time_10ms(&g, &none, INVALID_EDGE, 1_113_900, 5, MAX_DRIVING_KMH as u8, DRIVING);+ assert!(h > 0 && h <= fastest + 2, "heuristic {h} <= fastest {fastest}");+ let _ = BICYCLE;+}++#[test]+fn the_edge_id_hasher_is_deterministic_and_spreads() {+ let mut a = TrafficSpeeds::default();+ a.insert(42, 90);+ a.insert(u64::MAX, 30);+ assert_eq!(a.get(&42), Some(&90));+ assert_eq!(a.get(&u64::MAX), Some(&30));+ assert_eq!(a.get(&43), None);+ use std::hash::Hasher;+ let h = |n: u64| { let mut x = EdgeIdHasher::default(); x.write_u64(n); x.finish() };+ assert_eq!(h(7), h(7));+ assert_ne!(h(7), h(8));+ assert_ne!(h(0), h(1 << 32), "high bits spread too");+}
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 d1b90fd1f4..2efb44d52b 100644--- a/maps/src/main/rust/src/graph.rs+++ b/maps/src/main/rust/src/graph.rs@@ -454,4 +454,6 @@ include!("graph_part3.rs"); include!("graph_part4.rs"); include!("graph_part4b.rs"); include!("graph_part5.rs");-include!("graph_overlay.rs");\ No newline at end of file+include!("graph_overlay.rs");+#[cfg(test)]+pub(crate) mod graph_cov_tests;
maps/src/main/rust/src/graph/graph_cov_tests.rs
diff --git a/maps/src/main/rust/src/graph/graph_cov_tests.rs b/maps/src/main/rust/src/graph/graph_cov_tests.rsnew file mode 100644index 0000000000..6b568625d3--- /dev/null+++ b/maps/src/main/rust/src/graph/graph_cov_tests.rs@@ -0,0 +1,392 @@+//! Synthetic-graph tests for the loaders and table readers in graph_part2/2b/3+//! and graph_zsec. Graphs are built byte-by-byte in the v6 (raw) layout the+//! generator writes, so expected values are known by construction.+use super::*;+use std::collections::BTreeMap;++pub struct Spec {+ pub nodes: Vec<(i32, i32)>, // (lat_e7, lon_e7)+ pub edges: Vec<(u32, u32, u8, u8, u32)>, // (src, dst, type, limit, dist_mm)+ pub escaped: Vec<u64>, // edge indices via the escape table+ pub names: BTreeMap<u64, u32>, // edge idx -> pool offset+ pub pool: Vec<u8>,+ pub geom: BTreeMap<u64, Vec<(i16, i16)>>, // edge idx -> interior deltas+ pub lanes: Option<Vec<u8>>,+ pub elevation: Option<Vec<i16>>,+}++fn pad8(v: &mut Vec<u8>) {+ while v.len() % 8 != 0 {+ v.push(0);+ }+}+fn bitmap(edge_count: u64, present: &[u64]) -> Vec<u8> {+ let mut out = Vec::new();+ let blocks = edge_count.div_ceil(RANK_BLOCK_BYTES * 8);+ let mut rank = vec![0u64; (blocks + 1) as usize];+ let mut bytes = vec![0u8; edge_count.div_ceil(8) as usize];+ for &i in present {+ bytes[(i / 8) as usize] |= 1 << (i % 8);+ }+ let mut run = 0u64;+ for b in 0..blocks as usize {+ rank[b] = run;+ let (lo, hi) = (b * RANK_BLOCK_BYTES as usize, ((b + 1) * RANK_BLOCK_BYTES as usize).min(bytes.len()));+ run += bytes[lo..hi].iter().map(|x| u64::from(x.count_ones())).sum::<u64>();+ }+ rank[blocks as usize] = run;+ for r in rank {+ out.extend_from_slice(&r.to_le_bytes());+ }+ out.extend_from_slice(&bytes);+ out+}++/// The four mandatory section payloads (+ optionals) for `spec`, v6 layout.+pub fn payloads(spec: &Spec) -> (Vec<u8>, Vec<u8>, Vec<u8>, Vec<u8>) {+ let n = spec.nodes.len() as u32;+ let e = spec.edges.len() as u64;+ let mut edges: Vec<(usize, &(u32, u32, u8, u8, u32))> = spec.edges.iter().enumerate().collect();+ edges.sort_by_key(|(_, x)| x.0);+ let mut ptr = vec![0u32; spec.nodes.len() + 1];+ for (_, x) in &edges {+ ptr[x.0 as usize + 1] += 1;+ }+ for i in 0..spec.nodes.len() {+ ptr[i + 1] += ptr[i];+ }+ let mut nodes_b = Vec::new();+ for (i, (lat, lon)) in spec.nodes.iter().enumerate() {+ nodes_b.extend_from_slice(&lat.to_le_bytes());+ nodes_b.extend_from_slice(&lon.to_le_bytes());+ nodes_b.extend_from_slice(&ptr[i].to_le_bytes());+ }+ nodes_b.extend_from_slice(&0i32.to_le_bytes());+ nodes_b.extend_from_slice(&0i32.to_le_bytes());+ nodes_b.extend_from_slice(&(e as u32).to_le_bytes());++ let mut edges_b = Vec::new();+ let mut esc_rows: Vec<(u32, u32, u32)> = Vec::new();+ for (idx, (s, t, ty, lim, dist)) in &edges {+ if spec.escaped.contains(&(*idx as u64)) {+ edges_b.extend_from_slice(&i16::MIN.to_le_bytes());+ edges_b.extend_from_slice(&dist.to_le_bytes()[..3]);+ esc_rows.push((*idx as u32, *t, *dist));+ } else {+ edges_b.extend_from_slice(&((*t as i64 - *s as i64) as i16).to_le_bytes());+ edges_b.extend_from_slice(&dist.to_le_bytes()[..3]);+ }+ edges_b.push(*ty);+ edges_b.push(*lim);+ }+ pad8(&mut edges_b);+ let nblocks = e.div_ceil(ESCAPE_BLOCK) + 1;+ for b in 0..nblocks {+ let c = esc_rows.iter().filter(|r| u64::from(r.0) / ESCAPE_BLOCK < b).count();+ edges_b.extend_from_slice(&(c as u32).to_le_bytes());+ }+ for (idx, t, d) in &esc_rows {+ edges_b.extend_from_slice(&idx.to_le_bytes());+ edges_b.extend_from_slice(&t.to_le_bytes());+ edges_b.extend_from_slice(&d.to_le_bytes());+ }+ pad8(&mut edges_b);+ let named: Vec<u64> = spec.names.keys().copied().collect();+ edges_b.extend_from_slice(&bitmap(e, &named));+ for idx in &named {+ edges_b.extend_from_slice(&spec.names[idx].to_le_bytes());+ }++ // intermediate: blob, then [rank|present] bitmap, coarse, within, G.+ let gidx: Vec<u64> = spec.geom.keys().copied().collect();+ let g = gidx.len() as u64;+ let mut blob = Vec::new();+ let mut offs = vec![0u64];+ for idx in &gidx {+ for (dl, dn) in &spec.geom[idx] {+ blob.extend_from_slice(&dl.to_le_bytes());+ blob.extend_from_slice(&dn.to_le_bytes());+ }+ offs.push(blob.len() as u64);+ }+ let mut inter = blob.clone();+ inter.extend_from_slice(&bitmap(e, &gidx));+ let coarse_n = g.div_ceil(INTERMEDIATE_BLOCK) + 1;+ let mut coarse = vec![0u64; coarse_n as usize];+ let mut within = vec![0u16; (g + 1) as usize];+ // offs are cumulative; each block's coarse entry is its first offset and+ // `within` is the remainder (test blobs are far below the u16 limit).+ for i in 0..=g as usize {+ let blk = i / INTERMEDIATE_BLOCK as usize;+ if i % INTERMEDIATE_BLOCK as usize == 0 {+ coarse[blk] = offs[i];+ }+ within[i] = (offs[i] - coarse[blk]) as u16;+ }+ for c in &coarse {+ inter.extend_from_slice(&c.to_le_bytes());+ }+ for w in &within {+ inter.extend_from_slice(&w.to_le_bytes());+ }+ inter.extend_from_slice(&g.to_le_bytes());++ let mut meta = Vec::new();+ meta.extend_from_slice(&GRAPH_MAGIC.to_le_bytes());+ meta.extend_from_slice(&GRAPH_VERSION_MIN.to_le_bytes());+ meta.extend_from_slice(&u64::from(n).to_le_bytes());+ meta.extend_from_slice(&e.to_le_bytes());+ meta.extend_from_slice(&(esc_rows.len() as u64).to_le_bytes());+ meta.extend_from_slice(&(named.len() as u64).to_le_bytes());+ (meta, nodes_b, edges_b, inter)+}++pub fn assemble(spec: &Spec) -> Graph {+ let (meta, nodes, edges, inter) = payloads(spec);+ let mut owned = vec![meta, nodes, edges, inter];+ if !spec.pool.is_empty() {+ owned.push(spec.pool.clone());+ }+ if let Some(l) = &spec.lanes {+ owned.push(l.clone());+ }+ if let Some(el) = &spec.elevation {+ owned.push(el.iter().flat_map(|v| v.to_le_bytes()).collect());+ }+ let at = |i: usize| unsafe { std::slice::from_raw_parts(owned[i].as_ptr(), owned[i].len()) };+ let (mut i, mut pool, mut lanes, mut elev) = (4usize, None, None, None);+ if !spec.pool.is_empty() {+ pool = Some(at(i));+ i += 1;+ }+ if spec.lanes.is_some() {+ lanes = Some(at(i));+ i += 1;+ }+ if spec.elevation.is_some() {+ elev = Some(at(i));+ }+ Graph::assemble(+ GraphSections { meta: at(0), nodes: at(1), edges: at(2), intermediate: at(3), road_names: pool, lanes, elevation: elev },+ GraphOwnership { nodes: None, edges: None, intermediate: None, road_names: None, lanes: None, elevation: None, archive: None, buffers: owned },+ )+ .expect("synthetic graph assembles")+}++fn base_spec() -> Spec {+ // 0:(0,0) 1:(0,100_000) 2:(100_000,100_000) 3:(100_000,0); a square + a+ // degree-0 node 4. Edges both ways around the square.+ let mut edges = Vec::new();+ for (s, t) in [(0, 1), (1, 0), (1, 2), (2, 1), (2, 3), (3, 2), (3, 0), (0, 3)] {+ edges.push((s, t, 5u8, 50u8, 11_114u32));+ }+ Spec {+ nodes: vec![(0, 0), (0, 100_000), (100_000, 100_000), (100_000, 0), (50_000, 50_000)],+ edges,+ escaped: vec![],+ names: BTreeMap::new(),+ pool: vec![],+ geom: BTreeMap::new(),+ lanes: None,+ elevation: None,+ }+}++#[test]+fn assemble_reads_nodes_edges_and_ranges() {+ let g = assemble(&base_spec());+ assert_eq!((g.node_count, g.edge_count), (5, 8));+ assert_eq!((g.node(1).lat_e7, g.node(1).lon_e7), (0, 100_000));+ assert_eq!(g.edge_range(0), (0, 2), "node 0 owns edges 0..2 after src sort");+ assert_eq!(g.edge_range(4), (8, 8), "degree-0 node has an empty range");+ assert_eq!(g.edge_range(3).1, 8, "last-but-one range ends at the sentinel");+ let e = g.edge(0, 0);+ assert_eq!((e.target, e.dist_mm, e.type_, e.speed_limit), (1, 11_114, 5, 50));+ assert!(g.edge_targets(0, 0, 1) && !g.edge_targets(0, 0, 2));+ assert_eq!(g.get_node(99).edge_ptr, 0, "out-of-range reads as the zero node");+ assert_eq!(g.get_node(5).lat_e7, 0, "the sentinel is not a real node");+ assert!(!g.has_elevation() && g.node_elevation(0) == 0 && g.node_elevation(99) == 0);+}++#[test]+fn escaped_edges_read_target_and_distance_from_the_table() {+ let mut s = base_spec();+ s.escaped = vec![0];+ let g = assemble(&s);+ let e = g.edge(0, 0);+ assert_eq!((e.target, e.dist_mm), (1, 11_114), "escape row, not the sentinel record");+ assert_eq!(g.escape_count, 1);+}++#[test]+fn names_lanes_and_elevation_read_through_their_side_tables() {+ let mut s = base_spec();+ s.pool = b"Main Street\0Oak Avenue\0".to_vec();+ s.names = BTreeMap::from([(0u64, 0u32), (3u64, 12u32)]);+ // lanes: edge 1 has masks [through, left|right], edge 6 has [through].+ let mut lanes = Vec::new();+ lanes.extend_from_slice(&2u32.to_le_bytes());+ for (idx, off) in [(1u32, 0u32), (6, 4), (0, 6)] {+ lanes.extend_from_slice(&idx.to_le_bytes());+ lanes.extend_from_slice(&off.to_le_bytes());+ }+ for m in [2u16, 36, 2] {+ lanes.extend_from_slice(&m.to_le_bytes());+ }+ s.lanes = Some(lanes);+ s.elevation = Some(vec![10, 20, 30, 40, 50]);+ let g = assemble(&s);+ assert_eq!(g.edge_name_offset(0), Some(0));+ assert_eq!(g.edge_name_offset(3), Some(12));+ assert_eq!(g.edge_name_offset(1), None);+ assert_eq!(g.road_name(0).as_deref(), Some("Main Street"));+ assert_eq!(g.road_name(12).as_deref(), Some("Oak Avenue"));+ assert_eq!(g.road_name(NO_NAME), None);+ assert_eq!(g.road_name(10_000), None);+ assert_eq!(g.edge_lane_masks(1), Some(vec![2, 36]));+ assert_eq!(g.edge_lane_masks(6), Some(vec![2]));+ assert_eq!(g.edge_lane_masks(0), None);+ assert_eq!(g.edge_lane_masks(10_000), None);+ assert!(g.has_elevation());+ assert_eq!(g.node_elevation(2), 30);+}++#[test]+fn edge_geometry_decodes_deltas_and_reverses_for_the_flagged_twin() {+ let mut s = base_spec();+ // Edge 0 (0->1) stores one interior point halfway north of the chord.+ s.geom = BTreeMap::from([(0u64, vec![(30_000i16, 30_000i16)])]);+ let g = assemble(&s);+ let mut out = [LatLon { lat_e7: 0, lon_e7: 0 }; 256];+ let (cnt, rev) = g.get_edge_coordinates_from(0, 0, &mut out).unwrap();+ assert!(!rev && cnt == 3);+ assert_eq!((out[0].lat_e7, out[0].lon_e7), (0, 0), "seeded at the source");+ assert_eq!((out[1].lat_e7, out[1].lon_e7), (30_000, 30_000), "interior delta");+ assert_eq!((out[2].lat_e7, out[2].lon_e7), (0, 100_000), "terminated at the target");+ assert_eq!(get_pt_at(&out, cnt, false, 1).lat_e7, 30_000);+ // Sorted edge 2 (1->0) stores no geometry: callers get count 0, not a chord.+ let (cnt1, _) = g.get_edge_coordinates_from(1, 2, &mut out).unwrap();+ assert_eq!(cnt1, 0);+ assert!(g.get_edge_coordinates_from(0, 99, &mut out).is_none(), "past edge_count");+ // Flag the twin: sorted edge 2 (1->0, input index 1) gets+ // REVERSE_GEOMETRY_FLAG, so asking for it decodes edge 0's blob reversed.+ let mut s2 = base_spec();+ s2.edges[1].2 |= REVERSE_GEOMETRY_FLAG;+ s2.geom = BTreeMap::from([(0u64, vec![(30_000i16, 30_000i16)])]);+ let g2 = assemble(&s2);+ let (cnt2, rev2) = g2.get_edge_coordinates_from(1, 2, &mut out).unwrap();+ assert!(rev2 && cnt2 == 3);+ assert_eq!(get_pt_at(&out, cnt2, rev2, 0).lon_e7, 100_000, "reversed walk starts at node 1");+ assert_eq!(get_pt_at(&out, cnt2, rev2, 2).lon_e7, 0);+}++#[test]+fn spatial_codes_and_edge_owner_search() {+ assert_eq!(Graph::latlng_to_spatial(-90.0, -180.0), 0);+ assert_eq!(Graph::latlng_to_spatial(90.0, 180.0), u64::MAX);+ assert!(Graph::latlng_to_spatial(0.0, 0.0) < Graph::latlng_to_spatial(0.0, 0.001));+ assert!(Graph::latlng_to_spatial(0.0, 0.0) < Graph::latlng_to_spatial(0.001, 0.0));+ let g = assemble(&base_spec());+ // Node ranges (src-sorted): 0:[0,2) 1:[2,4) 2:[4,6) 3:[6,8) 4:[8,8).+ assert_eq!(g.find_node_idx_for_edge(0), 0);+ assert_eq!(g.find_node_idx_for_edge(1), 0);+ assert_eq!(g.find_node_idx_for_edge(2), 1);+ assert_eq!(g.find_node_idx_for_edge(7), 3);+ assert_eq!(g.find_node_idx_for_edge(8), 4, "largest ptr <= idx wins over degree-0 runs");+}++#[test]+fn load_reads_the_same_graph_from_files_and_refuses_corruption() {+ let spec = base_spec();+ let (meta, nodes, edges, inter) = payloads(&spec);+ let dir = std::env::temp_dir().join(format!("graph_load_{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let write = |name: &str, b: &[u8]| std::fs::write(dir.join(name), b).unwrap();+ write("metadata.bin", &meta);+ write("nodes.bin", &nodes);+ write("edges.bin", &edges);+ write("intermediate.bin", &inter);+ let base = dir.to_str().unwrap().to_string();+ let g = Graph::load(&base).expect("multi-file load");+ assert_eq!((g.node_count, g.edge_count), (5, 8));+ assert_eq!(g.edge(0, 0).target, 1);+ assert!(Graph::load(&format!("{base}/")).is_some(), "trailing slash optional");+ // Bad magic, short metadata, wrong nodes length, missing file.+ let mut bad = meta.clone();+ bad[0] ^= 0xFF;+ write("metadata.bin", &bad);+ assert!(Graph::load(&base).is_none(), "bad magic refused");+ write("metadata.bin", &meta[..20]);+ assert!(Graph::load(&base).is_none(), "short metadata refused");+ write("metadata.bin", &meta);+ write("nodes.bin", &nodes[..12]);+ assert!(Graph::load(&base).is_none(), "nodes length must match the counts exactly");+ write("nodes.bin", &nodes);+ std::fs::remove_file(dir.join("intermediate.bin")).unwrap();+ assert!(Graph::load(&base).is_none(), "intermediate.bin is mandatory");+ write("intermediate.bin", &inter[..4]);+ assert!(Graph::load(&base).is_none(), "truncated intermediate refused");+ let _ = std::fs::remove_dir_all(&dir);+}++#[test]+fn zsec_regions_round_trip_reads_and_cstrings() {+ let mut raw = Vec::new();+ raw.extend_from_slice(b"Main Street\0");+ raw.extend((0..70_000u32).map(|i| (i % 251) as u8));+ raw.extend_from_slice(b"Oak Avenue\0");+ let sec = tilecodec::zsec::write_zsec(&raw, 1024, 3);+ let z = ZsecRegion::parse(&sec).expect("zsec parses");+ assert_eq!(z.raw_len(), raw.len());+ let mut out = Vec::new();+ z.read_into(0, raw.len(), &mut out);+ assert_eq!(out, raw, "whole range across blocks");+ let mut tail = Vec::new();+ z.read_into(raw.len() - 5, 100, &mut tail);+ assert_eq!(tail, &raw[raw.len() - 5..], "reads clamp to the raw length");+ assert_eq!(z.cstr_at(0), b"Main Street");+ let oak = raw.len() - 11;+ assert_eq!(z.cstr_at(oak), b"Oak Avenue", "cstr at the very end");+ assert!(ZsecRegion::parse(b"nope").is_none());+ assert!(ZsecRegion::parse(&sec[..sec.len() - 1]).is_none(), "truncated refused");+ // v9 dispatchers: pre-v9 keeps raw bytes, v9 wraps them.+ let ptr = sec.as_ptr();+ assert!(matches!(ZsecRegion::v9_blob(ptr, sec.len() as u64, false), Some(None)));+ assert!(ZsecRegion::v9_blob(ptr, sec.len() as u64, true).is_some());+ assert!(matches!(ZsecRegion::v9_names(ptr, sec.len(), false), Some((None, _))));+ let (z2, raw_len) = ZsecRegion::v9_names(ptr, sec.len(), true).unwrap();+ assert!(z2.is_some() && raw_len == raw.len());+ assert!(matches!(ZsecRegion::v9_names(std::ptr::null(), 0, true), Some((None, 0))));+ let table = tilecodec::zsec::write_zsec(&8u32.to_le_bytes().repeat(2), 1024, 3);+ assert!(ZsecRegion::v9_name_offsets(&table, 0, 2, true).map_or(false, |z| z.is_some()));+ assert!(ZsecRegion::v9_name_offsets(&table, 0, 3, true).is_none(), "raw length must match named*4");+ assert!(ZsecRegion::v9_name_offsets(&[0u8; 8], 0, 2, false).map_or(false, |z| z.is_none()));+ assert!(ZsecRegion::v9_name_offsets(&[0u8; 7], 0, 2, false).is_none());+}++#[test]+fn load_reads_a_v7_blocked_pack_from_files() {+ let spec = base_spec();+ let (mut meta, nodes, edges, inter) = payloads(&spec);+ meta[4..8].copy_from_slice(&tilecodec::mamaps::archive::GRAPH_VERSION_BLOCKED.to_le_bytes());+ let nodes_b = tilecodec::blocked::write_blocked(&nodes, 12);+ let rec_end = 7 * spec.edges.len();+ let mut edges_b = tilecodec::blocked::write_blocked(&edges[..rec_end], 7);+ while edges_b.len() % 8 != 0 {+ edges_b.push(0);+ }+ edges_b.extend_from_slice(&edges[rec_end..]);+ let dir = std::env::temp_dir().join(format!("graph_load_v7_{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ for (name, b) in [("metadata.bin", &meta), ("nodes.bin", &nodes_b), ("edges.bin", &edges_b), ("intermediate.bin", &inter)] {+ std::fs::write(dir.join(name), b).unwrap();+ }+ let g = Graph::load(dir.to_str().unwrap()).expect("v7 multi-file load");+ assert_eq!((g.node_count, g.edge_count), (5, 8));+ assert!(g.uses_blocked_sections());+ assert_eq!(g.edge(0, 0).target, 1, "records read through the inflate cache");+ assert_eq!(g.node(1).lon_e7, 100_000);+ let _ = std::fs::remove_dir_all(&dir);+}
maps/src/main/rust/src/mvt.rs
diff --git a/maps/src/main/rust/src/mvt.rs b/maps/src/main/rust/src/mvt.rsindex 8a5f4c339b..514e682321 100644--- a/maps/src/main/rust/src/mvt.rs+++ b/maps/src/main/rust/src/mvt.rs@@ -197,3 +197,7 @@ pub fn generate_traffic_tile( } Some(compressed) }++#[cfg(test)]+#[path = "mvt_tests.rs"]+mod tests;
maps/src/main/rust/src/mvt_tests.rs
diff --git a/maps/src/main/rust/src/mvt_tests.rs b/maps/src/main/rust/src/mvt_tests.rsnew file mode 100644index 0000000000..a341f3bc1e--- /dev/null+++ b/maps/src/main/rust/src/mvt_tests.rs@@ -0,0 +1,213 @@+//! Unit tests for the traffic MVT encoder (sibling of `mvt.rs`, wired via+//! `#[path]`). Tiles are verified by gunzipping and walking the protobuf+//! wire format by hand, so the encoder is checked against the MVT spec's+//! field numbers rather than against itself.+use super::*;+use std::io::Read;++// --- minimal protobuf reader ---------------------------------------------+fn varint(b: &[u8], at: &mut usize) -> u64 {+ let (mut r, mut s) = (0u64, 0u32);+ loop {+ let x = b[*at];+ *at += 1;+ r |= u64::from(x & 0x7f) << s;+ if x & 0x80 == 0 {+ return r;+ }+ s += 7;+ }+}+fn fields(b: &[u8]) -> Vec<(u32, u64, Vec<u8>)> {+ let (mut at, mut out) = (0usize, Vec::new());+ while at < b.len() {+ let tag = varint(b, &mut at);+ let (f, w) = ((tag >> 3) as u32, (tag & 7) as u8);+ if w == 0 {+ out.push((f, varint(b, &mut at), Vec::new()));+ } else {+ let n = varint(b, &mut at) as usize;+ out.push((f, 0, b[at..at + n].to_vec()));+ at += n;+ }+ }+ out+}+fn gunzip(b: &[u8]) -> Vec<u8> {+ let mut out = Vec::new();+ flate2::read::GzDecoder::new(b).read_to_end(&mut out).unwrap();+ out+}+struct Layer {+ name: String,+ version: u64,+ extent: u64,+ keys: Vec<String>,+ values: Vec<String>,+ feats: Vec<(u64, Vec<u64>, Vec<u64>)>, // (id, tags, geometry commands raw)+}+fn parse_tile(gz: &[u8]) -> Layer {+ let tile = gunzip(gz);+ let tf = fields(&tile);+ assert_eq!(tf.len(), 1, "tile has exactly the layer field");+ assert_eq!(tf[0].0, 3, "tile field 3 is layers");+ let mut l = Layer { name: String::new(), version: 0, extent: 0, keys: vec![], values: vec![], feats: vec![] };+ for (f, v, bytes) in fields(&tf[0].2) {+ match f {+ 1 => l.name = String::from_utf8(bytes).unwrap(),+ 15 => l.version = v,+ 5 => l.extent = v,+ 3 => l.keys.push(String::from_utf8(bytes).unwrap()),+ 4 => {+ let vf = fields(&bytes);+ l.values.push(String::from_utf8(vf[0].2.clone()).unwrap());+ }+ 2 => {+ let (mut id, mut tags, mut geom) = (0u64, Vec::new(), Vec::new());+ for (ff, vv, bb) in fields(&bytes) {+ match ff {+ 3 => id = vv,+ 2 => { let mut a = 0; while a < bb.len() { tags.push(varint(&bb, &mut a)); } }+ 4 => { let mut a = 0; while a < bb.len() { geom.push(varint(&bb, &mut a)); } }+ _ => panic!("unexpected feature field {ff}"),+ }+ }+ l.feats.push((id, tags, geom));+ }+ _ => panic!("unexpected layer field {f}"),+ }+ }+ l+}+fn unzig(v: u64) -> i64 {+ ((v >> 1) as i64) ^ -((v & 1) as i64)+}+fn square(lat: i32, lon: i32) -> i32 {+ ((((lat + 360) as u32) << 16) | (lon + 720) as u32) as i32+}++#[test]+fn varint_and_tag_encodings_match_the_wire_format() {+ for (v, want) in [+ (0u64, vec![0u8]), (1, vec![1]), (127, vec![127]), (128, vec![0x80, 1]),+ (300, vec![0xAC, 2]), (16_384, vec![0x80, 0x80, 1]),+ (u64::MAX, vec![0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 1]),+ ] {+ let mut b = Vec::new();+ write_varint(&mut b, v);+ assert_eq!(b, want, "varint {v}");+ let mut at = 0;+ assert_eq!(varint(&b, &mut at), v, "round trip {v}");+ }+ let mut b = Vec::new();+ write_string(&mut b, 1, "traffic");+ assert_eq!(b, [0x0A, 7, b't', b'r', b'a', b'f', b'f', b'i', b'c']);+ assert_eq!(mvt_command(1, 1), 9, "MoveTo(1)");+ assert_eq!(mvt_command(2, 1), 10, "LineTo(1)");+ assert_eq!(mvt_command(7, 3), 31, "ClosePath(3)");+}++#[test]+fn zigzag_maps_signed_deltas_to_unsigned() {+ assert_eq!(zigzag(0), 0);+ assert_eq!(zigzag(-1), 1);+ assert_eq!(zigzag(1), 2);+ assert_eq!(zigzag(-2), 3);+ assert_eq!(zigzag(4096), 8192);+ assert_eq!(zigzag(-4096), 8191);+ for n in [-4608, -512, -1, 0, 1, 512, 4608, 1_000_000] {+ assert_eq!(unzig(zigzag(n) as u64), i64::from(n), "zigzag round trip {n}");+ }+}++#[test]+fn tile_projection_puts_the_origin_at_the_tile_centre() {+ let p = TileProj { n: 1.0, x: 0, y: 0 }; // the z0 world tile+ assert_eq!(p.wgs84_to_tile_px(0.0, 0.0), (2048, 2048));+ assert_eq!(p.wgs84_to_tile_px(0.0, -180.0), (0, 2048));+ assert_eq!(p.wgs84_to_tile_px(0.0, 180.0), (4096, 2048));+ let (px, py) = p.wgs84_to_tile_px(85.051_128_78, 0.0); // Web-Mercator limit+ assert_eq!(px, 2048);+ assert!(py.abs() <= 1, "north limit at the top edge, got {py}");+ let p2 = TileProj { n: 2.0, x: 1, y: 1 };+ assert_eq!(p2.wgs84_to_tile_px(0.0, 0.0), (0, 0), "tile (1,1) starts at the origin");+}++#[test]+fn gzip_round_trips_and_empty_input_stays_empty() {+ assert!(compress_gzip(&[]).is_empty(), "callers rely on empty == failure/none");+ let gz = compress_gzip(b"traffic-tile");+ assert_eq!(&gz[..3], &[0x1F, 0x8B, 8], "gzip magic + deflate");+ assert_eq!(gunzip(&gz), b"traffic-tile");+}++#[test]+fn an_empty_tile_still_has_a_valid_traffic_layer() {+ let gz = generate_traffic_tile(&BTreeMap::new(), 3, 2, 1).expect("tile");+ let l = parse_tile(&gz);+ assert_eq!(l.name, "traffic");+ assert_eq!(l.version, 2);+ assert_eq!(l.extent, 4096);+ assert_eq!(l.keys, ["color"]);+ assert!(l.values.is_empty() && l.feats.is_empty());+}++#[test]+fn a_segment_is_encoded_with_its_colour_and_geometry() {+ // z1 tile (0,0): lon -180..0, lat 0..85.05. Segment inside square (10,-10).+ let mut m = BTreeMap::new();+ m.insert(square(10, -10), vec![10.0, -10.0, 11.0, -9.0, 0.3]);+ let l = parse_tile(&generate_traffic_tile(&m, 1, 0, 0).unwrap());+ assert_eq!(l.values, ["#B71C1C"], "ratio < 0.5 is red");+ assert_eq!(l.feats.len(), 1);+ let (id, tags, geom) = &l.feats[0];+ assert_eq!(*id, 2);+ assert_eq!(tags, &[0, 0], "key 0 (color), value 0");+ let proj = TileProj { n: 2.0, x: 0, y: 0 };+ let (x1, y1) = proj.wgs84_to_tile_px(10.0, -10.0);+ let (x2, y2) = proj.wgs84_to_tile_px(11.0, -9.0);+ assert_eq!(geom.len(), 6);+ assert_eq!(geom[0], mvt_command(1, 1) as u64);+ assert_eq!((unzig(geom[1]), unzig(geom[2])), (i64::from(x1), i64::from(y1)), "MoveTo");+ assert_eq!(geom[3], mvt_command(2, 1) as u64);+ assert_eq!((unzig(geom[4]), unzig(geom[5])), (i64::from(x2 - x1), i64::from(y2 - y1)), "LineTo delta");+}++#[test]+fn colour_thresholds_and_value_interning() {+ let mut m = BTreeMap::new();+ // Four segments in one square: boundary ratios 0.5 and 0.9, plus a repeat.+ m.insert(square(10, -10), vec![+ 10.0, -10.0, 10.5, -9.5, 0.49,+ 11.0, -10.0, 11.5, -9.5, 0.5,+ 12.0, -10.0, 12.5, -9.5, 0.9,+ 13.0, -10.0, 13.5, -9.5, 0.2,+ ]);+ let l = parse_tile(&generate_traffic_tile(&m, 1, 0, 0).unwrap());+ assert_eq!(l.values, ["#B71C1C", "#E65100", "#1B5E20"], "first-seen intern order");+ let got: Vec<u64> = l.feats.iter().map(|f| f.1[1]).collect();+ assert_eq!(got, [0, 1, 2, 0], "0.5 is orange, 0.9 is green, repeats reuse the index");+}++#[test]+fn dead_truncated_and_off_tile_segments_are_skipped() {+ let mut m = BTreeMap::new();+ m.insert(square(10, -10), vec![+ 10.0, -10.0, 10.5, -9.5, 0.0, // no live speed+ 11.0, -10.0, 11.5, -9.5, -1.0, // negative ratio+ -80.0, -10.0, -81.0, -9.0, 1.0, // projects far below the tile: culled+ 12.0, -10.0, 12.5, // truncated tail group: ignored+ ]);+ let l = parse_tile(&generate_traffic_tile(&m, 1, 0, 0).unwrap());+ assert!(l.feats.is_empty(), "no feature survives: {:?}", l.feats);+ // A square outside the tile's floor range is never even visited.+ let mut m2 = BTreeMap::new();+ m2.insert(square(-40, 100), vec![-40.0, 100.0, -39.0, 101.0, 1.0]);+ let l2 = parse_tile(&generate_traffic_tile(&m2, 1, 0, 0).unwrap());+ assert!(l2.feats.is_empty());+ // Segments straddling the 512px gutter are kept (partial overlap).+ let mut m3 = BTreeMap::new();+ m3.insert(square(0, -1), vec![0.0, -1.0, 0.0, 0.5, 1.0]);+ let l3 = parse_tile(&generate_traffic_tile(&m3, 1, 0, 0).unwrap());+ assert_eq!(l3.feats.len(), 1, "crossing the east edge is drawn, not culled");+}
maps/src/main/rust/src/routing.rs
diff --git a/maps/src/main/rust/src/routing.rs b/maps/src/main/rust/src/routing.rsindex a327be1a9f..7b8c892bc2 100644--- a/maps/src/main/rust/src/routing.rs+++ b/maps/src/main/rust/src/routing.rs@@ -17,3 +17,6 @@ pub mod steps; pub use astar::perform_search_loop; pub use search::{Direct, RoutingContext, SnappedEdge, find_nearest_edge, prepare_routing}; pub use steps::{StepData, ascent_descent, reconstruct_path, route_ascent_descent};++#[cfg(test)]+mod search_cov_tests;
maps/src/main/rust/src/routing/astar.rs
diff --git a/maps/src/main/rust/src/routing/astar.rs b/maps/src/main/rust/src/routing/astar.rsindex 992f57d0f7..6bedcb6e04 100644--- a/maps/src/main/rust/src/routing/astar.rs+++ b/maps/src/main/rust/src/routing/astar.rs@@ -2,7 +2,7 @@ use crate::geometry::*; use crate::graph::*; use crate::state::{RadixHeap, RoutingScratchpad};-use super::search::{seed, RoutingContext};+use super::search::{seed, stub_reverse_allowed, RoutingContext}; /// Within this distance of either end the search expands every road; beyond it /// a full-graph node only hops onto the overlay.@@ -75,6 +75,10 @@ fn search( // apart rather than a few metres, so the wrong choice costs the length of // the street. Score both completions and keep the better one. let mut best_total = u32::MAX;+ // Completing via `end.node_b` means travelling the end stub backwards+ // along the end edge; on a one-way street (driving, no reverse edge)+ // that anchor cannot complete a route. See `stub_reverse_allowed`.+ let end_reverse_ok = stub_reverse_allowed(g, &ctx.end, mode); let n_full = g.node_count; let overlay = if ctx.hierarchy { g.overlay() } else { None }; let (end_lat, end_lon) = (ctx.end.proj_lat, ctx.end.proj_lon);@@ -111,7 +115,7 @@ fn search( break; } - if u == ctx.end.node_a || u == ctx.end.node_b {+ if u == ctx.end.node_a || (u == ctx.end.node_b && end_reverse_ok) { let stub = if u == ctx.end.node_a { ctx.end.dist_a_mm } else {
maps/src/main/rust/src/routing/search.rs
diff --git a/maps/src/main/rust/src/routing/search.rs b/maps/src/main/rust/src/routing/search.rsindex a8d09b32b5..bdcd8de4d7 100644--- a/maps/src/main/rust/src/routing/search.rs+++ b/maps/src/main/rust/src/routing/search.rs@@ -249,6 +249,34 @@ pub fn prepare_routing( }) } +/// Whether any directed edge runs `from -> to` (the road is traversable that+/// way at all). Used for the start/end stubs: travelling a stub *backwards*+/// along a snapped edge is only possible when the reverse directed edge+/// exists. Unlike [`twin_edge`] this does not require uniqueness — any+/// reverse edge makes the direction legal; `twin_edge`'s uniqueness is about+/// which polyline to draw, not whether travel is allowed.+pub(super) fn has_reverse_edge(g: &Graph, from: u32, to: u32) -> bool {+ if from >= g.node_count || to >= g.node_count {+ return false;+ }+ let (s, e) = g.edge_range(from);+ (s..e).any(|k| g.edge_targets(k, from, to))+}++/// Whether the stub along a snapped edge may be travelled backwards (from+/// `node_b` toward `node_a`) for `mode`. Driving must obey one-way streets:+/// without a reverse edge, a car snapped mid-block on a one-way street can+/// only leave via `node_b` and can only be reached from `node_a`. Walking+/// (and transit walk legs) may travel either way on any road. Before this+/// check the search seeded and completed through both anchors regardless,+/// so a one-way trip could start or end by driving the wrong way down the+/// street (found by `search_cov_tests::a_one_way_road_forbids_the_backward_direct_path`).+pub(super) fn stub_reverse_allowed(g: &Graph, edge: &SnappedEdge, mode: i32) -> bool {+ mode != DRIVING+ || edge.edge_idx == INVALID_EDGE+ || has_reverse_edge(g, edge.node_b, edge.node_a)+}+ /// Push the start edge's two endpoints onto the open set. pub(super) fn seed( g: &Graph,@@ -268,7 +296,9 @@ pub(super) fn seed( let h = heuristic_time_10ms(g, n_data.lat_e7, n_data.lon_e7, end.proj_lat, end.proj_lon, mode); heap.push(t_actual.wrapping_add(h), node); };- push(start.node_a, start.dist_a_mm);+ if stub_reverse_allowed(g, start, mode) {+ push(start.node_a, start.dist_a_mm);+ } push(start.node_b, start.dist_b_mm); }
maps/src/main/rust/src/routing/search_cov_tests.rs
diff --git a/maps/src/main/rust/src/routing/search_cov_tests.rs b/maps/src/main/rust/src/routing/search_cov_tests.rsnew file mode 100644index 0000000000..ecfabe9f65--- /dev/null+++ b/maps/src/main/rust/src/routing/search_cov_tests.rs@@ -0,0 +1,163 @@+//! End-to-end routing tests over the synthetic square graph from+//! `graph::graph_cov_tests`: snapping, the A* loop, the on-edge direct path+//! and step reconstruction, all with hand-computable distances (0.01° at the+//! equator is ~1113.9 m per side).+use crate::geometry::TrafficSpeeds;+use crate::graph::graph_cov_tests::{assemble, Spec};+use crate::graph::{BICYCLE, DRIVING, PUBLIC_TRANSIT, WALK};+use crate::routing::{ascent_descent, find_nearest_edge, perform_search_loop, prepare_routing, reconstruct_path, route_ascent_descent};+use crate::state::{RadixHeap, RoutingScratchpad};+use std::collections::BTreeMap;++fn square(one_way: bool, elevation: Option<Vec<i16>>) -> Spec {+ let mut edges: Vec<(u32, u32, u8, u8, u32)> = Vec::new();+ for (s, t) in [(0, 1), (1, 2), (2, 3), (3, 0)] {+ edges.push((s, t, 5, 50, 1_113_900));+ }+ if !one_way {+ for (s, t) in [(1, 0), (2, 1), (3, 2), (0, 3)] {+ edges.push((s, t, 5, 50, 1_113_900));+ }+ }+ Spec {+ nodes: vec![(0, 0), (0, 100_000), (100_000, 100_000), (100_000, 0)],+ edges,+ escaped: vec![],+ names: BTreeMap::new(),+ pool: vec![],+ geom: BTreeMap::new(),+ lanes: None,+ elevation,+ }+}++fn plan(spec: &Spec, s: (f64, f64), e: (f64, f64), mode: i32) -> Option<(Vec<crate::routing::StepData>, bool)> {+ let g = assemble(spec);+ let speeds = TrafficSpeeds::default();+ let (mut scratch, mut heap) = (RoutingScratchpad::new(), RadixHeap::new());+ let mut ensure = |_: i32, _: i32| {};+ let mut ctx = prepare_routing(&g, &speeds, &mut ensure, s.0, s.1, e.0, e.1, mode, &mut scratch, &mut heap)?;+ let has_direct = ctx.direct.is_some();+ perform_search_loop(&g, &speeds, &mut ensure, mode, &mut ctx, &mut scratch, &mut heap);+ Some((reconstruct_path(&g, &speeds, mode, &ctx, &mut scratch), has_direct))+}++fn total(steps: &[crate::routing::StepData]) -> (u64, u64) {+ (steps.iter().map(|s| s.dist_mm).sum(), steps.iter().map(|s| s.time_10ms).sum())+}++#[test]+fn snapping_finds_the_nearest_edge_and_projection() {+ let g = assemble(&square(false, None));+ // 55 m north of the 0->1 edge's midpoint.+ let s = find_nearest_edge(&g, 0.0005, 0.005, DRIVING);+ assert_eq!((s.node_a, s.node_b), (0, 1));+ assert!((500_000..580_000).contains(&s.dist_a_mm), "dist_a {}", s.dist_a_mm);+ assert!((500_000..580_000).contains(&s.dist_b_mm), "dist_b {}", s.dist_b_mm);+ assert_eq!((s.type_, s.speed_limit), (5, 50));+ assert_ne!(s.edge_idx, crate::graph::INVALID_EDGE);+ // An empty graph snaps to the sentinel, never to node 0.+ let mut empty = square(false, None);+ empty.nodes.clear();+ empty.edges.clear();+ let g0 = assemble(&empty);+ assert_eq!(find_nearest_edge(&g0, 0.0, 0.0, WALK).node_a, 0xFFFF_FFFF);+}++#[test]+fn a_two_leg_route_reconstructs_with_the_right_distance_and_time() {+ let (steps, direct) = plan(&square(false, None), (0.0001, 0.0001), (0.0099, 0.0099), DRIVING).unwrap();+ assert!(!direct, "different edges: the search, not the direct path");+ assert!(!steps.is_empty());+ let (dist, time) = total(&steps);+ // Two sides of the square (~1114 m each) less the corner stubs.+ assert!((2_050_000..2_300_000).contains(&dist), "dist {dist} mm");+ assert!(time > 0 && time < 100_000, "time {time}");+ let first = &steps[0].coords;+ assert!((first[0] - 0.0001).abs() < 0.001 && (first[1] - 0.0001).abs() < 0.001, "starts at the start");+ let last_step = steps.last().unwrap();+ let last = &last_step.coords;+ let (lo, la) = (last[last.len() - 2], last[last.len() - 1]);+ assert!((lo - 0.0099).abs() < 0.001 && (la - 0.0099).abs() < 0.001, "ends at the end, got {lo},{la}");+ // The same corners walk and cycle too (slower over the fixed speeds).+ for mode in [WALK, BICYCLE] {+ let (wsteps, _) = plan(&square(false, None), (0.0001, 0.0001), (0.0099, 0.0099), mode).unwrap();+ let (wd, wt) = total(&wsteps);+ assert!((2_050_000..2_300_000).contains(&wd), "mode {mode} dist {wd}");+ assert!(wt > time, "mode {mode} is slower than driving");+ }+}++#[test]+fn a_trip_along_one_road_takes_the_direct_path_both_ways() {+ // Both ends on edge 0->1, 0.006 degrees apart (~668 m): no node detour.+ let (steps, direct) = plan(&square(false, None), (0.0, 0.002), (0.0, 0.008), DRIVING).unwrap();+ assert!(direct, "same directed edge");+ let (dist, _) = total(&steps);+ assert!((620_000..720_000).contains(&dist), "direct dist {dist} mm, not a node round trip");+ let (rsteps, rdirect) = plan(&square(false, None), (0.0, 0.008), (0.0, 0.002), DRIVING).unwrap();+ assert!(rdirect, "the twin makes the return direct too");+ let (rdist, _) = total(&rsteps);+ assert!((620_000..720_000).contains(&rdist), "return dist {rdist} mm");+}++#[test]+fn a_one_way_road_forbids_the_backward_direct_path() {+ let (steps, direct) = plan(&square(true, None), (0.0, 0.008), (0.0, 0.002), DRIVING).unwrap();+ assert!(!direct, "no twin, no backward direct path");+ let (dist, _) = total(&steps);+ // Around the other three sides (~3.3 km) instead of 0.67 km back.+ assert!(dist > 2_500_000, "one-way detour dist {dist} mm");+ // Forward along the one-way street is still direct.+ let (_, fwd_direct) = plan(&square(true, None), (0.0, 0.002), (0.0, 0.008), DRIVING).unwrap();+ assert!(fwd_direct);+}++#[test]+fn transit_walk_legs_refuse_implausible_lengths_and_unsearched_routes_are_empty() {+ // A 10-degree transit walk leg is refused before snapping.+ assert!(plan(&square(false, None), (0.0, 0.0), (10.0, 10.0), PUBLIC_TRANSIT).is_none());+ // Reconstructing before any search (target unset, no direct) is empty.+ let g = assemble(&square(false, None));+ let speeds = TrafficSpeeds::default();+ let (mut scratch, mut heap) = (RoutingScratchpad::new(), RadixHeap::new());+ let mut ensure = |_: i32, _: i32| {};+ let ctx = prepare_routing(&g, &speeds, &mut ensure, 0.0001, 0.0001, 0.0099, 0.0099, DRIVING, &mut scratch, &mut heap).unwrap();+ assert!(reconstruct_path(&g, &speeds, DRIVING, &ctx, &mut scratch).is_empty());+}++#[test]+fn elevations_ride_the_route_and_sum_to_the_terrain() {+ let spec = square(false, Some(vec![0, 100, 0, 0]));+ let (steps, _) = plan(&spec, (0.0001, 0.0001), (0.0099, 0.0099), DRIVING).unwrap();+ let (asc, desc) = route_ascent_descent(&steps);+ assert!((asc - 100.0).abs() < 3.0, "climbs node 1's 100 m: {asc}");+ assert!((desc - 100.0).abs() < 3.0, "and descends again: {desc}");+ assert_eq!(ascent_descent(&[]), (0.0, 0.0));+ assert_eq!(ascent_descent(&[5.0]), (0.0, 0.0));+}++#[test]+fn a_route_over_curved_edges_reconstructs_through_their_geometry() {+ // Bottom edge bulges north, right edge bulges west: the route must follow+ // the stored polylines (start stub, main leg and end stub all take the+ // geometry branches of reconstruct_path), not the straight chords.+ let mut spec = square(false, None);+ let mut sorted = spec.edges.clone();+ sorted.sort_by_key(|e| e.0);+ let bottom = sorted.iter().position(|e| (e.0, e.1) == (0, 1)).unwrap() as u64;+ let right = sorted.iter().position(|e| (e.0, e.1) == (1, 2)).unwrap() as u64;+ spec.geom = BTreeMap::from([+ (bottom, vec![(30_000i16, 30_000i16)]),+ (right, vec![(30_000i16, -30_000i16)]),+ ]);+ let (steps, _) = plan(&spec, (0.0001, 0.0002), (0.009, 0.0099), DRIVING).unwrap();+ assert!(!steps.is_empty());+ let (dist, _) = total(&steps);+ // Longer than the two straight chords (~2.13 km) because of the bulges,+ // shorter than any three-side alternative.+ assert!((1_900_000..2_900_000).contains(&dist), "curved dist {dist} mm");+ let all: Vec<f64> = steps.iter().flat_map(|s| s.coords.clone()).collect();+ let has_bulge = all.windows(2).any(|w| (w[0] - 0.003).abs() < 0.001 && (w[1] - 0.003).abs() < 0.001);+ assert!(has_bulge, "an interior bulge vertex (lon 0.003, lat 0.003) is in the route: {all:?}");+}
maps/src/main/rust/src/routing/steps/lanes.rs
diff --git a/maps/src/main/rust/src/routing/steps/lanes.rs b/maps/src/main/rust/src/routing/steps/lanes.rsindex 070a434961..f2a18981c7 100644--- a/maps/src/main/rust/src/routing/steps/lanes.rs+++ b/maps/src/main/rust/src/routing/steps/lanes.rs@@ -193,3 +193,7 @@ mod tests { assert!(!lane_serves(mask, 9), "but not a straight-on"); } }++#[cfg(test)]+#[path = "lanes_tests.rs"]+mod cov_tests;
maps/src/main/rust/src/routing/steps/lanes_tests.rs
diff --git a/maps/src/main/rust/src/routing/steps/lanes_tests.rs b/maps/src/main/rust/src/routing/steps/lanes_tests.rsnew file mode 100644index 0000000000..6663aae6c2--- /dev/null+++ b/maps/src/main/rust/src/routing/steps/lanes_tests.rs@@ -0,0 +1,99 @@+//! Lane-guidance tests (sibling of `lanes.rs`): mask conversion, lane+//! validity tolerances, real OSM lanes, and topology fallback at a cross.+use super::*;+use crate::graph::graph_cov_tests::{assemble, Spec};+use std::collections::BTreeMap;++#[test]+fn osm_masks_convert_to_maneuver_ordinals() {+ assert_eq!(osm_mask_to_dir_mask(LANE_THROUGH), 1 << 9);+ assert_eq!(osm_mask_to_dir_mask(LANE_NONE), 1 << 9, "unmarked reads as through");+ assert_eq!(osm_mask_to_dir_mask(0), 1 << 9, "an empty mask defaults to straight");+ assert_eq!(osm_mask_to_dir_mask(LANE_LEFT), 1 << 4);+ assert_eq!(osm_mask_to_dir_mask(LANE_SLIGHT_LEFT), 1 << 1);+ assert_eq!(osm_mask_to_dir_mask(LANE_SHARP_LEFT), 1 << 2);+ assert_eq!(osm_mask_to_dir_mask(LANE_RIGHT), 1 << 8);+ assert_eq!(osm_mask_to_dir_mask(LANE_SLIGHT_RIGHT), 1 << 5);+ assert_eq!(osm_mask_to_dir_mask(LANE_SHARP_RIGHT), 1 << 6);+ assert_eq!(osm_mask_to_dir_mask(LANE_MERGE_TO_LEFT), 1 << 1);+ assert_eq!(osm_mask_to_dir_mask(LANE_MERGE_TO_RIGHT), 1 << 5);+ let both = osm_mask_to_dir_mask(LANE_THROUGH | LANE_RIGHT);+ assert_eq!(both, (1 << 9) | (1 << 8), "a lane can offer two turns");+}++#[test]+fn lane_serves_tolerates_the_neighbouring_turn() {+ let left = osm_mask_to_dir_mask(LANE_LEFT);+ assert!(lane_serves(left, 4) && lane_serves(left, 1) && lane_serves(left, 2));+ assert!(!lane_serves(left, 8) && !lane_serves(left, 9));+ let right = osm_mask_to_dir_mask(LANE_RIGHT);+ assert!(lane_serves(right, 8) && lane_serves(right, 5) && lane_serves(right, 6));+ assert!(!lane_serves(right, 4));+ let through = osm_mask_to_dir_mask(LANE_THROUGH);+ assert!(lane_serves(through, 9) && !lane_serves(through, 4));+}++fn cross(lanes: Option<Vec<u8>>) -> Spec {+ // Centre node 0 with arms east(1) north(2) west(3) south(4); edge 3->0 is+ // the approach carrying the real lanes in the lane test.+ let mut edges = Vec::new();+ for (s, t) in [(3, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (2, 0), (4, 0)] {+ edges.push((s, t, 5u8, 50u8, 1_113_900u32));+ }+ Spec {+ nodes: vec![(0, 0), (0, 100_000), (100_000, 0), (0, -100_000), (-100_000, 0)],+ edges,+ escaped: vec![],+ names: BTreeMap::new(),+ pool: vec![],+ geom: BTreeMap::new(),+ lanes,+ elevation: None,+ }+}++#[test]+fn real_lanes_pack_dir_mask_and_validity() {+ // Approach edge (sorted index of 3->0) carries [through, left].+ let mut spec0 = cross(None);+ spec0.edges.sort();+ let approach = spec0.edges.iter().position(|e| (e.0, e.1) == (3, 0)).unwrap() as u32;+ let mut lanes = Vec::new();+ lanes.extend_from_slice(&1u32.to_le_bytes());+ lanes.extend_from_slice(&approach.to_le_bytes());+ lanes.extend_from_slice(&0u32.to_le_bytes());+ lanes.extend_from_slice(&(approach + 1).to_le_bytes());+ lanes.extend_from_slice(&4u32.to_le_bytes()); // blob length sentinel+ for m in [LANE_THROUGH, LANE_LEFT] {+ lanes.extend_from_slice(&m.to_le_bytes());+ }+ let g = assemble(&cross(Some(lanes)));+ // Sorted graph index differs from the spec position: find it via range.+ let (s, _) = g.edge_range(3);+ let packed = real_lanes(&g, s, 9).expect("real lanes present");+ assert_eq!(packed, [(1 << 9) << 1 | 1, (1 << 4) << 1], "straight valid, left not");+ let packed_left = real_lanes(&g, s, 4).unwrap();+ assert_eq!(packed_left, [(1 << 9) << 1, (1 << 4) << 1 | 1]);+ assert!(real_lanes(&g, INVALID_EDGE, 9).is_none());+ let (s0, _) = g.edge_range(0);+ assert!(real_lanes(&g, s0, 9).is_none(), "an untagged edge falls back to topology");+}++#[test]+fn junction_lanes_offer_left_straight_right_at_a_cross() {+ let g = assemble(&cross(None));+ // Arrive at the centre heading east (bearing 90), from the west arm (3).+ let lanes = junction_lanes(&g, 0, 3, 90.0, 9);+ assert_eq!(lanes.len(), 3, "left, straight and right: {lanes:?}");+ assert_eq!(lanes[0], (1 << 4) << 1, "leftmost is the left turn, not taken");+ assert_eq!(lanes[1], (1 << 9) << 1 | 1, "straight is taken");+ assert_eq!(lanes[2], (1 << 8) << 1, "rightmost is the right turn");+ // Taking the left instead just moves the valid bit.+ let left = junction_lanes(&g, 0, 3, 90.0, 4);+ assert_eq!(left[0] & 1, 1);+ assert_eq!(left[1] & 1, 0);+ // One option only (the way back excluded) means no guidance.+ let g2 = assemble(&cross(None));+ assert!(junction_lanes(&g2, 1, 0, 90.0, 9).is_empty(), "a dead-end arm has no choice");+ assert!(junction_lanes(&g2, 999, 0, 90.0, 9).is_empty(), "no such junction");+}