/// Chunked reader over the normalized file, for reading it across a thread pool. /// /// The sequential [`NormalizedReader`] is one cursor, so the decode of every feature — /// which allocates a `Geometry` and a `Vec` of properties, six times over a z11..z16 /// build — happens on whichever single thread owns it, while the pool waits. This reads /// a whole chunk's byte range positionally instead, so the decode happens on the worker /// that will bucket those features. /// /// Takes `&self` throughout: see [`crate::pmtiles::read_exact_at`]. One handle serves /// every thread. /// /// Anonymous twin: [`open_anon`](Self::open_anon) serves the same chunks from an /// [`crate::anon::AnonStore`] instead of a file. Same offsets, same bytes. pub struct NormalizedChunks { file: Option, anon: Option>, path: PathBuf, /// Chunk boundaries, `chunk_count() + 1` of them. See [`NormalizedSummary::chunks`]. chunks: Vec, } impl NormalizedChunks { /// `chunks` is [`NormalizedSummary::chunks`] for this file. pub fn open(path: impl Into, chunks: Vec) -> Result { let path = path.into(); let file = File::open(&path) .map_err(|e| Error(format!("cannot read {}: {e}", path.display())))?; Ok(NormalizedChunks { file: Some(file), anon: None, path, chunks }) } /// Anonymous twin of [`open`](Self::open): `store` is the sealed store from /// [`NormalizedWriter::finish_anon`], shared by refcount — the store /// outlives every reader, so this is a refcount bump, never a copy. /// `path` names nothing — it only rides along for error messages. pub fn open_anon( path: impl Into, chunks: Vec, store: std::sync::Arc, ) -> Result { Ok(NormalizedChunks { file: None, anon: Some(store), path: path.into(), chunks, }) } pub fn chunk_count(&self) -> usize { self.chunks.len().saturating_sub(1) } /// Whether this reader serves from anonymous memory rather than a file. pub fn is_anon(&self) -> bool { self.anon.is_some() } /// Decode chunk `i` into `out`, which is cleared first. /// /// `scratch` is the caller's per-worker byte buffer, reused across chunks so a pass /// allocates once per thread rather than once per chunk. /// /// The first feature of chunk `i` is input feature `i * NORM_CHUNK_FEATURES`, by /// construction of the index — which is what lets the caller reproduce the exact /// `seq` the sequential path assigns. /// /// The chunk span covers one compressed frame: it is read whole, inflated, and decoded /// with the same [`decode_chunk_records`] the sequential reader uses, so the two paths /// cannot diverge on what they accept. /// [`read_into`](Self::read_into), keeping only the records whose properties pass `keep` -- /// and decoding the geometry of those alone. For whole-spill scans that want a sliver of it /// (the region fallback keeps boundary shapes and place labels out of ~1.35 B planet /// features): the properties sit after the geometry in each record and are a few bytes, the /// geometry is most of the decode. Kept records come back exactly as `read_into` yields them. pub fn read_into_where( &self, i: usize, scratch: &mut Vec, out: &mut Vec, keep: &KeepProps, ) -> Result<()> { out.clear(); let mut all = Vec::new(); // Inflate through `read_into`'s own path, then walk the raw records here. let (Some(&start), Some(&end)) = (self.chunks.get(i), self.chunks.get(i + 1)) else { return self.read_into(i, scratch, &mut all); }; if end < start { return self.read_into(i, scratch, &mut all); } scratch.clear(); scratch.resize((end - start) as usize, 0); match (&self.file, &self.anon) { (Some(f), None) => crate::pmtiles::read_exact_at(f, scratch, start).map_err(|e| { Error(format!("reading normalized chunk {i} of {}: {e}", self.path.display())) })?, (None, Some(a)) => a.read_at(start, scratch).map_err(|e| { Error(format!("reading normalized chunk {i} of {}: {e}", self.path.display())) })?, _ => return err("a normalized chunk reader has no backend".to_string()), } let raw = inflate_frame(i, &self.path, scratch)?; let mut at = 0usize; while at < raw.len() { if raw.len() - at < NORM_HEADER_BYTES { return err(format!( "normalized chunk {i} of {} ends inside a record header", self.path.display() )); } let head: &[u8; NORM_HEADER_BYTES] = raw[at..at + NORM_HEADER_BYTES].try_into().expect("a header's worth of bytes"); let (geom_len, props_len, kind) = norm_header(head)?; let body = at + NORM_HEADER_BYTES; let rec_end = body + geom_len + props_len; if rec_end > raw.len() { return err(format!( "normalized chunk {i} of {} holds a record running past its end", self.path.display() )); } let props = decode_props(&raw[body + geom_len..rec_end])?; if keep(&props) { out.push(NormalizedFeature { geometry: decode_geometry(kind, &raw[body..body + geom_len])?, props, }); } at = rec_end; } Ok(()) } pub fn read_into( &self, i: usize, scratch: &mut Vec, out: &mut Vec, ) -> Result<()> { out.clear(); let (Some(&start), Some(&end)) = (self.chunks.get(i), self.chunks.get(i + 1)) else { return err(format!( "normalized chunk {i} is past the {} in {}", self.chunk_count(), self.path.display() )); }; if end < start { return err(format!( "normalized chunk {i} of {} ends before it starts", self.path.display() )); } let len = (end - start) as usize; scratch.clear(); scratch.resize(len, 0); match (&self.file, &self.anon) { (Some(f), None) => { crate::pmtiles::read_exact_at(f, scratch, start).map_err(|e| { Error(format!( "reading normalized chunk {i} of {}: {e}", self.path.display() )) })?; } (None, Some(a)) => a.read_at(start, scratch).map_err(|e| { Error(format!( "reading normalized chunk {i} of {}: {e}", self.path.display() )) })?, _ => return err("a normalized chunk reader has no backend".to_string()), } let raw = inflate_frame(i, &self.path, scratch)?; decode_chunk_records(i, &self.path, &raw, out) } } /// The normalized file's lifetime, so a run that dies mid-planet cannot strand it. /// /// A guard rather than `impl Drop` on the reader, because the reader is handed around /// and the file has to outlive every one of them. pub struct NormalizedFile(PathBuf); impl NormalizedFile { pub fn new(path: impl Into) -> NormalizedFile { NormalizedFile(path.into()) } pub fn path(&self) -> &Path { &self.0 } } impl Drop for NormalizedFile { fn drop(&mut self) { let _ = std::fs::remove_file(&self.0); } }