fn build_from_chunked( meta: &[u8], nodes: &[u8], edges: &[u8], out: &Path, chunk_nodes: u32, ) -> io::Result { let walk = GraphWalk::open(meta, nodes, edges)?; let n = walk.node_count as u64; let full_edges = u64_at(meta, 16); let chunk_nodes = chunk_nodes.max(1); let units: Vec = (0..n.div_ceil(u64::from(chunk_nodes))).map(|c| c as u32).collect(); let range = |c: u32| -> (u32, u32) { let a = u64::from(c) * u64::from(chunk_nodes); (a as u32, (a + u64::from(chunk_nodes)).min(n) as u32) }; // Pass 1: every endpoint of an arterial edge is on the overlay. A target may sit in any // range, so the bitmap is shared; `fetch_or` makes the result independent of which // thread sets a bit first. let shared: Vec = (0..n.div_ceil(8)).map(|_| AtomicU8::new(0)).collect(); let set = |id: u32| { shared[(id / 8) as usize].fetch_or(1 << (id % 8), Ordering::Relaxed); }; let pass1 = par::map_chunks(&units, 1, |_, unit| -> io::Result { let (a, b) = range(unit[0]); let mut art = Arterials::default(); walk.for_range(a, b, |u, lat, lon, es| { let before = art.edges.len(); for (i, e) in es.iter().filter(|(_, e)| on_overlay(e.type_)) { if u64::from(e.target) >= n { return Err(bad(format!( "edge from {u} targets {} past the node count", e.target ))); } set(u); set(e.target); art.edges.push((u, *i, *e)); } if art.edges.len() > before { art.sources.push((u, lat, lon)); } Ok(()) })?; Ok(art) }); // The first failing range in range order is the first failure a sequential walk meets. let pass1: Vec = pass1.into_iter().collect::>()?; let present: Vec = shared.into_iter().map(AtomicU8::into_inner).collect(); // Rank index: set bits before each 64-byte block, then the total. let blocks = n.div_ceil(RANK_BLOCK_BYTES * 8); let mut rank = Vec::with_capacity(blocks as usize + 1); let mut running = 0u64; for b in 0..=blocks { rank.push(running); let lo = (b * RANK_BLOCK_BYTES) as usize; let hi = (lo + RANK_BLOCK_BYTES as usize).min(present.len()); if lo < hi { running += present[lo..hi].iter().map(|x| u64::from(x.count_ones())).sum::(); } } let m = running; let of = |id: u32| -> u32 { let byte = u64::from(id) / 8; let block = byte / RANK_BLOCK_BYTES; let mut r = rank[block as usize]; for x in &present[(block * RANK_BLOCK_BYTES) as usize..byte as usize] { r += u64::from(x.count_ones()); } (r + u64::from((present[byte as usize] & ((1u8 << (id % 8)) - 1)).count_ones())) as u32 }; let is_set = |id: u32| present[(id / 8) as usize] & (1 << (id % 8)) != 0; // Pass 2: emit nodes in full-id order with their arterial out-edges, per range. let pass2 = par::map_chunks(&units, 1, |_, unit| -> io::Result { let (a, b) = range(unit[0]); let art = &pass1[unit[0] as usize]; let mut em = Emitted { nodes: Vec::new(), edges: Vec::new(), edge_count: 0 }; let mut cache = BlockCache::new(1); let (mut si, mut ei) = (0usize, 0usize); for u in a..b { if !is_set(u) { continue; } // Every source is on the overlay, so the cursor meets them in order. let (lat, lon) = match art.sources.get(si) { Some(&(s, lat, lon)) if s == u => { si += 1; (lat, lon) } _ => { let (lat, lon, _) = walk.node_at(u64::from(u), &mut cache)?; (lat, lon) } }; let mut rec = [0u8; NODE_LEN]; rec[0..4].copy_from_slice(&lat.to_le_bytes()); rec[4..8].copy_from_slice(&lon.to_le_bytes()); // Relative; rebased in the merge below. rec[8..12].copy_from_slice(&(em.edge_count as u32).to_le_bytes()); rec[12..16].copy_from_slice(&u.to_le_bytes()); em.nodes.extend_from_slice(&rec); while let Some(&(src, i, e)) = art.edges.get(ei) { if src != u { break; } let mut rec = [0u8; EDGE_LEN]; rec[0..4].copy_from_slice(&of(e.target).to_le_bytes()); rec[4..8].copy_from_slice(&e.dist_mm.to_le_bytes()); rec[8..16].copy_from_slice(&i.to_le_bytes()); rec[16] = e.type_; rec[17] = e.speed_limit; em.edges.extend_from_slice(&rec); em.edge_count += 1; ei += 1; } } Ok(em) }); drop(pass1); // Ordered merge: rebase each range's edge pointers on the edges before it. let mut node_recs: Vec = Vec::with_capacity((m as usize + 1) * NODE_LEN); let mut edge_recs: Vec = Vec::new(); let mut k = 0u64; for em in pass2 { let em = em?; for rec in em.nodes.chunks_exact(NODE_LEN) { let ptr = u32::try_from(k + u64::from(u32_at(rec, 8))) .map_err(|_| bad("overlay edge count past u32"))?; node_recs.extend_from_slice(&rec[0..8]); node_recs.extend_from_slice(&ptr.to_le_bytes()); node_recs.extend_from_slice(&rec[12..16]); } edge_recs.extend_from_slice(&em.edges); k += em.edge_count; } let mut sentinel = [0u8; NODE_LEN]; sentinel[8..12].copy_from_slice( &u32::try_from(k).map_err(|_| bad("overlay edge count past u32"))?.to_le_bytes(), ); sentinel[12..16].copy_from_slice(&u32::MAX.to_le_bytes()); node_recs.extend_from_slice(&sentinel); let nodes_sec = blocked_section(&node_recs, NODE_LEN); drop(node_recs); let edges_sec = blocked_section(&edge_recs, EDGE_LEN); drop(edge_recs); // One large buffer: the file is written in a few big sequential extents. let mut f = io::BufWriter::with_capacity(8 << 20, std::fs::File::create(out)?); f.write_all(&OVERLAY_MAGIC.to_le_bytes())?; f.write_all(&OVERLAY_VERSION.to_le_bytes())?; for v in [n, full_edges, m, k, nodes_sec.len() as u64, edges_sec.len() as u64] { f.write_all(&v.to_le_bytes())?; } let nodes_end = 56 + nodes_sec.len() as u64; let edges_end = align8(nodes_end) + edges_sec.len() as u64; f.write_all(&nodes_sec)?; f.write_all(&vec![0u8; (align8(nodes_end) - nodes_end) as usize])?; f.write_all(&edges_sec)?; f.write_all(&vec![0u8; (align8(edges_end) - edges_end) as usize])?; for r in &rank { f.write_all(&r.to_le_bytes())?; } f.write_all(&present)?; f.flush()?; let bytes = align8(edges_end) + rank.len() as u64 * 8 + present.len() as u64; Ok(OverlayStats { full_nodes: n, full_edges, nodes: m, edges: k, bytes }) } /// `records` as a ZBLK section, byte-identical to what /// [`tilecodec::blocked::BlockedStreamWriter`] writes for the same records, with the /// blocks compressed in parallel. /// /// The stream writer compresses each 4096-record block on its own with a fresh encoder, so /// a block's frame depends on that block's bytes alone. Each frame here is taken from /// [`write_blocked_with`] over that one block — tilecodec's own encoder and settings, so /// the two cannot drift — and the header and offset table are laid out as the module docs /// of `tilecodec::blocked` specify. `blocked_section_matches_the_stream_writer` pins the /// equality. fn blocked_section(records: &[u8], record_len: usize) -> Vec { assert_eq!(records.len() % record_len, 0, "whole records only"); let per_block = BLOCK_RECORDS as usize * record_len; let blocks: Vec<&[u8]> = records.chunks(per_block).collect(); let frames: Vec> = par::map_chunks(&blocks, 1, |_, block| { let one = write_blocked_with(block[0], record_len, BLOCK_RECORDS); let parsed = Blocked::parse(&one).expect("a section tilecodec just wrote"); let lo = parsed.block_offset(0).expect("one block") as usize; let hi = parsed.block_offset(1).expect("one block") as usize; one[lo..hi].to_vec() }); let mut out = Vec::with_capacity( 28 + (frames.len() + 1) * 8 + frames.iter().map(Vec::len).sum::(), ); out.extend_from_slice(&BLOCKED_MAGIC.to_le_bytes()); out.extend_from_slice(&0u32.to_le_bytes()); out.extend_from_slice(&(record_len as u32).to_le_bytes()); out.extend_from_slice(&BLOCK_RECORDS.to_le_bytes()); out.extend_from_slice(&(records.len() as u64).to_le_bytes()); out.extend_from_slice(&(frames.len() as u32).to_le_bytes()); let mut off = (28 + (frames.len() + 1) * 8) as u64; for f in &frames { out.extend_from_slice(&off.to_le_bytes()); off += f.len() as u64; } out.extend_from_slice(&off.to_le_bytes()); for f in &frames { out.extend_from_slice(f); } out } #[cfg(test)] mod tests { use super::*; /// A motorway A-B-C, a motorway_link C-D, residential D-E and B-F. fn sample(tag: &str) -> std::path::PathBuf { let p = |i: i32| (370_000_000 + i * 10_000, -1_220_000_000 + i * 10_000); let nodes: Vec<(i64, i32, i32)> = (1..=6).map(|id| (id as i64, p(id).0, p(id).1)).collect(); let nodes = [nodes[0], nodes[1], nodes[2], nodes[3], nodes[4], (6, p(2).0 + 5_000, p(2).1 - 5_000)]; let ways: [(i64, &str, &[i64]); 4] = [ (10, "motorway", &[1, 2, 3]), (11, "motorway_link", &[3, 4]), (12, "residential", &[4, 5]), (13, "residential", &[2, 6]), ]; let (pbf, dir) = crate::testpbf::write_highway_sample(tag, &nodes, &ways); crate::graph_build::build(&pbf, &dir).unwrap(); dir } struct Decoded { header: [u64; 6], nodes: Vec<(i32, i32, u32, u32)>, edges: Vec<(u32, u32, u64, u8)>, } fn decode(bytes: &[u8]) -> Decoded { assert_eq!(u32_at(bytes, 0), OVERLAY_MAGIC); assert_eq!(u32_at(bytes, 4), OVERLAY_VERSION); let header: [u64; 6] = std::array::from_fn(|i| u64_at(bytes, 8 + i * 8)); let (nodes_len, edges_len) = (header[4] as usize, header[5] as usize); let inflate = |b: &[u8]| { let v = Blocked::parse(b).unwrap(); let mut c = BlockCache::new(0); (0..v.block_count()).flat_map(|i| c.get(&v, i).unwrap().clone()).collect::>() }; let nb = inflate(&bytes[56..56 + nodes_len]); let edges_at = align8(56 + nodes_len as u64) as usize; let eb = inflate(&bytes[edges_at..edges_at + edges_len]); let nodes = nb .chunks(NODE_LEN) .map(|r| { ( i32::from_le_bytes(r[0..4].try_into().unwrap()), i32::from_le_bytes(r[4..8].try_into().unwrap()), u32_at(r, 8), u32_at(r, 12), ) }) .collect(); let edges = eb .chunks(EDGE_LEN) .map(|r| (u32_at(r, 0), u32_at(r, 4), u64_at(r, 8), r[16])) .collect(); Decoded { header, nodes, edges } } #[test] fn the_overlay_holds_the_arterials_and_their_ramps_only() { let dir = sample("overlay_arterials"); let out = dir.join("overlay.bin"); let stats = build(&dir, &out).unwrap(); let d = decode(&std::fs::read(&out).unwrap()); assert_eq!(d.header[0], stats.full_nodes); assert_eq!((d.header[2], d.header[3]), (stats.nodes, stats.edges)); assert_eq!(d.nodes.len() as u64, stats.nodes + 1, "plus the sentinel"); assert_eq!(d.nodes.last().unwrap().2 as u64, stats.edges, "sentinel edge_ptr is K"); // Coordinates identify the full nodes regardless of compaction. let p = |i: i32| (370_000_000 + i * 10_000, -1_220_000_000 + i * 10_000); let coords: Vec<(i32, i32)> = d.nodes[..stats.nodes as usize].iter().map(|n| (n.0, n.1)).collect(); for id in [1, 4] { assert!(coords.contains(&p(id)), "motorway end / ramp end {id} is on the overlay"); } assert!(!coords.contains(&p(5)), "the residential-only end is not"); // Each overlay edge is the full edge it names: same source, same target. let meta = std::fs::read(dir.join("metadata.bin")).unwrap(); let (nodes, edges) = (map(&dir.join("nodes.bin")).unwrap(), map(&dir.join("edges.bin")).unwrap()); let walk = GraphWalk::open(&meta, &nodes, &edges).unwrap(); let mut full: Vec<(u32, u64, u32, u8)> = Vec::new(); walk.for_each(|u, _, _, es| { full.extend(es.iter().map(|(i, e)| (u, *i, e.target, e.type_))); Ok(()) }) .unwrap(); let mut k = 0usize; for (o, n) in d.nodes[..stats.nodes as usize].iter().enumerate() { let end = d.nodes[o + 1].2 as usize; for &(t, _, full_edge, ty) in &d.edges[n.2 as usize..end] { let &(src, _, tgt, fty) = full.iter().find(|f| f.1 == full_edge).unwrap(); assert_eq!(src, n.3, "overlay node {o} owns full edge {full_edge}"); assert_eq!(tgt, d.nodes[t as usize].3, "target maps back"); assert_eq!(ty, fty); assert!(on_overlay(ty)); k += 1; } } assert_eq!(k as u64, stats.edges); assert_eq!( k, full.iter().filter(|f| on_overlay(f.3)).count(), "every arterial edge, nothing else" ); // Full ids ascend, so the rank map is exact. assert!(d.nodes[..stats.nodes as usize].windows(2).all(|w| w[0].3 < w[1].3)); } #[test] fn the_overlay_is_byte_identical_across_runs() { let dir = sample("overlay_determinism"); build(&dir, &dir.join("a.bin")).unwrap(); build(&dir, &dir.join("b.bin")).unwrap(); assert_eq!( std::fs::read(dir.join("a.bin")).unwrap(), std::fs::read(dir.join("b.bin")).unwrap() ); } #[test] fn the_overlay_is_byte_identical_across_work_splits_and_thread_counts() { let dir = sample("overlay_splits"); build(&dir, &dir.join("ref.bin")).unwrap(); let want = std::fs::read(dir.join("ref.bin")).unwrap(); let meta = std::fs::read(dir.join("metadata.bin")).unwrap(); let (nodes, edges) = (map(&dir.join("nodes.bin")).unwrap(), map(&dir.join("edges.bin")).unwrap()); // One node per range puts every range boundary between a source and its targets, // so a target bit, a target-only node's coordinates and an edge pointer all cross // a range on every edge. for chunk in [1, 2, 3, 5, CHUNK_NODES] { for threads in [1, 3, 8] { crate::par::set_threads(threads); let out = dir.join(format!("c{chunk}_t{threads}.bin")); build_from_chunked(&meta, &nodes, &edges, &out, chunk).unwrap(); assert_eq!( std::fs::read(&out).unwrap(), want, "chunk {chunk}, {threads} thread(s)" ); } } crate::par::clear_threads(); } #[test] fn blocked_section_matches_the_stream_writer() { // Several full blocks plus a tail, a single partial block, exactly one block, and // nothing at all, at both overlay strides. let mut x = 0x9E37_79B9_7F4A_7C15u64; for record_len in [NODE_LEN, EDGE_LEN] { for count in [0usize, 1, 4095, 4096, 4097, 3 * 4096 + 17] { let records: Vec = (0..count * record_len) .map(|i| { x ^= x << 13; x ^= x >> 7; x ^= x << 17; // Compressible but not trivially: a slow counter plus noise. if i % 4 == 0 { (x & 0x0F) as u8 } else { (i / 97) as u8 } }) .collect(); let scratch = std::env::temp_dir() .join(format!("overlay_bs_{}_{record_len}_{count}.tmp", std::process::id())); let mut w = tilecodec::blocked::BlockedStreamWriter::create(record_len, &scratch).unwrap(); // Pushed in odd-sized runs, as the old builder pushed one record at a time. for run in records.chunks(record_len * 7) { w.push(run).unwrap(); } assert_eq!( blocked_section(&records, record_len), w.finish().unwrap(), "{record_len} B x {count}" ); } } } }