impl WaySink { #[cfg(test)] pub fn create(path: &Path) -> Result { let file = File::create(path) .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?; Ok(WaySink { // A megabyte, because the writes are a few dozen bytes each and there are millions. out: WayOut::File(BufWriter::with_capacity(1 << 20, file)), record: Vec::new(), last_id: 0, count: 0, refs: 0, max_ref: 0, at: 0, blocks: Vec::new(), }) } /// Anonymous twin of [`create`](Self::create): same records in pagefile-backed /// memory, no file. `path` names nothing — it only rides /// along for error messages. Pair with [`WaySink::finish_anon`]. #[cfg(test)] pub fn create_anon(path: &Path) -> Result { Self::create_planned(path, osm_ingest::mem::SpillPlan::Anon) } /// Create with an explicit staging plan. See [`Sink::create_planned`]: the budget gate picks /// `File` when anon commit does not fit, and `File` stages through the `.tmp` at `path`, /// removed after materialise like every other scratch file. Pair with /// [`finish_either`](Self::finish_either). pub fn create_planned(path: &Path, plan: osm_ingest::mem::SpillPlan) -> Result { let out = match plan { osm_ingest::mem::SpillPlan::Anon => { WayOut::Anon(tile_build::anon::AnonStore::new()) } osm_ingest::mem::SpillPlan::File => { eprintln!(" [stage A] ways spill -> {} (file backend: commit budget)", path.display()); let file = File::create(path) .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?; // A megabyte, because the writes are a few dozen bytes each and there are millions. WayOut::File(BufWriter::with_capacity(1 << 20, file)) } }; Ok(WaySink { out, record: Vec::new(), last_id: 0, count: 0, refs: 0, max_ref: 0, at: 0, blocks: Vec::new(), }) } /// Append one classified way. `id` must be greater than the previous call's. /// /// `name` is the display label for `places`/`poi` ways, `None` for every other layer. Written /// as a length-prefixed string per record — zero bytes for the nameless, which is nearly all /// of them. `lane_count`, `turn_fwd`, `turn_bwd` and `carriageway` are a road's lane count, /// per-lane turn masks and directional split, empty for every other layer and for a road with /// no lane tags; a handful of trailing varints per record, which the scratch file (removed /// after materialise) affords. #[allow(clippy::too_many_arguments)] #[cfg(test)] pub fn push( &mut self, id: i64, class: &Class, refs: &[i64], name: Option<&str>, lane_count: u8, turn_fwd: &[u16], turn_bwd: &[u16], carriageway: Carriageway, building: Option, ) -> Result<()> { if self.count > 0 && id <= self.last_id { return err(unsorted_ways(id, self.last_id)); } self.record.clear(); put_svarint(&mut self.record, id.wrapping_sub(self.last_id)); let max_ref = encode_way_tail( &mut self.record, class, refs, name, lane_count, turn_fwd, turn_bwd, carriageway, building, )?; self.max_ref = self.max_ref.max(max_ref); // Moved out rather than cloned: `out_write` takes `&mut self`, so `&self.record` // cannot borrow across the call, and a per-way clone is a memcpy per record over // millions of records. The buffer is restored below with its capacity intact, so the // `clear` at the top of the next `push` still reuses the allocation. let record = std::mem::take(&mut self.record); let result = self.out_write(&record).map_err(|e| { Error(format!("cannot write the ways spill: {e}")) }); let len = record.len() as u64; self.record = record; result?; self.note_block(len, 1); self.last_id = id; self.count += 1; self.refs += refs.len() as u64; Ok(()) } /// Append a run of ways a worker encoded ([`WayBlock`]). Writes exactly what `push` would /// have written for those ways one at a time: the block's first id varint is re-encoded /// against the last id this sink saw, the rest is copied verbatim. The ordering rule is /// enforced across the block boundary just as `push` enforces it between records. pub fn push_block(&mut self, block: &WayBlock) -> Result<()> { if block.count == 0 { return Ok(()); } if self.count > 0 && block.first_id <= self.last_id { return err(unsorted_ways(block.first_id, self.last_id)); } self.record.clear(); put_svarint(&mut self.record, block.first_id.wrapping_sub(self.last_id)); let head = std::mem::take(&mut self.record); let wrote = self .out_write(&head) .and_then(|()| self.out_write(&block.bytes[block.head_len..])); let len = (head.len() + block.bytes.len() - block.head_len) as u64; self.record = head; wrote?; self.note_block(len, block.count); self.last_id = block.last_id; self.count += block.count; self.refs += block.refs; self.max_ref = self.max_ref.max(block.max_ref); Ok(()) } /// Index `len` bytes / `ways` records just written at `self.at`, whose first delta is taken /// from `self.last_id` (still the pre-write value). Coalesced into the previous entry while /// that stays within [`WAY_BLOCK_WAYS`]: a run of consecutive records decodes from the first /// one's base however it was written, so merging entries changes nothing but the index size. fn note_block(&mut self, len: u64, ways: u64) { match self.blocks.last_mut() { Some(last) if last.offset + last.len == self.at && last.ways + ways <= WAY_BLOCK_WAYS => { last.len += len; last.ways += ways; } _ => self.blocks.push(WayBlockLoc { offset: self.at, len, start_last_id: self.last_id, ways, }), } self.at += len; } fn out_write(&mut self, bytes: &[u8]) -> Result<()> { match &mut self.out { WayOut::File(f) => f.write_all(bytes).map_err(|e| { Error(format!("cannot write the ways spill: {e}")) }), WayOut::Anon(a) => a.push(bytes).map(|_| ()).map_err(|e| { Error(format!("cannot stage the ways spill: {e}")) }), } } /// Flush, and report how many ways were written, how many node refs they hold between them, and /// the largest of those refs. /// /// None of the three is a statistic. [`crate::extract`] reads this file back to collect the node /// ids pass 3 must resolve, and it picks between two ways of doing that on the ref count: below a /// budget it sizes one exact vector (grown by extension a 200 M-id vector doubles into 2.1 GB of /// capacity, and the realloc that gets it there holds the old and new allocations at once), and /// above it sizes a bitset from `max_ref`. Both numbers are free here, where every ref is already /// being walked to encode it, and neither is recoverable later without a second pass. #[cfg(test)] pub fn finish(mut self) -> Result { match &mut self.out { WayOut::File(f) => f.flush().map_err(|e| Error(format!("cannot flush the ways spill: {e}")))?, WayOut::Anon(a) => a.finish(), } Ok(WayCounts { ways: self.count, refs: self.refs, max_ref: self.max_ref, blocks: std::mem::take(&mut self.blocks), }) } /// Anonymous twin of [`finish`](Self::finish): seals the pagefile-backed /// spill and hands back the counts plus the staged store. Errors on a /// file-backed sink. #[cfg(test)] pub fn finish_anon(mut self) -> Result<(WayCounts, tile_build::anon::AnonStore)> { match &mut self.out { WayOut::File(_) => { return err("finish_anon on a file-backed ways sink".to_string()) } WayOut::Anon(a) => a.finish(), } let counts = WayCounts { ways: self.count, refs: self.refs, max_ref: self.max_ref, blocks: std::mem::take(&mut self.blocks), }; match self.out { WayOut::Anon(a) => Ok((counts, a)), WayOut::File(_) => unreachable!("checked above"), } } /// Seal, and hand back the counts plus the staged bytes on the anon plan or `None` on the /// file plan (whose bytes live at the path the sink was created with). Unifies /// [`finish`](Self::finish) and [`finish_anon`](Self::finish_anon) so callers that pick the /// backend by budget seal without knowing which one they chose. pub fn finish_either(mut self) -> Result<(WayCounts, Option)> { match &mut self.out { WayOut::File(f) => f.flush().map_err(|e| Error(format!("cannot flush the ways spill: {e}")))?, WayOut::Anon(a) => a.finish(), } let counts = WayCounts { ways: self.count, refs: self.refs, max_ref: self.max_ref, blocks: std::mem::take(&mut self.blocks), }; match self.out { WayOut::Anon(a) => Ok((counts, Some(a))), WayOut::File(_) => Ok((counts, None)), } } } /// What a finished [`WaySink`] holds. pub struct WayCounts { pub ways: u64, /// Node refs summed over every way, duplicates included — a capacity, not a cardinality. pub refs: u64, /// The largest node ref written, or zero if none were. What a bitset over the id space is sized /// from. pub max_ref: i64, /// The block index over the stream, in stream order: what [`WayBlocks`] decodes from. pub blocks: Vec, } /// Reads back what a [`WaySink`] wrote, in the order it was written. /// /// File-backed ([`open`](Self::open)) or anonymous ([`open_anon`](Self::open_anon)): /// the record format is a sequential varint stream either way, so the reader is /// a cursor over bytes — a file cursor or a store offset. Same records, same order. pub struct WayReader { inner: WayIn, last_id: i64, seen: u64, } /// Where a [`WayReader`] reads from. enum WayIn { #[cfg(test)] File(BufReader), #[cfg(test)] Anon { store: std::sync::Arc, at: u64, buf: Vec, used: usize, }, /// One block of the stream, read whole ([`WayBlocks::reader`]). Slice { buf: Vec, used: usize }, }