/// Everything in a way record after its id varint (see [`WaySink`]'s table), appended to `out`. /// Returns the largest ref, or zero for none -- the fold `WaySink` keeps. #[allow(clippy::too_many_arguments)] fn encode_way_tail( out: &mut Vec, class: &Class, refs: &[i64], name: Option<&str>, lane_count: u8, turn_fwd: &[u16], turn_bwd: &[u16], carriageway: Carriageway, building: Option, ) -> Result { put_uvarint(out, pack(class)?); put_uvarint(out, refs.len() as u64); let mut previous: i64 = 0; let mut max_ref: i64 = 0; for &node in refs { put_svarint(out, node.wrapping_sub(previous)); previous = node; max_ref = max_ref.max(node); } match name.filter(|n| !n.is_empty()) { Some(name) => { put_uvarint(out, name.len() as u64); out.extend_from_slice(name.as_bytes()); } None => put_uvarint(out, 0), } put_uvarint(out, lane_count as u64); // The turn masks: a count then each u16, forward then backward. Zero counts for the // overwhelming majority, which cost one byte each. for masks in [turn_fwd, turn_bwd] { put_uvarint(out, masks.len() as u64); for &m in masks { put_uvarint(out, m as u64); } } // The directional split, as one packed varint. Zero -- one byte -- when never surveyed. put_uvarint(out, pack_carriageway(carriageway)); // The building attributes: a presence byte, then the three packed words when present. A // non-building writes one zero byte; a building -- even one with no S3DB tags -- writes its // (usually all-zero) words so the tiler's side table stays dense-parallel to the layer. match building { Some(attrs) => { put_uvarint(out, 1); let (a, b, c) = pack_building(&attrs); put_uvarint(out, a); put_uvarint(out, b); put_uvarint(out, c); } None => put_uvarint(out, 0), } Ok(max_ref) } /// The sealed ways spill as independently decodable blocks. Shared read-only across the pool: /// every [`reader`](Self::reader) call is a positional read of one block. pub struct WayBlocks { file: Option, anon: Option>, locs: Vec, } impl WayBlocks { /// Open whichever backend the sink sealed -- the shared anon store when present, else the /// file at `path` -- with the index [`WaySink`] returned in its [`WayCounts`]. pub fn open( path: &Path, anon: &Option>, locs: Vec, ) -> Result { let file = match anon { Some(_) => None, None => Some( File::open(path).map_err(|e| Error(format!("cannot open {}: {e}", path.display())))?, ), }; Ok(WayBlocks { file, anon: anon.clone(), locs }) } pub fn locs(&self) -> &[WayBlockLoc] { &self.locs } /// A cursor over block `i` alone, positioned on its first record with the id its first delta /// is taken from. Yields exactly the records [`WayReader::open`] yields over that byte range. pub fn reader(&self, i: usize) -> Result { let loc = self.locs[i]; let len = usize::try_from(loc.len) .map_err(|_| Error("a ways spill block does not fit in memory".to_string()))?; let mut buf = vec![0u8; len]; match (&self.anon, &self.file) { (Some(anon), _) => anon .read_at(loc.offset, &mut buf) .map_err(|e| Error(format!("cannot read the anon ways spill: {e}")))?, (None, Some(file)) => read_exact_at(file, &mut buf, loc.offset) .map_err(|e| Error(format!("cannot read the ways spill: {e}")))?, (None, None) => return err("a ways spill with no backend".to_string()), } Ok(WayReader { inner: WayIn::Slice { buf, used: 0 }, last_id: loc.start_last_id, seen: 0, }) } } /// Positional read of exactly `buf.len()` bytes, safe to call from many threads on one `File`. fn read_exact_at(file: &File, mut buf: &mut [u8], mut offset: u64) -> std::io::Result<()> { while !buf.is_empty() { #[cfg(windows)] let n = std::os::windows::fs::FileExt::seek_read(file, buf, offset)?; #[cfg(unix)] let n = std::os::unix::fs::FileExt::read_at(file, buf, offset)?; if n == 0 { return Err(std::io::Error::new( std::io::ErrorKind::UnexpectedEof, "the ways spill ended inside a block", )); } buf = &mut buf[n..]; offset += n as u64; } Ok(()) } #[cfg(test)] mod way_block_tests { use super::*; fn class(layer: u8, kind: u16) -> Class { Class { layer, kind, kind_detail: 0, flags: 0, area: false, min_zoom: 12, min_area_px: 0.0 } } /// Pushing ways one at a time and pushing the same ways as worker-built blocks must write the /// same bytes, report the same counts, and read back the same records both through the /// sequential cursor and block by block -- on both backends. #[test] fn blocks_write_the_same_stream_and_read_back_block_by_block() { let dir = std::env::temp_dir().join(format!("mamaps_wayblock_{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); type WayRow = (i64, Vec, Option, u8, Vec); let mut ways: Vec = Vec::new(); let mut id = 7i64; for i in 0..10_000i64 { id += 1 + (i % 5) * 1000; let refs: Vec = (0..(2 + i % 9)).map(|k| 1_000_000 + i * 3 + k * 17).collect(); let name = (i % 7 == 0).then(|| format!("Road {i}")); ways.push((id, refs, name, (i % 4) as u8, if i % 11 == 0 { vec![1, 4] } else { vec![] })); } let c = class(tilecodec::mamaps::dict::LAYER_ROADS, 3); for anon in [false, true] { let one_path = dir.join(format!("one{anon}.tmp")); let blk_path = dir.join(format!("blk{anon}.tmp")); let plan = if anon { osm_ingest::mem::SpillPlan::Anon } else { osm_ingest::mem::SpillPlan::File }; let mut one = WaySink::create_planned(&one_path, plan).unwrap(); let mut blk = WaySink::create_planned(&blk_path, plan).unwrap(); let mut block = WayBlock::new(); for (n, (id, refs, name, lanes, turns)) in ways.iter().enumerate() { one.push(*id, &c, refs, name.as_deref(), *lanes, turns, &[], Carriageway::default(), None) .unwrap(); block .push(*id, &c, refs, name.as_deref(), *lanes, turns, &[], Carriageway::default(), None) .unwrap(); // Uneven block sizes, including one-way blocks, to exercise coalescing. if n % 1237 == 0 || block.len() >= 3000 { blk.push_block(&std::mem::take(&mut block)).unwrap(); } } blk.push_block(&block).unwrap(); let (c1, s1) = one.finish_either().unwrap(); let (c2, s2) = blk.finish_either().unwrap(); assert_eq!((c1.ways, c1.refs, c1.max_ref), (c2.ways, c2.refs, c2.max_ref)); let bytes = |path: &Path, s: Option<&tile_build::anon::AnonStore>| -> Vec { match s { Some(a) => { let mut v = vec![0u8; a.len() as usize]; a.read_at(0, &mut v).unwrap(); v } None => std::fs::read(path).unwrap(), } }; let s2 = s2.map(std::sync::Arc::new); let b1 = bytes(&one_path, s1.as_ref()); let b2 = bytes(&blk_path, s2.as_deref()); assert_eq!(b1, b2, "the block path must write the per-way stream byte for byte"); for counts in [&c1, &c2] { assert!(counts.blocks.iter().all(|l| l.ways <= WAY_BLOCK_WAYS)); assert_eq!(counts.blocks.iter().map(|l| l.ways).sum::(), ways.len() as u64); } // Block-by-block decode equals the sequential cursor, record for record. let blocks = WayBlocks::open(&blk_path, &s2, c2.blocks.clone()).unwrap(); let mut seq = WayReader::open_either(&blk_path, &s2).unwrap(); let (mut r1, mut r2) = (Vec::new(), Vec::new()); for i in 0..blocks.locs().len() { let mut reader = blocks.reader(i).unwrap(); let mut n = 0u64; while let Some(a) = reader.next(&mut r1).unwrap() { let b = seq.next(&mut r2).unwrap().expect("sequential has as many records"); assert_eq!(a.0, b.0); assert_eq!(a.2, b.2); assert_eq!(a.3, b.3); assert_eq!(a.4, b.4); assert_eq!(r1, r2); n += 1; } assert_eq!(n, blocks.locs()[i].ways); } assert!(seq.next(&mut r2).unwrap().is_none()); } let _ = std::fs::remove_dir_all(&dir); } /// The ordering rule holds across a block boundary, not only inside one. #[test] fn a_block_that_does_not_advance_is_refused() { let path = std::env::temp_dir().join(format!("mamaps_wayblock_order_{}.tmp", std::process::id())); let c = class(tilecodec::mamaps::dict::LAYER_ROADS, 3); let mut sink = WaySink::create_planned(&path, osm_ingest::mem::SpillPlan::Anon).unwrap(); let mut a = WayBlock::new(); a.push(10, &c, &[1, 2], None, 0, &[], &[], Carriageway::default(), None).unwrap(); sink.push_block(&a).unwrap(); let mut b = WayBlock::new(); b.push(10, &c, &[1, 2], None, 0, &[], &[], Carriageway::default(), None).unwrap(); assert!(sink.push_block(&b).is_err()); assert!(a.push(9, &c, &[1, 2], None, 0, &[], &[], Carriageway::default(), None).is_err()); } } // --- zoom decode for the parallel map reader -------------------------------------------------------- /// The staged features opened for positional, many-thread decoding: one handle shared by every /// decode thread of [`crate::tiler`]'s map reader. pub struct ZoomChunks { inner: NormalizedChunks, } impl Store { /// Open the staged bytes for [`ZoomChunks::decode`]. Same backend choice as every other reader. pub fn zoom_chunks(&self) -> Result { Ok(ZoomChunks { inner: self.open_chunks()? }) } } impl ZoomChunks { /// Spill chunk `chunk`'s features that zoom `z` draws, in file order, plus each one's vertex /// count. Exactly what a [`ZoomReader`] lane yields for that chunk -- the same `read_into`, the /// same `feature_of`, the same zoom window -- so a reader that concatenates these in wanted /// order sees the stream `reader_for_zoom` delivers. pub fn decode( &self, chunk: usize, z: u8, scratch: &mut Vec, records: &mut Vec, ) -> Result<(Vec, Vec)> { self.inner .read_into(chunk, scratch, records) .map_err(|e| osm_ingest::proto::Error(e.to_string()))?; let mut features = Vec::with_capacity(records.len()); let mut counts = Vec::with_capacity(records.len()); for record in records.drain(..) { let feature = feature_of(record)?; // The zoom window: floor is the feature's own `min_zoom`, ceiling the layer cap // (`MAX_ZOOM_PER_LAYER`). The same test `ZoomReader`'s lanes apply. if z >= feature.class.min_zoom && z <= crate::schema::max_zoom_for_layer(feature.class.layer) { counts.push(geometry_vertices(&feature.geometry)); features.push(feature); } } Ok((features, counts)) } } /// Every vertex in a geometry, all parts and rings: the measure the map reader cuts chunks by. pub fn geometry_vertices(geometry: &Geometry) -> usize { match geometry { Geometry::Points(points) => points.len(), Geometry::Lines(lines) => lines.iter().map(Vec::len).sum(), Geometry::Polygons(polygons) => polygons.iter().flatten().map(Vec::len).sum(), } } impl Store { /// Parallel scan with a cheap pre-filter on each record's packed class and /// whether it carries a feature id: records it rejects are never turned into features (their /// geometry is never decoded), so it must accept every record `keep` could keep. pub fn par_scan_where(&self, pre: P, keep: F) -> Result> where T: Send, P: Fn(&Class, bool) -> bool + Sync + 'static, F: Fn(Feature) -> Option + Sync, { let pre = move |props: &[(String, Value)]| -> bool { let class = props.iter().find_map(|(k, v)| match (k.as_str(), v) { (CLASS_KEY, Value::Uint(bits)) => Some(unpack(*bits)), _ => None, }); // A record with no class is corrupt: let it through so `feature_of` reports it. let Some(class) = class else { return true }; pre(&class, props.iter().any(|(k, _)| k == ID_KEY)) }; use rayon::prelude::*; let chunks = self.open_chunks()?; let n = chunks.chunk_count(); // Groups bound what is in flight (one `Vec` header per chunk) on a 21 M-chunk planet. const GROUP: usize = 1 << 16; let mut out = Vec::new(); let mut start = 0usize; while start < n { let end = (start + GROUP).min(n); let results: Vec>> = tile_build::par::install(|| { (start..end) .into_par_iter() .map_init( || (Vec::new(), Vec::new()), |(scratch, records), i| -> Result> { chunks .read_into_where(i, scratch, records, &pre) .map_err(|e| osm_ingest::proto::Error(e.to_string()))?; let mut kept = Vec::new(); for record in records.drain(..) { if let Some(v) = keep(feature_of(record)?) { kept.push(v); } } Ok(kept) }, ) .collect() }); for r in results { out.extend(r?); } start = end; } Ok(out) } }