/// One spill record -- header, pre-encoded geometry, properties -- written into `out` /// (cleared first). Pure, so the materialise drains build records on the pool and hand them to /// [`NormalizedWriter::push_record`] in order; `push_preencoded` is exactly this plus that. pub fn encode_normalized_record( kind: GeomKind, geom_bytes: &[u8], props: &[(String, Value)], out: &mut Vec, ) -> Result<()> { out.clear(); out.resize(NORM_HEADER_BYTES, 0); out.extend_from_slice(geom_bytes); let geom_len = count(geom_bytes.len())?; encode_props(props, out)?; let props_len = count(out.len() - NORM_HEADER_BYTES - geom_len as usize)?; let rec_len = count(out.len())?; out[0..4].copy_from_slice(&rec_len.to_le_bytes()); out[4..8].copy_from_slice(&geom_len.to_le_bytes()); out[8..12].copy_from_slice(&props_len.to_le_bytes()); out[12] = kind.tag(); Ok(()) } /// One normalized feature. #[derive(Debug, Clone, PartialEq)] pub struct NormalizedFeature { pub geometry: Geometry, pub props: Vec<(String, Value)>, } /// Validate a normalized record's fixed header, returning its payload shape. /// /// Shared by the sequential reader and the chunked one, so the two cannot diverge on /// what they accept: a record one of them rejects must not be one the other decodes. fn norm_header(head: &[u8; NORM_HEADER_BYTES]) -> Result<(usize, usize, GeomKind)> { if head[13..NORM_HEADER_BYTES].iter().any(|v| *v != 0) { return err("normalized record has a nonzero reserved tail"); } let u32_at = |o: usize| u32::from_le_bytes(head[o..o + 4].try_into().expect("4 bytes")); let rec_len = u32_at(0) as u64; let geom_len = u32_at(4) as usize; let props_len = u32_at(8) as usize; let want = NORM_HEADER_BYTES as u64 + geom_len as u64 + props_len as u64; if rec_len != want { return err(format!( "normalized record claims {rec_len} byte(s) but its header adds up to {want}" )); } if want > MAX_RECORD_BYTES { return err(format!( "normalized record is {want} byte(s), which is corruption" )); } Ok((geom_len, props_len, GeomKind::from_tag(head[12])?)) } /// Decode a validated record's payload, `geom_len` bytes of geometry then properties. fn norm_payload(kind: GeomKind, geom_len: usize, payload: &[u8]) -> Result { Ok(NormalizedFeature { geometry: decode_geometry(kind, &payload[..geom_len])?, props: decode_props(&payload[geom_len..])?, }) } /// Validate a spill file header, returning nothing: the magic, version and reserved tail are /// either exactly what the writer emits or the file is not a spill this reader knows. fn norm_file_header(head: &[u8; NORM_FILE_HEADER_BYTES]) -> Result<()> { if &head[0..4] != NORM_MAGIC { return err("not a normalized spill file (bad NZC1 magic)".to_string()); } if head[4] != NORM_VERSION { return err(format!( "unsupported normalized spill version {} (this reader speaks v{NORM_VERSION})", head[4], )); } if head[5..NORM_FILE_HEADER_BYTES].iter().any(|v| *v != 0) { return err("a normalized spill file has a nonzero reserved tail".to_string()); } Ok(()) } /// Inflate one frame: `u32 compressed_len` + raw DEFLATE of one chunk's records. /// /// The length is checked against the chunk span first (a frame longer than its span is /// corruption, not a large chunk), then the inflate itself is the check: DEFLATE framing errors /// on truncated or bit-rotted input rather than yielding partial records. Record validation /// (`norm_header` per record) still runs on the inflated bytes, so a corrupt frame that /// happens to inflate is refused as the desync it is. fn inflate_frame(chunk: usize, path: &std::path::Path, frame: &[u8]) -> Result> { if frame.len() < 4 { return err(format!( "normalized chunk {chunk} of {} ends {} byte(s) into its 4-byte frame header", path.display(), frame.len(), )); } let want = u32::from_le_bytes(frame[0..4].try_into().expect("4 bytes")) as u64; if want > MAX_FRAME_BYTES { return err(format!( "normalized chunk {chunk} of {} claims a {want}-byte frame, which is corruption", path.display(), )); } if want as usize != frame.len() - 4 { return err(format!( "normalized chunk {chunk} of {} holds {} frame byte(s) but claims {want}", path.display(), frame.len() - 4, )); } miniz_oxide::inflate::decompress_to_vec(&frame[4..]).map_err(|e| { Error(format!( "normalized chunk {chunk} of {} does not inflate: {e:?}", path.display(), )) }) } /// Decode every record in one inflated chunk into `out`, which is cleared first. /// /// Split from [`NormalizedChunks::read_into`] so the sequential reader shares the exact same /// validation: a record one of them rejects must not be one the other decodes. fn decode_chunk_records( chunk: usize, path: &std::path::Path, raw: &[u8], out: &mut Vec, ) -> Result<()> { out.clear(); let mut at = 0usize; while at < raw.len() { if raw.len() - at < NORM_HEADER_BYTES { return err(format!( "normalized chunk {chunk} of {} ends {} byte(s) into a \ {NORM_HEADER_BYTES}-byte record header", path.display(), raw.len() - at )); } 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 {chunk} of {} holds a record running {} byte(s) past its end", path.display(), rec_end - raw.len() )); } out.push(norm_payload(kind, geom_len, &raw[body..rec_end])?); at = rec_end; } Ok(()) } /// Sequential reader over the normalized spill, rewindable because every zoom /// re-reads it from the front. File-backed ([`open`](Self::open)) or anonymous /// ([`open_anon`](Self::open_anon)): the record format is a sequential stream /// either way, so the reader is a cursor over bytes — a file cursor or a store /// offset. pub struct NormalizedReader { src: ReaderIn, path: PathBuf, /// The current frame's inflated records. Refilled from the next frame when exhausted; the /// reader yields records across the refill boundary without the caller seeing frames at all. frame: Vec, /// Bytes of `frame` already yielded. frame_used: usize, /// Frames exhausted so far, for error messages that name the chunk. frames_seen: usize, /// Scratch for one compressed frame, reused so a refill allocates nothing but the inflate. raw_frame: Vec, } /// Where a [`NormalizedReader`] reads from. /// /// Both variants are frame-aware now: the file cursor sits at the next unread frame (past the /// 8-byte file header), and the anon offset likewise. `rewind` returns both to the first frame. enum ReaderIn { File(BufReader), Anon { store: std::sync::Arc, at: u64, }, } impl NormalizedReader { pub fn open(path: impl Into) -> Result { let path = path.into(); let f = File::open(&path) .map_err(|e| Error(format!("cannot read {}: {e}", path.display())))?; let mut reader = NormalizedReader { src: ReaderIn::File(BufReader::with_capacity(1 << 20, f)), path, frame: Vec::new(), frame_used: 0, frames_seen: 0, raw_frame: Vec::new(), }; reader.read_file_header()?; Ok(reader) } /// Anonymous twin of [`open`](Self::open): reads the sealed store from /// [`NormalizedWriter::finish_anon`], shared by refcount. pub fn open_anon( path: impl Into, store: std::sync::Arc, ) -> Result { let mut reader = NormalizedReader { src: ReaderIn::Anon { store, at: NORM_FILE_HEADER_BYTES as u64 }, path: path.into(), frame: Vec::new(), frame_used: 0, frames_seen: 0, raw_frame: Vec::new(), }; reader.read_file_header()?; Ok(reader) } /// Parse and validate the 8-byte file header, positioning the cursor at the first frame. /// /// Read through the cursor itself (not a separate open) so the file and anon paths share /// the framing: on the file path this consumes the header bytes; on anon it validates the /// store's own first 8 bytes while `at` already skips past them. fn read_file_header(&mut self) -> Result<()> { match &mut self.src { ReaderIn::File(f) => { let mut head = [0u8; NORM_FILE_HEADER_BYTES]; use std::io::Read; f.read_exact(&mut head).map_err(|e| { Error(format!("reading {}'s spill header: {e}", self.path.display())) })?; norm_file_header(&head)?; } ReaderIn::Anon { store, .. } => { let mut head = [0u8; NORM_FILE_HEADER_BYTES]; store.read_at(0, &mut head).map_err(|e| { Error(format!("reading {}'s spill header: {e}", self.path.display())) })?; norm_file_header(&head)?; } } Ok(()) } pub fn rewind(&mut self) -> Result<()> { match &mut self.src { ReaderIn::File(f) => { use std::io::Seek; // Past the file header: frame 0 starts at byte 8, not byte 0. f.seek(std::io::SeekFrom::Start(NORM_FILE_HEADER_BYTES as u64)) .map_err(|e| Error(format!("rewinding {}: {e}", self.path.display())))?; } ReaderIn::Anon { at, .. } => *at = NORM_FILE_HEADER_BYTES as u64, } self.frame.clear(); self.frame_used = 0; self.frames_seen = 0; Ok(()) } /// Fill `buf` with exactly `len` bytes from the cursor, or `Ok(false)` at a /// clean frame boundary (start of read, or exactly past the last frame's bytes). /// /// A short read anywhere else is corruption, and the callers treat it as such: frames state /// their own length, so a file that ends mid-frame is truncated, not finished. fn read_full(&mut self, buf: &mut [u8]) -> Result { match &mut self.src { ReaderIn::File(f) => { let mut read = 0usize; while read < buf.len() { let n = f .read(&mut buf[read..]) .map_err(|e| Error(format!("reading {}: {e}", self.path.display())))?; if n == 0 { break; } read += n; } // `Ok(false)` only at a frame boundary: mid-frame EOF is reported by the frame // length check in `refill`, not here. Ok(read > 0) } ReaderIn::Anon { store, at } => { if *at >= store.len() { return Ok(false); } let remaining = store.len() - *at; let take = (buf.len() as u64).min(remaining) as usize; store.read_at(*at, &mut buf[..take]).map_err(|e| { Error(format!("reading {}: {e}", self.path.display())) })?; *at += take as u64; Ok(true) } } } /// The next frame's inflated records, replacing `frame`. /// /// Reads the frame's `u32` length, then exactly that many bytes -- a short read there is a /// truncated file, never a legitimate end -- inflates, and validates the inflate before any /// record is yielded. `Ok(false)` only when the cursor sits exactly at end of input. fn refill(&mut self) -> Result { let mut len_buf = [0u8; 4]; if !self.read_full(&mut len_buf)? { return Ok(false); } let want = u32::from_le_bytes(len_buf) as usize; if want as u64 > MAX_FRAME_BYTES { return err(format!( "normalized frame {} of {} claims {} byte(s), which is corruption", self.frames_seen, self.path.display(), want, )); } self.raw_frame.clear(); self.raw_frame.resize(want, 0); // Exact-length by construction (the length was just read), so a short payload is // corruption, not EOF. `read_full` may return short mid-frame on the file path; // loop until the frame is whole or the file ends. let mut read = 0usize; while read < want { let mut chunk = vec![0u8; want - read]; if !self.read_full(&mut chunk)? { return err(format!( "{} ends {} byte(s) into frame {}", self.path.display(), read, self.frames_seen, )); } // `read_full` on the file path may return short; on anon it fills exactly. let n = chunk.len(); self.raw_frame[read..read + n].copy_from_slice(&chunk); read += n; if n == 0 { break; } } let mut framed = Vec::with_capacity(4 + want); framed.extend_from_slice(&len_buf); framed.extend_from_slice(&self.raw_frame); self.frame = inflate_frame(self.frames_seen, &self.path, &framed)?; self.frame_used = 0; self.frames_seen += 1; Ok(true) } #[allow(clippy::should_implement_trait)] pub fn next(&mut self) -> Result> { loop { if self.frame_used < self.frame.len() { let head: &[u8; NORM_HEADER_BYTES] = self.frame [self.frame_used..self.frame_used + NORM_HEADER_BYTES] .try_into() .map_err(|_| { Error(format!( "{} ends {} byte(s) into a {NORM_HEADER_BYTES}-byte record header", self.path.display(), self.frame.len() - self.frame_used, )) })?; let (geom_len, props_len, kind) = norm_header(head)?; let body = self.frame_used + NORM_HEADER_BYTES; let rec_end = body + geom_len + props_len; if rec_end > self.frame.len() { return err(format!( "{} holds a record running {} byte(s) past its frame", self.path.display(), rec_end - self.frame.len(), )); } let feature = norm_payload(kind, geom_len, &self.frame[body..rec_end])?; self.frame_used = rec_end; return Ok(Some(feature)); } if !self.refill()? { return Ok(None); } } } }