impl Collector { /// Open the partition files. `stem` is a scratch path; each partition appends to it. pub fn create(stem: &Path) -> Result { let mut files = Vec::with_capacity(PARTITIONS); let mut paths = Vec::with_capacity(PARTITIONS); for i in 0..PARTITIONS { let path = stem.with_extension(format!("lanefill{i:03}.tmp")); // Read and write on one handle, so `finish` reads the partition back through it and // the name can be unlinked straight away: a build killed mid-scan leaves nothing. let file = std::fs::OpenOptions::new() .read(true) .write(true) .create(true) .truncate(true) .open(&path) .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?; // Small buffers: there are `PARTITIONS` of them held open at once, and each takes a // steady trickle rather than a burst. files.push(BufWriter::with_capacity(1 << 14, file)); paths.push(path); } let mut unlinked = true; for path in &paths { unlinked &= osm_ingest::mem::unlink_open_scratch(path); } Ok(Collector { files, paths, unlinked }) } /// Offer one way to the join. Ways that cannot take part are dropped here. #[cfg_attr(not(test), allow(dead_code))] pub fn push(&mut self, segment: &Segment) -> Result<()> { match prepare(segment) { Some(prepared) => self.push_prepared(&prepared), None => Ok(()), } } /// Write the two endpoint records [`prepare`] built, in the order `push` always wrote them /// (first end, then last end). Split from `push` so the geometry -- length, bearings, name /// hash -- runs on the pool and only these two fixed-width writes stay serial. pub fn push_prepared(&mut self, prepared: &Prepared) -> Result<()> { for record in prepared.0 { record.write(&mut self.files[partition_of(record.node)])?; } Ok(()) } /// Resolve every partition and return `(way id, inherited lane count)` for the ways that /// actually change, ascending by way id so the materialise pass can binary-search it. /// /// Ways whose inherited count equals the default they would have had anyway are left out, the /// same way [`crate::corridor::promote`] leaves out ways its corridor does not move. pub fn finish(mut self) -> Result> { let mut files: Vec = Vec::with_capacity(self.files.len()); for file in std::mem::take(&mut self.files) { files.push( file.into_inner() .map_err(|e| Error(format!("cannot flush a lanefill partition: {e}")))?, ); } // `(way, end, donor lanes, one-way)`. The only state that outlives a partition, because a // way's two endpoints hash to two different files and the "donor at both ends" condition // cannot be decided until both have been seen. // // The 256 partitions are independent — every record for a node lives in exactly the one // partition `partition_of` sends it to — so each is read, sorted and paired on its own // thread and the per-partition pairs concatenated. `found` is globally sorted below, so the // concatenation order never reaches the output: the resolution stays independent of both // the write order and the partition order. let per_partition: Vec> = par::install(|| { files .par_iter_mut() .zip(self.paths.par_iter()) .map(|(file, path)| -> Result> { let mut records: Vec = Vec::new(); read_partition(file, path, &mut records)?; let mut local: Vec<(i64, u8, u8, bool)> = Vec::new(); if !records.is_empty() { // Sorted rather than hashed, for the reason `corridor::promote` gives: a // hash map over the record count is the largest thing this pass would // otherwise allocate. The full key makes the order total, so the output // does not depend on the write order. records.sort_unstable_by_key(|r| (r.node, r.way, r.flags)); for run in records.chunk_by(|a, b| a.node == b.node) { pair_up(run, &mut local); } } Ok(local) }) .collect::>>() })?; let mut found: Vec<(i64, u8, u8, bool)> = per_partition.into_iter().flatten().collect(); drop(files); if !self.unlinked { for path in &self.paths { let _ = std::fs::remove_file(path); } } found.sort_unstable(); let mut out: Vec<(i64, u8)> = Vec::new(); for run in found.chunk_by(|a, b| a.0 == b.0) { if !run.iter().any(|e| e.1 == 0) || !run.iter().any(|e| e.1 == 1) { continue; } let inherited = run.iter().map(|e| e.2).min().unwrap_or(0); // What the renderer would have drawn without us: `tile/geometry.rs` turns a zero lane // count into one lane for a one-way and two for anything else. let default = if run[0].3 { 1 } else { 2 }; if inherited != default { out.push((run[0].0, inherited)); } } Ok(out) } } impl Drop for Collector { /// Only where the names could not be unlinked at creation: a collector dropped on an error /// path must not leave its partitions behind. fn drop(&mut self) { if !self.unlinked { self.files.clear(); for path in &self.paths { let _ = std::fs::remove_file(path); } } } } /// Every recipient in `run` against every donor, appending the pairs that survive the conditions. fn pair_up(run: &[Record], found: &mut Vec<(i64, u8, u8, bool)>) { for recipient in run.iter().filter(|r| r.lanes == 0) { for donor in run.iter().filter(|d| d.lanes > 0) { if donor.way == recipient.way || donor.name_hash != recipient.name_hash || donor.oneway() != recipient.oneway() { continue; } if deviation(f64::from(recipient.bearing), f64::from(donor.bearing)) > MAX_TURN_DEGREES { continue; } found.push((recipient.way, recipient.end(), donor.lanes, recipient.oneway())); } } } fn read_partition(file: &mut File, path: &Path, out: &mut Vec) -> Result<()> { out.clear(); std::io::Seek::rewind(file) .map_err(|e| Error(format!("cannot rewind {}: {e}", path.display())))?; let mut bytes = Vec::new(); file.read_to_end(&mut bytes) .map_err(|e| Error(format!("cannot read {}: {e}", path.display())))?; if bytes.len() % RECORD_LEN != 0 { return err(format!( "{} holds {} bytes, which is not a whole number of {RECORD_LEN}-byte records", path.display(), bytes.len(), )); } out.reserve(bytes.len() / RECORD_LEN); for chunk in bytes.chunks_exact(RECORD_LEN) { out.push(Record::read(chunk)); } Ok(()) } /// Which partition an endpoint node belongs to. /// /// Mixed rather than taken modulo directly: OSM node ids are allocated in runs, so the low bits of /// neighbouring ids are correlated and a plain modulo would fill a few partitions and starve the /// rest. This is the SplitMix64 finaliser, which is cheap and spreads the low bits. fn partition_of(node: i64) -> usize { let mut z = (node as u64) ^ 0x9e37_79b9_7f4a_7c15; z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); ((z ^ (z >> 31)) % PARTITIONS as u64) as usize } /// FNV-1a over the name's bytes. See the module docs on why a collision is survivable. fn hash_name(name: &str) -> u64 { let mut hash: u64 = 0xcbf2_9ce4_8422_2325; for byte in name.as_bytes() { hash ^= u64::from(*byte); hash = hash.wrapping_mul(0x0000_0100_0000_01b3); } hash } /// The bearing leaving the line's first (or last) point, walking past repeated coordinates. /// /// `None` when every point is the same place, which has no direction to report. fn leaving(line: &[(f64, f64)], from_start: bool) -> Option { if from_start { let origin = *line.first()?; Some(bearing(origin, *line.iter().skip(1).find(|p| **p != origin)?)) } else { let origin = *line.last()?; Some(bearing(origin, *line.iter().rev().skip(1).find(|p| **p != origin)?)) } } /// Bearing from `a` to `b` in degrees clockwise from north. Both are lon/lat. fn bearing(a: (f64, f64), b: (f64, f64)) -> f64 { let north = b.1 - a.1; let east = (b.0 - a.0) * a.1.to_radians().cos(); east.atan2(north).to_degrees() } /// How far two bearings are from being a straight continuation of one another, in degrees. /// /// Both point *away* from the node they share, so a road running straight through it leaves on two /// bearings 180° apart and scores zero. fn deviation(a: f64, b: f64) -> f64 { let mut delta = (a - b) % 360.0; if delta > 180.0 { delta -= 360.0; } else if delta < -180.0 { delta += 360.0; } (180.0 - delta.abs()).abs() } include!("lanefill_part1.rs"); #[cfg(test)] mod lazy_tests { use super::*; /// `prepare_lazy` decides every way exactly as `prepare` on its full line does: same `None`s, /// same records, for donors and recipients, short and long, with repeated vertices at either /// end and degenerate ways. #[test] fn lazy_preparation_matches_preparing_the_whole_line() { let mut state = 0x2545_F491_4F6C_DD1Du64; let mut next = || { state ^= state << 13; state ^= state >> 7; state ^= state << 17; state }; for case in 0..20_000i64 { let n = 2 + (next() % 12) as usize; let step = [1e-6, 1e-5, 1e-4, 3e-4][(next() % 4) as usize]; let mut line = Vec::with_capacity(n); let (mut x, mut y) = (-122.3 + (next() % 1000) as f64 * 1e-3, 37.5); for _ in 0..n { if next() % 5 != 0 { x += ((next() % 200) as f64 - 100.0) * step; y += ((next() % 200) as f64 - 100.0) * step; } line.push((x, y)); } let mut nodes: Vec = (0..n as i64).map(|k| 1000 + k).collect(); if case % 9 == 0 { let last = nodes.len() - 1; nodes[last] = nodes[0]; } let lanes = (next() % 3) as u8; let oneway = next() % 2 == 0; let name = if case % 13 == 0 { "" } else { "Main St" }; let whole = prepare(&Segment { id: case, name, lanes, oneway, nodes: &nodes, line: &line }); let lazy = prepare_lazy(case, name, lanes, oneway, &nodes, |i| line[i]); match (whole, lazy) { (None, None) => {} (Some(a), Some(b)) => { for (ra, rb) in a.0.iter().zip(b.0.iter()) { let (mut ba, mut bb) = (Vec::new(), Vec::new()); ra.write(&mut ba).unwrap(); rb.write(&mut bb).unwrap(); assert_eq!(ba, bb, "case {case}"); } } (a, b) => panic!("case {case}: whole {} lazy {}", a.is_some(), b.is_some()), } } } /// The partition files are unlinked at creation on Unix: their directory is empty while the /// collector is live, and `finish` still reads every record back through the handles. #[test] fn partitions_leave_no_names_behind() { let dir = std::env::temp_dir().join(format!("mamaps_lanefill_unlink_{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let mut c = Collector::create(&dir.join("tiles.features.tmp")).unwrap(); let line = [(-122.0, 37.0), (-122.0, 37.0001)]; let a = Segment { id: 1, name: "A St", lanes: 0, oneway: false, nodes: &[10, 11], line: &line }; c.push(&a).unwrap(); #[cfg(unix)] assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "a partition name was left"); let _ = c.finish().unwrap(); assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0); std::fs::remove_dir(&dir).unwrap(); } }