Modern Apps git

← Modern-Apps.git

tilecodec: split oversized Rust files under the 500-line limit

Commit
03049f7a65ca1692ddac2e7660694e70a4bf8681
Author
Vayun Mathur <[email protected]>
When
2026-12-01 20:28 UTC (4 days ago)
Parents
4a09515
blocked.rs (828), mamaps/body/codec.rs (688), tests_extra.rs
(650), body/tables.rs (628), write/writer.rs (601), tests.rs
(575), body/tables_extra.rs (562), write/spill.rs and body/tests.rs
(553), body/tests_extra.rs (548) and read/archive.rs (537)
exceeded the 500-line rustFileLength limit.

Split each along module lines using the established include!
part pattern: whole top-level items move verbatim into *_sN.rs
files spliced into the same module, so every item, visibility
and call path is identical and no public surface changes.

Verified: cargo fmt -p tilecodec -- --check clean and
cargo test -p tilecodec --locked green (202 passed in the
library suite plus integration suites).

Diff

library/tilecodec/src/main/rust/src/blocked.rs
diff --git a/library/tilecodec/src/main/rust/src/blocked.rs b/library/tilecodec/src/main/rust/src/blocked.rsindex 0d2f376f45..e2cb8fa156 100644--- a/library/tilecodec/src/main/rust/src/blocked.rs+++ b/library/tilecodec/src/main/rust/src/blocked.rs@@ -428,401 +428,4 @@ pub fn compress_block(block: &[u8]) -> Vec<u8> {     }) } -/// [`compress_block`] of the block's column transform ([`columns_forward`]).-#[cfg(feature = "write")]-pub fn compress_block_columns(block: &[u8], record_len: usize) -> Vec<u8> {-    compress_block(&columns_forward(block, record_len))-}--/// Lay out header + offset table + frames. Shared by the whole-slice and-/// streaming writers so the two cannot drift.-#[cfg(feature = "write")]-fn assemble_blocked(-    record_len: usize,-    per_block: u32,-    unpacked_len: usize,-    frames: &[Vec<u8>],-) -> Vec<u8> {-    let block_count = frames.len();-    let mut out = Vec::new();-    out.extend_from_slice(&BLOCKED_MAGIC.to_le_bytes());-    out.extend_from_slice(&0u32.to_le_bytes());-    out.extend_from_slice(&(record_len as u32).to_le_bytes());-    out.extend_from_slice(&per_block.to_le_bytes());-    out.extend_from_slice(&(unpacked_len as u64).to_le_bytes());-    out.extend_from_slice(&(block_count as u32).to_le_bytes());-    let mut off = (28 + (block_count + 1) * 8) as u64;-    for f in frames {-        out.extend_from_slice(&off.to_le_bytes());-        off += f.len() as u64;-    }-    out.extend_from_slice(&off.to_le_bytes());-    for f in frames {-        out.extend_from_slice(f);-    }-    out-}--/// Streaming blocked writer: records in, frames to scratch, table in memory.-///-/// Whole-slice [`write_blocked`] holds every record at once (5 GB for planet-/// `nodes.bin`); the graph writers stream, so this matches them: one block-/// (4096 records) in memory, frames spilled to a scratch file beside the-/// output, the 8-bytes-per-block offset table in memory (524 KB for 268 M-/// planet bodies). [`BlockedStreamWriter::finish`] returns the assembled-/// section; the caller writes it to the final path.-#[cfg(feature = "write")]-pub struct BlockedStreamWriter {-    record_len: usize,-    flags: u32,-    per_block: u32,-    block: Vec<u8>,-    frames_path: std::path::PathBuf,-    frames_out: std::fs::File,-    frame_lens: Vec<u64>,-    records: u64,-}--#[cfg(feature = "write")]-impl BlockedStreamWriter {-    /// Stage frames in `scratch_path` (removed by [`BlockedStreamWriter::finish`]).-    pub fn create(-        record_len: usize,-        scratch_path: &std::path::Path,-    ) -> std::io::Result<BlockedStreamWriter> {-        Ok(BlockedStreamWriter {-            record_len,-            flags: 0,-            per_block: BLOCK_RECORDS,-            block: Vec::with_capacity(record_len * BLOCK_RECORDS as usize),-            frames_path: scratch_path.to_path_buf(),-            frames_out: std::fs::File::create(scratch_path)?,-            frame_lens: Vec::new(),-            records: 0,-        })-    }--    /// Column-transform every block ([`BLOCKED_FLAG_COLUMNS`]). Set before the first record;-    /// frames handed to [`BlockedStreamWriter::push_frames`] must then come from-    /// [`compress_block_columns`].-    pub fn with_columns(mut self) -> BlockedStreamWriter {-        assert_eq!(self.records, 0, "with_columns before any record");-        self.flags = BLOCKED_FLAG_COLUMNS;-        self-    }--    /// True when blocks are column-transformed.-    pub fn columns(&self) -> bool {-        self.flags & BLOCKED_FLAG_COLUMNS != 0-    }--    fn frame(&self, block: &[u8]) -> Vec<u8> {-        if self.flags & BLOCKED_FLAG_COLUMNS != 0 {-            compress_block_columns(block, self.record_len)-        } else {-            compress_block(block)-        }-    }--    /// Append whole records. Must be a multiple of the stride.-    pub fn push(&mut self, records: &[u8]) -> std::io::Result<()> {-        assert_eq!(records.len() % self.record_len, 0, "whole records only");-        self.block.extend_from_slice(records);-        self.records += (records.len() / self.record_len) as u64;-        while self.block.len() >= self.per_block as usize * self.record_len {-            self.flush_block()?;-        }-        Ok(())-    }--    fn flush_block(&mut self) -> std::io::Result<()> {-        use std::io::Write as _;-        let n = self.per_block as usize * self.record_len;-        let frame = self.frame(&self.block[..n]);-        self.frames_out.write_all(&frame)?;-        self.frame_lens.push(frame.len() as u64);-        self.block.drain(..n);-        Ok(())-    }--    /// Bytes in one full block (`records_per_block * record_len`): the unit-    /// [`compress_block`] frames for [`BlockedStreamWriter::push_frames`].-    pub fn block_bytes(&self) -> usize {-        self.per_block as usize * self.record_len-    }--    /// Append whole blocks the caller already compressed with-    /// [`compress_block`] — the parallel form of [`BlockedStreamWriter::push`].-    ///-    /// Byte-identical to pushing the same records: every frame is an-    /// independent zstd frame of exactly one block, compressed by a fresh-    /// encoder at the same level, so a frame is a pure function of its block-    /// whoever compresses it. Only valid on a block boundary (nothing staged-    /// by `push`), and every frame must hold a full block. The frames go out in-    /// one write, so the scratch file sees large sequential appends.-    pub fn push_frames(&mut self, frames: &[Vec<u8>]) -> std::io::Result<()> {-        use std::io::Write as _;-        assert!(self.block.is_empty(), "push_frames needs a block boundary");-        let total: usize = frames.iter().map(Vec::len).sum();-        let mut joined = Vec::with_capacity(total);-        for f in frames {-            joined.extend_from_slice(f);-            self.frame_lens.push(f.len() as u64);-        }-        self.frames_out.write_all(&joined)?;-        self.records += frames.len() as u64 * u64::from(self.per_block);-        Ok(())-    }--    /// [`BlockedStreamWriter::finish`], streamed: compress the tail block, then-    /// write header + offset table into `out` and copy the frames straight from-    /// the scratch file behind them, never holding the section in memory.-    /// Byte-identical to writing `finish()`'s bytes. Returns the section length.-    pub fn finish_into<W: std::io::Write>(mut self, out: &mut W) -> std::io::Result<u64> {-        use std::io::Write as _;-        if !self.block.is_empty() {-            let frame = self.frame(&self.block);-            self.frames_out.write_all(&frame)?;-            self.frame_lens.push(frame.len() as u64);-        }-        self.frames_out.flush()?;-        drop(self.frames_out);-        let block_count = self.frame_lens.len();-        let unpacked = self.records * self.record_len as u64;-        let mut head = Vec::with_capacity(28 + (block_count + 1) * 8);-        head.extend_from_slice(&BLOCKED_MAGIC.to_le_bytes());-        head.extend_from_slice(&self.flags.to_le_bytes());-        head.extend_from_slice(&(self.record_len as u32).to_le_bytes());-        head.extend_from_slice(&self.per_block.to_le_bytes());-        head.extend_from_slice(&unpacked.to_le_bytes());-        head.extend_from_slice(&(block_count as u32).to_le_bytes());-        let mut off = (28 + (block_count + 1) * 8) as u64;-        for len in &self.frame_lens {-            head.extend_from_slice(&off.to_le_bytes());-            off += len;-        }-        head.extend_from_slice(&off.to_le_bytes());-        out.write_all(&head)?;-        let frames_bytes: u64 = self.frame_lens.iter().sum();-        let mut f = std::fs::File::open(&self.frames_path)?;-        let copied = std::io::copy(&mut f, out)?;-        drop(f);-        let _ = std::fs::remove_file(&self.frames_path);-        if copied != frames_bytes {-            return Err(std::io::Error::new(-                std::io::ErrorKind::UnexpectedEof,-                format!("blocked scratch holds {copied} frame byte(s), expected {frames_bytes}"),-            ));-        }-        Ok(off)-    }--    /// Compress the tail block, assemble header + table + frames, remove the-    /// scratch file, and return the section bytes.-    pub fn finish(mut self) -> std::io::Result<Vec<u8>> {-        use std::io::Write as _;-        if !self.block.is_empty() {-            // Tail block: fewer than per_block records. Same framing; the-            // reader derives record counts from unpacked_len, never from drum-tight blocks.-            let frame = self.frame(&self.block);-            self.frames_out.write_all(&frame)?;-            self.frame_lens.push(frame.len() as u64);-        }-        drop(self.frames_out);-        let mut frames = Vec::with_capacity(self.frame_lens.len());-        let mut f = std::fs::File::open(&self.frames_path)?;-        use std::io::Read as _;-        for &len in &self.frame_lens {-            let mut frame = vec![0u8; len as usize];-            f.read_exact(&mut frame)?;-            frames.push(frame);-        }-        drop(f);-        let _ = std::fs::remove_file(&self.frames_path);-        let unpacked = self.records * self.record_len as u64;-        let mut out = assemble_blocked(self.record_len, self.per_block, unpacked as usize, &frames);-        out[4..8].copy_from_slice(&self.flags.to_le_bytes());-        Ok(out)-    }-}--#[cfg(test)]-mod tests {-    use super::*;--    #[test]-    fn the_column_transform_round_trips_every_stride() {-        for w in [2usize, 3, 7, 8, 12, 16, 20] {-            for n in [0usize, 1, 5, 4096] {-                let rows: Vec<u8> =-                    (0..n * w).map(|i| (i * 7919 % 251) as u8 ^ (i >> 5) as u8).collect();-                assert_eq!(columns_inverse(&columns_forward(&rows, w), w), rows, "w {w} n {n}");-            }-        }-    }--    #[cfg(feature = "write")]-    #[test]-    fn a_columns_section_reads_back_through_block_and_untransform() {-        let recs = pattern_records(10_000, 12);-        let sec = write_blocked_columns(&recs, 12);-        let v = Blocked::parse(&sec).expect("parse");-        assert_eq!(v.flags(), BLOCKED_FLAG_COLUMNS);-        let mut back = Vec::new();-        for b in 0..v.block_count() {-            back.extend_from_slice(&v.block(b).expect("block"));-        }-        assert_eq!(back, recs);-        // A stream writer with columns produces the same bytes.-        let dir = std::env::temp_dir().join(format!("zblkcols{}", std::process::id()));-        let mut w = BlockedStreamWriter::create(12, &dir).expect("scratch").with_columns();-        w.push(&recs).expect("push");-        assert_eq!(w.finish().expect("finish"), sec);-        // ...and it is smaller than the row layout on curve-ordered coordinates.-        assert!(sec.len() < write_blocked(&recs, 12).len());-    }--    fn pattern_records(n: usize, len: usize) -> Vec<u8> {-        // Coordinate-like: small ints LE plus a slow counter, like NodeRecs.-        // `len` bytes per record: the 12-byte pattern truncated (7-byte edge records)-        // or zero-padded, so any stride gets whole records.-        let mut out = Vec::with_capacity(n * len);-        for i in 0..n {-            let mut rec = Vec::with_capacity(12.max(len));-            rec.extend_from_slice(&(350_000_000 + i as i32 * 37).to_le_bytes());-            rec.extend_from_slice(&(-1_200_000_000 + i as i32 * 11).to_le_bytes());-            rec.extend_from_slice(&(i as u32 * 3).to_le_bytes());-            rec.resize(len, 0);-            out.extend_from_slice(&rec);-        }-        assert_eq!(out.len(), n * len);-        out-    }--    #[test]-    fn a_blocked_section_round_trips() {-        let records = pattern_records(10_000, 12);-        let bytes = write_blocked(&records, 12);-        let s = Blocked::parse(&bytes).expect("parse");-        assert_eq!(s.unpacked_len(), records.len() as u64);-        assert_eq!(s.block_count(), 3, "10000 / 4096 rounds up");-        let mut cache = BlockCache::new(4);-        let mut back = Vec::with_capacity(records.len());-        for id in 0..10_000u64 {-            back.extend_from_slice(&s.record(id, &mut cache).expect("record"));-        }-        assert_eq!(back, records);-    }--    #[test]-    fn a_blocked_section_refuses_garbage() {-        let records = pattern_records(100, 12);-        let mut bytes = write_blocked(&records, 12);-        assert!(Blocked::parse(&bytes).is_ok());-        bytes[0] = b'X';-        assert!(Blocked::parse(&bytes).is_err(), "bad magic");-        let mut bytes = write_blocked(&records, 12);-        bytes[4] = 2;-        assert!(Blocked::parse(&bytes).is_err(), "unknown flags");-        assert!(Blocked::parse(&bytes[..10]).is_err(), "truncated");-    }--    #[test]-    fn last_block_holds_the_remainder() {-        let records = pattern_records(4097, 7);-        let bytes = write_blocked(&records, 7);-        let s = Blocked::parse(&bytes).expect("parse");-        assert_eq!(s.block_count(), 2);-        let mut cache = BlockCache::new(0);-        // First record of the last block and the very last record.-        assert_eq!(s.record(4096, &mut cache).expect("first of last"), records[4096 * 7..4097 * 7]);-        assert_eq!(s.record(4096, &mut cache).expect("cached"), records[4096 * 7..4097 * 7]);-    }--    #[test]-    fn the_streaming_writer_matches_the_whole_slice_writer() {-        let records = pattern_records(10_000, 12);-        let dir = std::env::temp_dir();-        let scratch = dir.join("tilecodec_blocked_stream_test.tmp");-        let _ = std::fs::remove_file(&scratch);-        let mut w = BlockedStreamWriter::create(12, &scratch).expect("create");-        // Odd-sized pushes (417 whole records each — `push` takes whole records only),-        // including across block boundaries.-        for chunk in records.chunks(417 * 12) {-            w.push(chunk).expect("push");-        }-        let streamed = w.finish().expect("finish");-        assert!(!scratch.exists(), "scratch is removed");-        let whole = write_blocked(&records, 12);-        assert_eq!(streamed, whole, "streaming must be byte-identical to whole-slice");-        // And the streamed bytes read back.-        let s = Blocked::parse(&streamed).expect("parse");-        assert_eq!(s.block_count(), 3);-        let mut cache = BlockCache::new(4);-        assert_eq!(s.record(9999, &mut cache).expect("last"), records[9999 * 12..10_000 * 12]);-    }--    #[test]-    fn pushing_precompressed_frames_matches_pushing_records() {-        let records = pattern_records(10_000, 12);-        let dir = std::env::temp_dir();-        let a = dir.join("tilecodec_blocked_frames_a.tmp");-        let b = dir.join("tilecodec_blocked_frames_b.tmp");-        let mut plain = BlockedStreamWriter::create(12, &a).expect("create");-        plain.push(&records).expect("push");-        let plain = plain.finish().expect("finish");-        let mut framed = BlockedStreamWriter::create(12, &b).expect("create");-        let bb = framed.block_bytes();-        let full = records.len() / bb * bb;-        let frames: Vec<Vec<u8>> = records[..full].chunks(bb).map(compress_block).collect();-        framed.push_frames(&frames).expect("frames");-        framed.push(&records[full..]).expect("tail");-        let framed = framed.finish().expect("finish");-        assert_eq!(framed, plain, "frames compressed elsewhere must be byte-identical");-    }--    #[test]-    fn a_reused_context_frames_blocks_like_a_fresh_one() {-        // Blocks of varied size and content, large before small and back, so-        // any table state leaking from one frame into the next would show.-        let mut blocks: Vec<Vec<u8>> = Vec::new();-        for (n, seed) in [(4096usize, 1u32), (17, 2), (4096, 3), (1, 4), (2500, 5), (4096, 1)] {-            let mut b = pattern_records(n, 12);-            for (i, byte) in b.iter_mut().enumerate() {-                *byte ^= (seed.wrapping_mul(2654435761).rotate_left(i as u32 % 31)) as u8 & 3;-            }-            blocks.push(b);-        }-        let fresh = |b: &[u8]| {-            let mut enc = zstd_rs::Compressor::new(zstd_rs::CompressionConfig {-                level: BLOCK_LEVEL,-                ..zstd_rs::CompressionConfig::DEFAULT-            })-            .unwrap();-            let mut f = Vec::new();-            enc.compress(b, None, &mut f).unwrap();-            f-        };-        for b in &blocks {-            assert_eq!(compress_block(b), fresh(b), "reused context diverged");-        }-    }--    #[test]-    fn finishing_into_a_writer_matches_finish() {-        let records = pattern_records(10_000, 12);-        let dir = std::env::temp_dir();-        let a = dir.join("tilecodec_blocked_into_a.tmp");-        let b = dir.join("tilecodec_blocked_into_b.tmp");-        let mut w1 = BlockedStreamWriter::create(12, &a).expect("create");-        w1.push(&records).expect("push");-        let whole = w1.finish().expect("finish");-        let mut w2 = BlockedStreamWriter::create(12, &b).expect("create");-        w2.push(&records).expect("push");-        let mut streamed = Vec::new();-        let n = w2.finish_into(&mut streamed).expect("finish_into");-        assert_eq!(n as usize, streamed.len());-        assert_eq!(streamed, whole);-        assert!(!b.exists(), "scratch is removed");-    }-}+include!("blocked_s1.rs");
library/tilecodec/src/main/rust/src/blocked_s1.rs
diff --git a/library/tilecodec/src/main/rust/src/blocked_s1.rs b/library/tilecodec/src/main/rust/src/blocked_s1.rsnew file mode 100644index 0000000000..75882606eb--- /dev/null+++ b/library/tilecodec/src/main/rust/src/blocked_s1.rs@@ -0,0 +1,398 @@+/// [`compress_block`] of the block's column transform ([`columns_forward`]).+#[cfg(feature = "write")]+pub fn compress_block_columns(block: &[u8], record_len: usize) -> Vec<u8> {+    compress_block(&columns_forward(block, record_len))+}++/// Lay out header + offset table + frames. Shared by the whole-slice and+/// streaming writers so the two cannot drift.+#[cfg(feature = "write")]+fn assemble_blocked(+    record_len: usize,+    per_block: u32,+    unpacked_len: usize,+    frames: &[Vec<u8>],+) -> Vec<u8> {+    let block_count = frames.len();+    let mut out = Vec::new();+    out.extend_from_slice(&BLOCKED_MAGIC.to_le_bytes());+    out.extend_from_slice(&0u32.to_le_bytes());+    out.extend_from_slice(&(record_len as u32).to_le_bytes());+    out.extend_from_slice(&per_block.to_le_bytes());+    out.extend_from_slice(&(unpacked_len as u64).to_le_bytes());+    out.extend_from_slice(&(block_count as u32).to_le_bytes());+    let mut off = (28 + (block_count + 1) * 8) as u64;+    for f in frames {+        out.extend_from_slice(&off.to_le_bytes());+        off += f.len() as u64;+    }+    out.extend_from_slice(&off.to_le_bytes());+    for f in frames {+        out.extend_from_slice(f);+    }+    out+}++/// Streaming blocked writer: records in, frames to scratch, table in memory.+///+/// Whole-slice [`write_blocked`] holds every record at once (5 GB for planet+/// `nodes.bin`); the graph writers stream, so this matches them: one block+/// (4096 records) in memory, frames spilled to a scratch file beside the+/// output, the 8-bytes-per-block offset table in memory (524 KB for 268 M+/// planet bodies). [`BlockedStreamWriter::finish`] returns the assembled+/// section; the caller writes it to the final path.+#[cfg(feature = "write")]+pub struct BlockedStreamWriter {+    record_len: usize,+    flags: u32,+    per_block: u32,+    block: Vec<u8>,+    frames_path: std::path::PathBuf,+    frames_out: std::fs::File,+    frame_lens: Vec<u64>,+    records: u64,+}++#[cfg(feature = "write")]+impl BlockedStreamWriter {+    /// Stage frames in `scratch_path` (removed by [`BlockedStreamWriter::finish`]).+    pub fn create(+        record_len: usize,+        scratch_path: &std::path::Path,+    ) -> std::io::Result<BlockedStreamWriter> {+        Ok(BlockedStreamWriter {+            record_len,+            flags: 0,+            per_block: BLOCK_RECORDS,+            block: Vec::with_capacity(record_len * BLOCK_RECORDS as usize),+            frames_path: scratch_path.to_path_buf(),+            frames_out: std::fs::File::create(scratch_path)?,+            frame_lens: Vec::new(),+            records: 0,+        })+    }++    /// Column-transform every block ([`BLOCKED_FLAG_COLUMNS`]). Set before the first record;+    /// frames handed to [`BlockedStreamWriter::push_frames`] must then come from+    /// [`compress_block_columns`].+    pub fn with_columns(mut self) -> BlockedStreamWriter {+        assert_eq!(self.records, 0, "with_columns before any record");+        self.flags = BLOCKED_FLAG_COLUMNS;+        self+    }++    /// True when blocks are column-transformed.+    pub fn columns(&self) -> bool {+        self.flags & BLOCKED_FLAG_COLUMNS != 0+    }++    fn frame(&self, block: &[u8]) -> Vec<u8> {+        if self.flags & BLOCKED_FLAG_COLUMNS != 0 {+            compress_block_columns(block, self.record_len)+        } else {+            compress_block(block)+        }+    }++    /// Append whole records. Must be a multiple of the stride.+    pub fn push(&mut self, records: &[u8]) -> std::io::Result<()> {+        assert_eq!(records.len() % self.record_len, 0, "whole records only");+        self.block.extend_from_slice(records);+        self.records += (records.len() / self.record_len) as u64;+        while self.block.len() >= self.per_block as usize * self.record_len {+            self.flush_block()?;+        }+        Ok(())+    }++    fn flush_block(&mut self) -> std::io::Result<()> {+        use std::io::Write as _;+        let n = self.per_block as usize * self.record_len;+        let frame = self.frame(&self.block[..n]);+        self.frames_out.write_all(&frame)?;+        self.frame_lens.push(frame.len() as u64);+        self.block.drain(..n);+        Ok(())+    }++    /// Bytes in one full block (`records_per_block * record_len`): the unit+    /// [`compress_block`] frames for [`BlockedStreamWriter::push_frames`].+    pub fn block_bytes(&self) -> usize {+        self.per_block as usize * self.record_len+    }++    /// Append whole blocks the caller already compressed with+    /// [`compress_block`] — the parallel form of [`BlockedStreamWriter::push`].+    ///+    /// Byte-identical to pushing the same records: every frame is an+    /// independent zstd frame of exactly one block, compressed by a fresh+    /// encoder at the same level, so a frame is a pure function of its block+    /// whoever compresses it. Only valid on a block boundary (nothing staged+    /// by `push`), and every frame must hold a full block. The frames go out in+    /// one write, so the scratch file sees large sequential appends.+    pub fn push_frames(&mut self, frames: &[Vec<u8>]) -> std::io::Result<()> {+        use std::io::Write as _;+        assert!(self.block.is_empty(), "push_frames needs a block boundary");+        let total: usize = frames.iter().map(Vec::len).sum();+        let mut joined = Vec::with_capacity(total);+        for f in frames {+            joined.extend_from_slice(f);+            self.frame_lens.push(f.len() as u64);+        }+        self.frames_out.write_all(&joined)?;+        self.records += frames.len() as u64 * u64::from(self.per_block);+        Ok(())+    }++    /// [`BlockedStreamWriter::finish`], streamed: compress the tail block, then+    /// write header + offset table into `out` and copy the frames straight from+    /// the scratch file behind them, never holding the section in memory.+    /// Byte-identical to writing `finish()`'s bytes. Returns the section length.+    pub fn finish_into<W: std::io::Write>(mut self, out: &mut W) -> std::io::Result<u64> {+        use std::io::Write as _;+        if !self.block.is_empty() {+            let frame = self.frame(&self.block);+            self.frames_out.write_all(&frame)?;+            self.frame_lens.push(frame.len() as u64);+        }+        self.frames_out.flush()?;+        drop(self.frames_out);+        let block_count = self.frame_lens.len();+        let unpacked = self.records * self.record_len as u64;+        let mut head = Vec::with_capacity(28 + (block_count + 1) * 8);+        head.extend_from_slice(&BLOCKED_MAGIC.to_le_bytes());+        head.extend_from_slice(&self.flags.to_le_bytes());+        head.extend_from_slice(&(self.record_len as u32).to_le_bytes());+        head.extend_from_slice(&self.per_block.to_le_bytes());+        head.extend_from_slice(&unpacked.to_le_bytes());+        head.extend_from_slice(&(block_count as u32).to_le_bytes());+        let mut off = (28 + (block_count + 1) * 8) as u64;+        for len in &self.frame_lens {+            head.extend_from_slice(&off.to_le_bytes());+            off += len;+        }+        head.extend_from_slice(&off.to_le_bytes());+        out.write_all(&head)?;+        let frames_bytes: u64 = self.frame_lens.iter().sum();+        let mut f = std::fs::File::open(&self.frames_path)?;+        let copied = std::io::copy(&mut f, out)?;+        drop(f);+        let _ = std::fs::remove_file(&self.frames_path);+        if copied != frames_bytes {+            return Err(std::io::Error::new(+                std::io::ErrorKind::UnexpectedEof,+                format!("blocked scratch holds {copied} frame byte(s), expected {frames_bytes}"),+            ));+        }+        Ok(off)+    }++    /// Compress the tail block, assemble header + table + frames, remove the+    /// scratch file, and return the section bytes.+    pub fn finish(mut self) -> std::io::Result<Vec<u8>> {+        use std::io::Write as _;+        if !self.block.is_empty() {+            // Tail block: fewer than per_block records. Same framing; the+            // reader derives record counts from unpacked_len, never from drum-tight blocks.+            let frame = self.frame(&self.block);+            self.frames_out.write_all(&frame)?;+            self.frame_lens.push(frame.len() as u64);+        }+        drop(self.frames_out);+        let mut frames = Vec::with_capacity(self.frame_lens.len());+        let mut f = std::fs::File::open(&self.frames_path)?;+        use std::io::Read as _;+        for &len in &self.frame_lens {+            let mut frame = vec![0u8; len as usize];+            f.read_exact(&mut frame)?;+            frames.push(frame);+        }+        drop(f);+        let _ = std::fs::remove_file(&self.frames_path);+        let unpacked = self.records * self.record_len as u64;+        let mut out = assemble_blocked(self.record_len, self.per_block, unpacked as usize, &frames);+        out[4..8].copy_from_slice(&self.flags.to_le_bytes());+        Ok(out)+    }+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn the_column_transform_round_trips_every_stride() {+        for w in [2usize, 3, 7, 8, 12, 16, 20] {+            for n in [0usize, 1, 5, 4096] {+                let rows: Vec<u8> =+                    (0..n * w).map(|i| (i * 7919 % 251) as u8 ^ (i >> 5) as u8).collect();+                assert_eq!(columns_inverse(&columns_forward(&rows, w), w), rows, "w {w} n {n}");+            }+        }+    }++    #[cfg(feature = "write")]+    #[test]+    fn a_columns_section_reads_back_through_block_and_untransform() {+        let recs = pattern_records(10_000, 12);+        let sec = write_blocked_columns(&recs, 12);+        let v = Blocked::parse(&sec).expect("parse");+        assert_eq!(v.flags(), BLOCKED_FLAG_COLUMNS);+        let mut back = Vec::new();+        for b in 0..v.block_count() {+            back.extend_from_slice(&v.block(b).expect("block"));+        }+        assert_eq!(back, recs);+        // A stream writer with columns produces the same bytes.+        let dir = std::env::temp_dir().join(format!("zblkcols{}", std::process::id()));+        let mut w = BlockedStreamWriter::create(12, &dir).expect("scratch").with_columns();+        w.push(&recs).expect("push");+        assert_eq!(w.finish().expect("finish"), sec);+        // ...and it is smaller than the row layout on curve-ordered coordinates.+        assert!(sec.len() < write_blocked(&recs, 12).len());+    }++    fn pattern_records(n: usize, len: usize) -> Vec<u8> {+        // Coordinate-like: small ints LE plus a slow counter, like NodeRecs.+        // `len` bytes per record: the 12-byte pattern truncated (7-byte edge records)+        // or zero-padded, so any stride gets whole records.+        let mut out = Vec::with_capacity(n * len);+        for i in 0..n {+            let mut rec = Vec::with_capacity(12.max(len));+            rec.extend_from_slice(&(350_000_000 + i as i32 * 37).to_le_bytes());+            rec.extend_from_slice(&(-1_200_000_000 + i as i32 * 11).to_le_bytes());+            rec.extend_from_slice(&(i as u32 * 3).to_le_bytes());+            rec.resize(len, 0);+            out.extend_from_slice(&rec);+        }+        assert_eq!(out.len(), n * len);+        out+    }++    #[test]+    fn a_blocked_section_round_trips() {+        let records = pattern_records(10_000, 12);+        let bytes = write_blocked(&records, 12);+        let s = Blocked::parse(&bytes).expect("parse");+        assert_eq!(s.unpacked_len(), records.len() as u64);+        assert_eq!(s.block_count(), 3, "10000 / 4096 rounds up");+        let mut cache = BlockCache::new(4);+        let mut back = Vec::with_capacity(records.len());+        for id in 0..10_000u64 {+            back.extend_from_slice(&s.record(id, &mut cache).expect("record"));+        }+        assert_eq!(back, records);+    }++    #[test]+    fn a_blocked_section_refuses_garbage() {+        let records = pattern_records(100, 12);+        let mut bytes = write_blocked(&records, 12);+        assert!(Blocked::parse(&bytes).is_ok());+        bytes[0] = b'X';+        assert!(Blocked::parse(&bytes).is_err(), "bad magic");+        let mut bytes = write_blocked(&records, 12);+        bytes[4] = 2;+        assert!(Blocked::parse(&bytes).is_err(), "unknown flags");+        assert!(Blocked::parse(&bytes[..10]).is_err(), "truncated");+    }++    #[test]+    fn last_block_holds_the_remainder() {+        let records = pattern_records(4097, 7);+        let bytes = write_blocked(&records, 7);+        let s = Blocked::parse(&bytes).expect("parse");+        assert_eq!(s.block_count(), 2);+        let mut cache = BlockCache::new(0);+        // First record of the last block and the very last record.+        assert_eq!(s.record(4096, &mut cache).expect("first of last"), records[4096 * 7..4097 * 7]);+        assert_eq!(s.record(4096, &mut cache).expect("cached"), records[4096 * 7..4097 * 7]);+    }++    #[test]+    fn the_streaming_writer_matches_the_whole_slice_writer() {+        let records = pattern_records(10_000, 12);+        let dir = std::env::temp_dir();+        let scratch = dir.join("tilecodec_blocked_stream_test.tmp");+        let _ = std::fs::remove_file(&scratch);+        let mut w = BlockedStreamWriter::create(12, &scratch).expect("create");+        // Odd-sized pushes (417 whole records each — `push` takes whole records only),+        // including across block boundaries.+        for chunk in records.chunks(417 * 12) {+            w.push(chunk).expect("push");+        }+        let streamed = w.finish().expect("finish");+        assert!(!scratch.exists(), "scratch is removed");+        let whole = write_blocked(&records, 12);+        assert_eq!(streamed, whole, "streaming must be byte-identical to whole-slice");+        // And the streamed bytes read back.+        let s = Blocked::parse(&streamed).expect("parse");+        assert_eq!(s.block_count(), 3);+        let mut cache = BlockCache::new(4);+        assert_eq!(s.record(9999, &mut cache).expect("last"), records[9999 * 12..10_000 * 12]);+    }++    #[test]+    fn pushing_precompressed_frames_matches_pushing_records() {+        let records = pattern_records(10_000, 12);+        let dir = std::env::temp_dir();+        let a = dir.join("tilecodec_blocked_frames_a.tmp");+        let b = dir.join("tilecodec_blocked_frames_b.tmp");+        let mut plain = BlockedStreamWriter::create(12, &a).expect("create");+        plain.push(&records).expect("push");+        let plain = plain.finish().expect("finish");+        let mut framed = BlockedStreamWriter::create(12, &b).expect("create");+        let bb = framed.block_bytes();+        let full = records.len() / bb * bb;+        let frames: Vec<Vec<u8>> = records[..full].chunks(bb).map(compress_block).collect();+        framed.push_frames(&frames).expect("frames");+        framed.push(&records[full..]).expect("tail");+        let framed = framed.finish().expect("finish");+        assert_eq!(framed, plain, "frames compressed elsewhere must be byte-identical");+    }++    #[test]+    fn a_reused_context_frames_blocks_like_a_fresh_one() {+        // Blocks of varied size and content, large before small and back, so+        // any table state leaking from one frame into the next would show.+        let mut blocks: Vec<Vec<u8>> = Vec::new();+        for (n, seed) in [(4096usize, 1u32), (17, 2), (4096, 3), (1, 4), (2500, 5), (4096, 1)] {+            let mut b = pattern_records(n, 12);+            for (i, byte) in b.iter_mut().enumerate() {+                *byte ^= (seed.wrapping_mul(2654435761).rotate_left(i as u32 % 31)) as u8 & 3;+            }+            blocks.push(b);+        }+        let fresh = |b: &[u8]| {+            let mut enc = zstd_rs::Compressor::new(zstd_rs::CompressionConfig {+                level: BLOCK_LEVEL,+                ..zstd_rs::CompressionConfig::DEFAULT+            })+            .unwrap();+            let mut f = Vec::new();+            enc.compress(b, None, &mut f).unwrap();+            f+        };+        for b in &blocks {+            assert_eq!(compress_block(b), fresh(b), "reused context diverged");+        }+    }++    #[test]+    fn finishing_into_a_writer_matches_finish() {+        let records = pattern_records(10_000, 12);+        let dir = std::env::temp_dir();+        let a = dir.join("tilecodec_blocked_into_a.tmp");+        let b = dir.join("tilecodec_blocked_into_b.tmp");+        let mut w1 = BlockedStreamWriter::create(12, &a).expect("create");+        w1.push(&records).expect("push");+        let whole = w1.finish().expect("finish");+        let mut w2 = BlockedStreamWriter::create(12, &b).expect("create");+        w2.push(&records).expect("push");+        let mut streamed = Vec::new();+        let n = w2.finish_into(&mut streamed).expect("finish_into");+        assert_eq!(n as usize, streamed.len());+        assert_eq!(streamed, whole);+        assert!(!b.exists(), "scratch is removed");+    }+}
library/tilecodec/src/main/rust/src/mamaps/body/codec.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/codec.rs b/library/tilecodec/src/main/rust/src/mamaps/body/codec.rsindex 8ab2d90e5b..03b2db2986 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/codec.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/codec.rs@@ -322,367 +322,4 @@ pub(crate) fn parse_layer(layer_id: u8, feature_count: usize, buf: &[u8]) -> Res     parse_layer_v8(layer_id, feature_count, buf) } -/// v8 payload: 24-byte records, 12-byte parts.-fn parse_layer_v8(layer_id: u8, feature_count: usize, buf: &[u8]) -> Result<Layer> {-    let features_len = feature_count * FEATURE_RECORD_LEN;-    if features_len > buf.len() {-        return err("a .mamaps layer's features run past its payload");-    }-    let mut features = Vec::with_capacity(feature_count);-    let mut parts_needed = 0usize;-    for i in 0..feature_count {-        let at = i * FEATURE_RECORD_LEN;-        let u16_at = |o: usize| u16::from_le_bytes([buf[at + o], buf[at + o + 1]]);-        let u32_at = |o: usize| {-            u32::from_le_bytes([buf[at + o], buf[at + o + 1], buf[at + o + 2], buf[at + o + 3]])-        };-        let geom_type = buf[at + 4];-        if !matches!(geom_type, GEOM_LINE | GEOM_POLYGON | GEOM_POINT) {-            return err(format!(-                "a .mamaps feature has geometry type {geom_type}, which this format does not carry"-            ));-        }-        let flags = buf[at + 5];-        if flags & !KNOWN_FEATURE_FLAGS != 0 {-            return err("a .mamaps feature sets unknown flags");-        }-        let feature = Feature {-            kind: u16_at(0),-            kind_detail: u16_at(2),-            geom_type,-            flags,-            name_idx: u16_at(6),-            parts_offset: u32_at(8),-            part_count: u32_at(12),-            transit_color: u32_at(16),-            transit_ordinal: buf[at + 20],-            transit_lanes: buf[at + 21],-            transit_taper: buf[at + 22],-            lane_count: buf[at + 23],-        };-        if feature.part_count == 0 {-            return err("a .mamaps feature has no geometry");-        }-        let end = (feature.parts_offset as usize)-            .checked_add(feature.part_count as usize)-            .ok_or_else(|| crate::proto::Error("a .mamaps feature's parts overflow".to_string()))?;-        parts_needed = parts_needed.max(end);-        features.push(feature);-    }--    let parts_at = features_len;-    let parts_len = parts_needed * PART_ENTRY_LEN;-    if parts_at + parts_len > buf.len() {-        return err("a .mamaps layer's parts run past its payload");-    }-    let mut parts = Vec::with_capacity(parts_needed);-    let mut coords_needed = 0usize;-    for i in 0..parts_needed {-        let at = parts_at + i * PART_ENTRY_LEN;-        let u32_at = |o: usize| {-            u32::from_le_bytes([buf[at + o], buf[at + o + 1], buf[at + o + 2], buf[at + o + 3]])-        };-        let winding = u16::from_le_bytes([buf[at + 8], buf[at + 9]]);-        if !matches!(winding, WINDING_OUTER | WINDING_HOLE) {-            return err(format!(-                "a .mamaps part has winding {winding}, which is neither outer nor hole"-            ));-        }-        if u16::from_le_bytes([buf[at + 10], buf[at + 11]]) != 0 {-            return err("a .mamaps part has a non-zero reserved half-word");-        }-        let part = Part { coord_start: u32_at(0), point_count: u32_at(4), winding };-        let end = (part.coord_start as usize).checked_add(part.point_count as usize).ok_or_else(-            || crate::proto::Error("a .mamaps part's coordinates overflow".to_string()),-        )?;-        coords_needed = coords_needed.max(end);-        parts.push(part);-    }--    let coords_at = align4(parts_at + parts_len);-    if coords_at > buf.len() {-        return err("a .mamaps layer's coordinate arena starts past its payload");-    }-    // Walked in parts-table order, because a varint arena has no random access: each part's points-    // are deltas from the one before it, restarting at every part.-    let mut coords = Vec::with_capacity(coords_needed);-    let mut reader = crate::proto::Reader::new(&buf[coords_at..]);-    for part in &parts {-        if part.coord_start as usize != coords.len() {-            return err(format!(-                "a .mamaps part claims to start at point {} but the arena is {} points in",-                part.coord_start,-                coords.len(),-            ));-        }-        let (mut x, mut y) = (0i32, 0i32);-        for _ in 0..part.point_count {-            x += zigzag(reader.uvarint()?);-            y += zigzag(reader.uvarint()?);-            let (Ok(x), Ok(y)) = (i16::try_from(x), i16::try_from(y)) else {-                return err("a .mamaps coordinate delta walks outside the extent an i16 holds");-            };-            coords.push((x, y));-        }-    }-    if coords.len() != coords_needed {-        return err(format!(-            "a .mamaps layer decoded {} points where its parts want {coords_needed}",-            coords.len(),-        ));-    }-    Ok(Layer { layer_id, features, parts, coords })-}--/// v10 payload: narrowed per-layer records, 4-byte parts, shared arena.-///-/// The class is a pure function of the layer id (see-/// `emit_extra::record_class`), so the reader derives the same layout the-/// writer used without a wire bit. Dropped fields read back as their defaults-/// (zero names/details/transit/lanes), and `coord_start` is reconstructed by-/// the arena walk — v10 parts are validated contiguous exactly as v8 requires.-pub(crate) fn parse_layer_v10(-    layer_id: u8,-    feature_count: usize,-    buf: &[u8],-    v12: bool,-) -> Result<Layer> {-    use super::consts::{FEATURE_RECORD_MIN_LEN, FEATURE_RECORD_ROAD_LEN, PART_ENTRY_V10_LEN};-    use super::emit_extra::{is_mixed_layer, record_class, RecordClass};-    let class = record_class(layer_id);-    let mixed = is_mixed_layer(layer_id);-    // Uniform layers stride fixed-width records; mixed layers walk a tag-    // byte per record (0 = Min, 1 = Road) so named lines keep their names.-    let mut features = Vec::with_capacity(feature_count);-    let mut parts_needed = 0usize;-    let mut at = 0usize;-    for _ in 0..feature_count {-        let feature_class = if mixed {-            if at + 1 > buf.len() {-                return err("a .mamaps mixed-layer record ends inside its class tag");-            }-            let wide = match buf[at] {-                0 => false,-                1 => true,-                t => {-                    return err(format!(-                        "a .mamaps mixed-layer record has class tag {t}, which this format does not carry"-                    ));-                }-            };-            at += 1;-            if wide {-                RecordClass::Road-            } else {-                RecordClass::Min-            }-        } else {-            class-        };-        let reclen = match feature_class {-            RecordClass::Min => FEATURE_RECORD_MIN_LEN,-            RecordClass::Road => FEATURE_RECORD_ROAD_LEN,-            RecordClass::Full => FEATURE_RECORD_LEN,-        };-        if at + reclen > buf.len() {-            return err("a .mamaps layer's features run past its payload");-        }-        let u16_at = |o: usize| u16::from_le_bytes([buf[at + o], buf[at + o + 1]]);-        let u32_at = |o: usize| {-            u32::from_le_bytes([buf[at + o], buf[at + o + 1], buf[at + o + 2], buf[at + o + 3]])-        };-        // Field offsets within the class. Min: kind(0) geom(2) flags(3)-        // off(4) cnt(8). Road adds detail(2 in v8 order...) — laid out in-        // emit order: kind, [detail,] geom, flags, [name,] off, cnt, [lane].-        let (kind_detail, name_idx, lane_count, transit);-        let (geom_type, flags, parts_offset, part_count);-        match feature_class {-            RecordClass::Min => {-                kind_detail = 0;-                name_idx = NAME_NONE;-                lane_count = 0;-                transit = (0u32, 0u8, 0u8, 0u8);-                geom_type = buf[at + 2];-                flags = buf[at + 3];-                parts_offset = u32_at(4);-                part_count = u32_at(8);-            }-            RecordClass::Road => {-                kind_detail = u16_at(2);-                name_idx = u16_at(6);-                lane_count = buf[at + 16];-                transit = (0u32, 0u8, 0u8, 0u8);-                geom_type = buf[at + 4];-                flags = buf[at + 5];-                parts_offset = u32_at(8);-                part_count = u32_at(12);-            }-            RecordClass::Full => {-                kind_detail = u16_at(2);-                name_idx = u16_at(6);-                lane_count = buf[at + 23];-                transit = (u32_at(16), buf[at + 20], buf[at + 21], buf[at + 22]);-                geom_type = buf[at + 4];-                flags = buf[at + 5];-                parts_offset = u32_at(8);-                part_count = u32_at(12);-            }-        }-        if !matches!(geom_type, GEOM_LINE | GEOM_POLYGON | GEOM_POINT) {-            return err(format!(-                "a .mamaps feature has geometry type {geom_type}, which this format does not carry"-            ));-        }-        if flags & !KNOWN_FEATURE_FLAGS != 0 {-            return err("a .mamaps feature sets unknown flags");-        }-        let feature = Feature {-            kind: u16_at(0),-            kind_detail,-            geom_type,-            flags,-            name_idx,-            parts_offset,-            part_count,-            transit_color: transit.0,-            transit_ordinal: transit.1,-            transit_lanes: transit.2,-            transit_taper: transit.3,-            lane_count,-        };-        if feature.part_count == 0 {-            return err("a .mamaps feature has no geometry");-        }-        let end = (feature.parts_offset as usize)-            .checked_add(feature.part_count as usize)-            .ok_or_else(|| crate::proto::Error("a .mamaps feature's parts overflow".to_string()))?;-        parts_needed = parts_needed.max(end);-        features.push(feature);-        at += reclen;-    }--    let parts_at = at;-    let parts_len = parts_needed * PART_ENTRY_V10_LEN;-    if parts_at + parts_len > buf.len() {-        return err("a .mamaps layer's parts run past its payload");-    }-    let mut parts = Vec::with_capacity(parts_needed);-    let mut token_parts: Vec<bool> = Vec::with_capacity(parts_needed);-    let mut coords_needed = 0usize;-    for i in 0..parts_needed {-        let at = parts_at + i * PART_ENTRY_V10_LEN;-        let point_count = u32::from(u16::from_le_bytes([buf[at], buf[at + 1]]));-        let pflags = buf[at + 2];-        let allowed = if v12 { 0x01 | super::emit_extra::PART_FLAG_SHARED_RUNS } else { 0x01 };-        if pflags & !allowed != 0 {-            return err(format!("a .mamaps part sets unknown flags {pflags:#04x}"));-        }-        if buf[at + 3] != 0 {-            return err("a .mamaps part has a non-zero reserved byte");-        }-        let winding = if pflags & 0x01 != 0 { WINDING_HOLE } else { WINDING_OUTER };-        // coord_start is reconstructed: v10 parts are contiguous by-        // construction (the writer validates), so the Nth part starts where-        // the arena walk ends.-        token_parts.push(pflags & super::emit_extra::PART_FLAG_SHARED_RUNS != 0);-        let part = Part { coord_start: coords_needed as u32, point_count, winding };-        let end = (part.coord_start as usize).checked_add(part.point_count as usize).ok_or_else(-            || crate::proto::Error("a .mamaps part's coordinates overflow".to_string()),-        )?;-        coords_needed = coords_needed.max(end);-        parts.push(part);-    }--    let coords_at = align4(parts_at + parts_len);-    if coords_at > buf.len() {-        return err("a .mamaps layer's coordinate arena starts past its payload");-    }-    // Identical arena walk to v8: varint deltas restarting at each part.-    let mut coords = Vec::with_capacity(coords_needed);-    let mut reader = crate::proto::Reader::new(&buf[coords_at..]);-    for (pi, part) in parts.iter().enumerate() {-        if part.coord_start as usize != coords.len() {-            return err(format!(-                "a .mamaps part claims to start at point {} but the arena is {} points in",-                part.coord_start,-                coords.len(),-            ));-        }-        if token_parts[pi] {-            decode_part_tokens(&mut reader, &parts, pi, &mut coords)?;-            continue;-        }-        let (mut x, mut y) = (0i32, 0i32);-        for _ in 0..part.point_count {-            x += zigzag(reader.uvarint()?);-            y += zigzag(reader.uvarint()?);-            let (Ok(x), Ok(y)) = (i16::try_from(x), i16::try_from(y)) else {-                return err("a .mamaps coordinate delta walks outside the extent an i16 holds");-            };-            coords.push((x, y));-        }-    }-    if coords.len() != coords_needed {-        return err(format!(-            "a .mamaps layer decoded {} points where its parts want {coords_needed}",-            coords.len(),-        ));-    }-    Ok(Layer { layer_id, features, parts, coords })-}--/// Decode one v12 shared-run part (see `emit_extra::encode_layer_shared_runs`) onto `coords`.-fn decode_part_tokens(-    reader: &mut crate::proto::Reader<'_>,-    parts: &[Part],-    pi: usize,-    coords: &mut Vec<(i16, i16)>,-) -> Result<()> {-    let want = parts[pi].point_count as usize;-    let start_len = coords.len();-    let (mut x, mut y) = (0i32, 0i32);-    while coords.len() - start_len < want {-        let t = reader.uvarint()?;-        let len = (t >> 1) as usize;-        if len == 0 || coords.len() - start_len + len > want {-            return err("a .mamaps shared-run token overruns its part");-        }-        if t & 1 == 0 {-            for _ in 0..len {-                x += zigzag(reader.uvarint()?);-                y += zigzag(reader.uvarint()?);-                let (Ok(xx), Ok(yy)) = (i16::try_from(x), i16::try_from(y)) else {-                    return err("a .mamaps coordinate delta walks outside the extent an i16 holds");-                };-                coords.push((xx, yy));-            }-        } else {-            let r = reader.uvarint()?;-            let back = (r >> 1) as usize;-            let reverse = r & 1 != 0;-            let start = reader.uvarint()? as usize;-            if back == 0 || back > pi {-                return err("a .mamaps shared-run copy names a part that is not earlier");-            }-            let q = &parts[pi - back];-            let qs = q.coord_start as usize;-            let qn = q.point_count as usize;-            let ok = if reverse { start < qn && start + 1 >= len } else { start + len <= qn };-            if !ok {-                return err("a .mamaps shared-run copy runs outside its source part");-            }-            for t in 0..len {-                let p = if reverse { coords[qs + start - t] } else { coords[qs + start + t] };-                coords.push(p);-            }-            let last = coords[coords.len() - 1];-            x = last.0 as i32;-            y = last.1 as i32;-        }-    }-    Ok(())-}--fn zigzag(v: u64) -> i32 {-    crate::proto::zigzag_decode(v) as i32-}+include!("codec_s1.rs");
library/tilecodec/src/main/rust/src/mamaps/body/codec_s1.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/codec_s1.rs b/library/tilecodec/src/main/rust/src/mamaps/body/codec_s1.rsnew file mode 100644index 0000000000..b5fead98b6--- /dev/null+++ b/library/tilecodec/src/main/rust/src/mamaps/body/codec_s1.rs@@ -0,0 +1,364 @@+/// v8 payload: 24-byte records, 12-byte parts.+fn parse_layer_v8(layer_id: u8, feature_count: usize, buf: &[u8]) -> Result<Layer> {+    let features_len = feature_count * FEATURE_RECORD_LEN;+    if features_len > buf.len() {+        return err("a .mamaps layer's features run past its payload");+    }+    let mut features = Vec::with_capacity(feature_count);+    let mut parts_needed = 0usize;+    for i in 0..feature_count {+        let at = i * FEATURE_RECORD_LEN;+        let u16_at = |o: usize| u16::from_le_bytes([buf[at + o], buf[at + o + 1]]);+        let u32_at = |o: usize| {+            u32::from_le_bytes([buf[at + o], buf[at + o + 1], buf[at + o + 2], buf[at + o + 3]])+        };+        let geom_type = buf[at + 4];+        if !matches!(geom_type, GEOM_LINE | GEOM_POLYGON | GEOM_POINT) {+            return err(format!(+                "a .mamaps feature has geometry type {geom_type}, which this format does not carry"+            ));+        }+        let flags = buf[at + 5];+        if flags & !KNOWN_FEATURE_FLAGS != 0 {+            return err("a .mamaps feature sets unknown flags");+        }+        let feature = Feature {+            kind: u16_at(0),+            kind_detail: u16_at(2),+            geom_type,+            flags,+            name_idx: u16_at(6),+            parts_offset: u32_at(8),+            part_count: u32_at(12),+            transit_color: u32_at(16),+            transit_ordinal: buf[at + 20],+            transit_lanes: buf[at + 21],+            transit_taper: buf[at + 22],+            lane_count: buf[at + 23],+        };+        if feature.part_count == 0 {+            return err("a .mamaps feature has no geometry");+        }+        let end = (feature.parts_offset as usize)+            .checked_add(feature.part_count as usize)+            .ok_or_else(|| crate::proto::Error("a .mamaps feature's parts overflow".to_string()))?;+        parts_needed = parts_needed.max(end);+        features.push(feature);+    }++    let parts_at = features_len;+    let parts_len = parts_needed * PART_ENTRY_LEN;+    if parts_at + parts_len > buf.len() {+        return err("a .mamaps layer's parts run past its payload");+    }+    let mut parts = Vec::with_capacity(parts_needed);+    let mut coords_needed = 0usize;+    for i in 0..parts_needed {+        let at = parts_at + i * PART_ENTRY_LEN;+        let u32_at = |o: usize| {+            u32::from_le_bytes([buf[at + o], buf[at + o + 1], buf[at + o + 2], buf[at + o + 3]])+        };+        let winding = u16::from_le_bytes([buf[at + 8], buf[at + 9]]);+        if !matches!(winding, WINDING_OUTER | WINDING_HOLE) {+            return err(format!(+                "a .mamaps part has winding {winding}, which is neither outer nor hole"+            ));+        }+        if u16::from_le_bytes([buf[at + 10], buf[at + 11]]) != 0 {+            return err("a .mamaps part has a non-zero reserved half-word");+        }+        let part = Part { coord_start: u32_at(0), point_count: u32_at(4), winding };+        let end = (part.coord_start as usize).checked_add(part.point_count as usize).ok_or_else(+            || crate::proto::Error("a .mamaps part's coordinates overflow".to_string()),+        )?;+        coords_needed = coords_needed.max(end);+        parts.push(part);+    }++    let coords_at = align4(parts_at + parts_len);+    if coords_at > buf.len() {+        return err("a .mamaps layer's coordinate arena starts past its payload");+    }+    // Walked in parts-table order, because a varint arena has no random access: each part's points+    // are deltas from the one before it, restarting at every part.+    let mut coords = Vec::with_capacity(coords_needed);+    let mut reader = crate::proto::Reader::new(&buf[coords_at..]);+    for part in &parts {+        if part.coord_start as usize != coords.len() {+            return err(format!(+                "a .mamaps part claims to start at point {} but the arena is {} points in",+                part.coord_start,+                coords.len(),+            ));+        }+        let (mut x, mut y) = (0i32, 0i32);+        for _ in 0..part.point_count {+            x += zigzag(reader.uvarint()?);+            y += zigzag(reader.uvarint()?);+            let (Ok(x), Ok(y)) = (i16::try_from(x), i16::try_from(y)) else {+                return err("a .mamaps coordinate delta walks outside the extent an i16 holds");+            };+            coords.push((x, y));+        }+    }+    if coords.len() != coords_needed {+        return err(format!(+            "a .mamaps layer decoded {} points where its parts want {coords_needed}",+            coords.len(),+        ));+    }+    Ok(Layer { layer_id, features, parts, coords })+}++/// v10 payload: narrowed per-layer records, 4-byte parts, shared arena.+///+/// The class is a pure function of the layer id (see+/// `emit_extra::record_class`), so the reader derives the same layout the+/// writer used without a wire bit. Dropped fields read back as their defaults+/// (zero names/details/transit/lanes), and `coord_start` is reconstructed by+/// the arena walk — v10 parts are validated contiguous exactly as v8 requires.+pub(crate) fn parse_layer_v10(+    layer_id: u8,+    feature_count: usize,+    buf: &[u8],+    v12: bool,+) -> Result<Layer> {+    use super::consts::{FEATURE_RECORD_MIN_LEN, FEATURE_RECORD_ROAD_LEN, PART_ENTRY_V10_LEN};+    use super::emit_extra::{is_mixed_layer, record_class, RecordClass};+    let class = record_class(layer_id);+    let mixed = is_mixed_layer(layer_id);+    // Uniform layers stride fixed-width records; mixed layers walk a tag+    // byte per record (0 = Min, 1 = Road) so named lines keep their names.+    let mut features = Vec::with_capacity(feature_count);+    let mut parts_needed = 0usize;+    let mut at = 0usize;+    for _ in 0..feature_count {+        let feature_class = if mixed {+            if at + 1 > buf.len() {+                return err("a .mamaps mixed-layer record ends inside its class tag");+            }+            let wide = match buf[at] {+                0 => false,+                1 => true,+                t => {+                    return err(format!(+                        "a .mamaps mixed-layer record has class tag {t}, which this format does not carry"+                    ));+                }+            };+            at += 1;+            if wide {+                RecordClass::Road+            } else {+                RecordClass::Min+            }+        } else {+            class+        };+        let reclen = match feature_class {+            RecordClass::Min => FEATURE_RECORD_MIN_LEN,+            RecordClass::Road => FEATURE_RECORD_ROAD_LEN,+            RecordClass::Full => FEATURE_RECORD_LEN,+        };+        if at + reclen > buf.len() {+            return err("a .mamaps layer's features run past its payload");+        }+        let u16_at = |o: usize| u16::from_le_bytes([buf[at + o], buf[at + o + 1]]);+        let u32_at = |o: usize| {+            u32::from_le_bytes([buf[at + o], buf[at + o + 1], buf[at + o + 2], buf[at + o + 3]])+        };+        // Field offsets within the class. Min: kind(0) geom(2) flags(3)+        // off(4) cnt(8). Road adds detail(2 in v8 order...) — laid out in+        // emit order: kind, [detail,] geom, flags, [name,] off, cnt, [lane].+        let (kind_detail, name_idx, lane_count, transit);+        let (geom_type, flags, parts_offset, part_count);+        match feature_class {+            RecordClass::Min => {+                kind_detail = 0;+                name_idx = NAME_NONE;+                lane_count = 0;+                transit = (0u32, 0u8, 0u8, 0u8);+                geom_type = buf[at + 2];+                flags = buf[at + 3];+                parts_offset = u32_at(4);+                part_count = u32_at(8);+            }+            RecordClass::Road => {+                kind_detail = u16_at(2);+                name_idx = u16_at(6);+                lane_count = buf[at + 16];+                transit = (0u32, 0u8, 0u8, 0u8);+                geom_type = buf[at + 4];+                flags = buf[at + 5];+                parts_offset = u32_at(8);+                part_count = u32_at(12);+            }+            RecordClass::Full => {+                kind_detail = u16_at(2);+                name_idx = u16_at(6);+                lane_count = buf[at + 23];+                transit = (u32_at(16), buf[at + 20], buf[at + 21], buf[at + 22]);+                geom_type = buf[at + 4];+                flags = buf[at + 5];+                parts_offset = u32_at(8);+                part_count = u32_at(12);+            }+        }+        if !matches!(geom_type, GEOM_LINE | GEOM_POLYGON | GEOM_POINT) {+            return err(format!(+                "a .mamaps feature has geometry type {geom_type}, which this format does not carry"+            ));+        }+        if flags & !KNOWN_FEATURE_FLAGS != 0 {+            return err("a .mamaps feature sets unknown flags");+        }+        let feature = Feature {+            kind: u16_at(0),+            kind_detail,+            geom_type,+            flags,+            name_idx,+            parts_offset,+            part_count,+            transit_color: transit.0,+            transit_ordinal: transit.1,+            transit_lanes: transit.2,+            transit_taper: transit.3,+            lane_count,+        };+        if feature.part_count == 0 {+            return err("a .mamaps feature has no geometry");+        }+        let end = (feature.parts_offset as usize)+            .checked_add(feature.part_count as usize)+            .ok_or_else(|| crate::proto::Error("a .mamaps feature's parts overflow".to_string()))?;+        parts_needed = parts_needed.max(end);+        features.push(feature);+        at += reclen;+    }++    let parts_at = at;+    let parts_len = parts_needed * PART_ENTRY_V10_LEN;+    if parts_at + parts_len > buf.len() {+        return err("a .mamaps layer's parts run past its payload");+    }+    let mut parts = Vec::with_capacity(parts_needed);+    let mut token_parts: Vec<bool> = Vec::with_capacity(parts_needed);+    let mut coords_needed = 0usize;+    for i in 0..parts_needed {+        let at = parts_at + i * PART_ENTRY_V10_LEN;+        let point_count = u32::from(u16::from_le_bytes([buf[at], buf[at + 1]]));+        let pflags = buf[at + 2];+        let allowed = if v12 { 0x01 | super::emit_extra::PART_FLAG_SHARED_RUNS } else { 0x01 };+        if pflags & !allowed != 0 {+            return err(format!("a .mamaps part sets unknown flags {pflags:#04x}"));+        }+        if buf[at + 3] != 0 {+            return err("a .mamaps part has a non-zero reserved byte");+        }+        let winding = if pflags & 0x01 != 0 { WINDING_HOLE } else { WINDING_OUTER };+        // coord_start is reconstructed: v10 parts are contiguous by+        // construction (the writer validates), so the Nth part starts where+        // the arena walk ends.+        token_parts.push(pflags & super::emit_extra::PART_FLAG_SHARED_RUNS != 0);+        let part = Part { coord_start: coords_needed as u32, point_count, winding };+        let end = (part.coord_start as usize).checked_add(part.point_count as usize).ok_or_else(+            || crate::proto::Error("a .mamaps part's coordinates overflow".to_string()),+        )?;+        coords_needed = coords_needed.max(end);+        parts.push(part);+    }++    let coords_at = align4(parts_at + parts_len);+    if coords_at > buf.len() {+        return err("a .mamaps layer's coordinate arena starts past its payload");+    }+    // Identical arena walk to v8: varint deltas restarting at each part.+    let mut coords = Vec::with_capacity(coords_needed);+    let mut reader = crate::proto::Reader::new(&buf[coords_at..]);+    for (pi, part) in parts.iter().enumerate() {+        if part.coord_start as usize != coords.len() {+            return err(format!(+                "a .mamaps part claims to start at point {} but the arena is {} points in",+                part.coord_start,+                coords.len(),+            ));+        }+        if token_parts[pi] {+            decode_part_tokens(&mut reader, &parts, pi, &mut coords)?;+            continue;+        }+        let (mut x, mut y) = (0i32, 0i32);+        for _ in 0..part.point_count {+            x += zigzag(reader.uvarint()?);+            y += zigzag(reader.uvarint()?);+            let (Ok(x), Ok(y)) = (i16::try_from(x), i16::try_from(y)) else {+                return err("a .mamaps coordinate delta walks outside the extent an i16 holds");+            };+            coords.push((x, y));+        }+    }+    if coords.len() != coords_needed {+        return err(format!(+            "a .mamaps layer decoded {} points where its parts want {coords_needed}",+            coords.len(),+        ));+    }+    Ok(Layer { layer_id, features, parts, coords })+}++/// Decode one v12 shared-run part (see `emit_extra::encode_layer_shared_runs`) onto `coords`.+fn decode_part_tokens(+    reader: &mut crate::proto::Reader<'_>,+    parts: &[Part],+    pi: usize,+    coords: &mut Vec<(i16, i16)>,+) -> Result<()> {+    let want = parts[pi].point_count as usize;+    let start_len = coords.len();+    let (mut x, mut y) = (0i32, 0i32);+    while coords.len() - start_len < want {+        let t = reader.uvarint()?;+        let len = (t >> 1) as usize;+        if len == 0 || coords.len() - start_len + len > want {+            return err("a .mamaps shared-run token overruns its part");+        }+        if t & 1 == 0 {+            for _ in 0..len {+                x += zigzag(reader.uvarint()?);+                y += zigzag(reader.uvarint()?);+                let (Ok(xx), Ok(yy)) = (i16::try_from(x), i16::try_from(y)) else {+                    return err("a .mamaps coordinate delta walks outside the extent an i16 holds");+                };+                coords.push((xx, yy));+            }+        } else {+            let r = reader.uvarint()?;+            let back = (r >> 1) as usize;+            let reverse = r & 1 != 0;+            let start = reader.uvarint()? as usize;+            if back == 0 || back > pi {+                return err("a .mamaps shared-run copy names a part that is not earlier");+            }+            let q = &parts[pi - back];+            let qs = q.coord_start as usize;+            let qn = q.point_count as usize;+            let ok = if reverse { start < qn && start + 1 >= len } else { start + len <= qn };+            if !ok {+                return err("a .mamaps shared-run copy runs outside its source part");+            }+            for t in 0..len {+                let p = if reverse { coords[qs + start - t] } else { coords[qs + start + t] };+                coords.push(p);+            }+            let last = coords[coords.len() - 1];+            x = last.0 as i32;+            y = last.1 as i32;+        }+    }+    Ok(())+}++fn zigzag(v: u64) -> i32 {+    crate::proto::zigzag_decode(v) as i32+}
library/tilecodec/src/main/rust/src/mamaps/body/tables.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/tables.rs b/library/tilecodec/src/main/rust/src/mamaps/body/tables.rsindex 1bc4ab1cc9..644a8d42d3 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/tables.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/tables.rs@@ -408,221 +408,4 @@ pub fn serialize_lanes(turn_lanes: &[(u8, Vec<LaneTurns>)], out: &mut Vec<u8>) {     } } -/// Parse the carriageway table: a `u8` [`MarkingConvention`] byte for the whole tile, three-/// reserved bytes, then the same framing [`parse_lanes`] uses — a `u32` entry count, then per entry-/// a `u8` layer id, three reserved bytes, a `u32` record count and that many fixed 6-byte records-/// (`u8` forward, `u8` backward, `u32` solid divider bits, little-endian).-///-/// The convention leads rather than trailing so it is readable without walking the entries, and it-/// is per tile rather than per record because a tile never meaningfully spans two conventions.-///-/// Validation matches [`parse_lanes`] exactly: an entry must name a layer the body carries, entries-/// ascend and are distinct by layer id, and a layer's record vector is exactly as long as its-/// feature vector — a mismatch would misattribute every road's carriageway after the first.-pub(crate) fn parse_carriageways(-    buf: &[u8],-    layers: &[Layer],-) -> Result<(LayerTable<Carriageway>, MarkingConvention, usize)> {-    if buf.len() < 8 {-        return err("a .mamaps carriageway table ends before its header");-    }-    let convention = MarkingConvention::from_byte(buf[0])?;-    if buf[1] != 0 || u16::from_le_bytes([buf[2], buf[3]]) != 0 {-        return err("a .mamaps carriageway table has non-zero reserved bytes");-    }-    let count = u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]) as usize;-    if count > layers.len() {-        return err(format!(-            "a .mamaps carriageway table has {count} entries for a body with {} layer(s)",-            layers.len(),-        ));-    }-    let mut at = 8usize;-    let mut table = Vec::with_capacity(count);-    let mut previous: Option<u8> = None;-    for _ in 0..count {-        if at + 8 > buf.len() {-            return err("a .mamaps carriageway table ends inside an entry header");-        }-        let layer_id = buf[at];-        if buf[at + 1] != 0 || u16::from_le_bytes([buf[at + 2], buf[at + 3]]) != 0 {-            return err("a .mamaps carriageway table entry has non-zero reserved bytes");-        }-        let feat_len =-            u32::from_le_bytes([buf[at + 4], buf[at + 5], buf[at + 6], buf[at + 7]]) as usize;-        at += 8;-        if previous.is_some_and(|p| layer_id <= p) {-            return err("a .mamaps carriageway table's entries are not ordered by layer id");-        }-        previous = Some(layer_id);-        let Some(layer) = layers.iter().find(|l| l.layer_id == layer_id) else {-            return err(format!(-                "a .mamaps carriageway table names layer {layer_id}, which the body does not carry"-            ));-        };-        if feat_len != layer.features.len() {-            return err(format!(-                "a .mamaps carriageway table gives layer {layer_id} {feat_len} record(s) for {} \-                 feature(s)",-                layer.features.len(),-            ));-        }-        // Bounded against the slice before allocating, so a corrupt count cannot ask for a-        // gigabyte of `Vec` — the same discipline `parse_lanes` and `parse_layer` apply.-        let bytes = feat_len.checked_mul(CARRIAGEWAY_RECORD_LEN).ok_or_else(|| {-            crate::proto::Error("a .mamaps carriageway table overflows".to_string())-        })?;-        if at + bytes > buf.len() {-            return err("a .mamaps carriageway table's records run past the table");-        }-        let mut rows = Vec::with_capacity(feat_len);-        for _ in 0..feat_len {-            rows.push(Carriageway {-                forward: buf[at],-                backward: buf[at + 1],-                solid_dividers: u32::from_le_bytes([-                    buf[at + 2],-                    buf[at + 3],-                    buf[at + 4],-                    buf[at + 5],-                ]),-            });-            at += CARRIAGEWAY_RECORD_LEN;-        }-        table.push((layer_id, rows));-    }-    let aligned = align4(at);-    if aligned > buf.len() {-        return err("a .mamaps carriageway table's padding runs past the body");-    }-    Ok((table, convention, aligned))-}--/// Serialise a carriageway table, 4-byte aligned. The inverse of [`parse_carriageways`].-pub fn serialize_carriageways(-    carriageways: &[(u8, Vec<Carriageway>)],-    convention: MarkingConvention,-    out: &mut Vec<u8>,-) {-    out.push(convention.to_byte());-    out.extend_from_slice(&[0u8; 3]);-    out.extend_from_slice(&(carriageways.len() as u32).to_le_bytes());-    for (layer_id, entries) in carriageways {-        out.push(*layer_id);-        out.extend_from_slice(&[0u8; 3]);-        out.extend_from_slice(&(entries.len() as u32).to_le_bytes());-        for row in entries {-            out.push(row.forward);-            out.push(row.backward);-            out.extend_from_slice(&row.solid_dividers.to_le_bytes());-        }-    }-    while out.len() % 4 != 0 {-        out.push(0);-    }-}--/// Parse the per-tile heightmap: a `u16` grid side length `dim`, then `dim * dim` `u16` samples,-/// row-major. Returns the grid and the bytes consumed (including 4-byte alignment padding).-///-/// A zero `dim` is refused rather than read as an empty grid: an elevation-free tile omits the-/// section (the flag is clear) instead of writing a degenerate one, so a zero here is corruption.-pub(crate) fn parse_heightmap(buf: &[u8]) -> Result<(Heightmap, usize)> {-    if buf.len() < 2 {-        return err("a .mamaps heightmap ends before its dimension");-    }-    let dim = u16::from_le_bytes([buf[0], buf[1]]);-    if dim == 0 {-        return err("a .mamaps heightmap has a zero dimension");-    }-    let cells = dim as usize * dim as usize;-    let bytes = cells-        .checked_mul(2)-        .ok_or_else(|| crate::proto::Error("a .mamaps heightmap's grid overflows".to_string()))?;-    let mut at = 2usize;-    if at + bytes > buf.len() {-        return err("a .mamaps heightmap's samples run past the body");-    }-    let mut samples = Vec::with_capacity(cells);-    for i in 0..cells {-        let o = at + i * 2;-        samples.push(u16::from_le_bytes([buf[o], buf[o + 1]]));-    }-    at += bytes;-    let aligned = align4(at);-    if aligned > buf.len() {-        return err("a .mamaps heightmap's padding runs past the body");-    }-    Ok((Heightmap { dim, samples }, aligned))-}--/// Serialise a per-tile heightmap, 4-byte aligned. The inverse of [`parse_heightmap`].-pub fn serialize_heightmap(grid: &Heightmap, out: &mut Vec<u8>) {-    out.extend_from_slice(&grid.dim.to_le_bytes());-    for &s in &grid.samples {-        out.extend_from_slice(&s.to_le_bytes());-    }-    while out.len() % 4 != 0 {-        out.push(0);-    }-}--/// The MED (LOCO-I) prediction for sample `(r, c)` of a `d x d` grid from already-known-/// neighbours: left, up and up-left. First row predicts from the left, first column from above,-/// the first sample from sea level (32768). Shared by the encoder and the decoder so they agree.-#[inline]-fn med_predict(s: &[u16], d: usize, r: usize, c: usize) -> u16 {-    if r == 0 && c == 0 {-        return 32768;-    }-    if r == 0 {-        return s[c - 1];-    }-    if c == 0 {-        return s[(r - 1) * d];-    }-    let (l, u, ul) =-        (s[r * d + c - 1] as i32, s[(r - 1) * d + c] as i32, s[(r - 1) * d + c - 1] as i32);-    let (lo, hi) = (l.min(u), l.max(u));-    let p = if ul >= hi {-        lo-    } else if ul <= lo {-        hi-    } else {-        l + u - ul-    };-    p as u16-}--/// Serialise a heightmap as v11 MED residuals: the same `dim` + `dim*dim` u16 layout as-/// [`serialize_heightmap`], each sample replaced by `zigzag((sample - prediction) mod 2^16)`.-/// Flat or smoothly sloping ground becomes runs of tiny values, which is what zstd needs.-pub fn serialize_heightmap_residual(grid: &Heightmap, out: &mut Vec<u8>) {-    let d = grid.dim as usize;-    out.extend_from_slice(&grid.dim.to_le_bytes());-    for r in 0..d {-        for c in 0..d {-            let v = grid.samples[r * d + c];-            let e = v.wrapping_sub(med_predict(&grid.samples, d, r, c)) as i16;-            let zz = ((e << 1) ^ (e >> 15)) as u16;-            out.extend_from_slice(&zz.to_le_bytes());-        }-    }-    while out.len() % 4 != 0 {-        out.push(0);-    }-}--/// Undo [`serialize_heightmap_residual`] in place, in raster order so every prediction reads-/// samples already reconstructed.-pub(crate) fn unresidual_heightmap(grid: &mut Heightmap) {-    let d = grid.dim as usize;-    for r in 0..d {-        for c in 0..d {-            let zz = grid.samples[r * d + c];-            let e = ((zz >> 1) as i16) ^ -((zz & 1) as i16);-            let p = med_predict(&grid.samples, d, r, c);-            grid.samples[r * d + c] = p.wrapping_add(e as u16);-        }-    }-}+include!("tables_s1.rs");
library/tilecodec/src/main/rust/src/mamaps/body/tables_extra.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/tables_extra.rs b/library/tilecodec/src/main/rust/src/mamaps/body/tables_extra.rsindex 755e7cc12a..9ce8e05ff9 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/tables_extra.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/tables_extra.rs@@ -415,148 +415,4 @@ fn pack_attrs(a: &BuildingAttrs) -> u8 {     packed } -/// Parse the v10 sparse S3DB table: `u32` layer count, then per layer a `u8`-/// id, a `u32` feature count, a bitset of the features carrying tags-/// (`(n+7)/8` bytes), and the packed 14-byte non-default entries in feature-/// order. Expands to the dense model (defaults filled), so the reader API is-/// unchanged. Returns the table and the bytes consumed.-pub(crate) fn parse_sparse_buildings(-    buf: &[u8],-    layers: &[Layer],-) -> Result<(LayerTable<BuildingAttrs>, usize)> {-    use super::model::{ROOF_ORIENT_ACROSS, ROOF_ORIENT_ALONG};-    if buf.len() < 4 {-        return err("a .mamaps sparse building table ends before its count");-    }-    let count = u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize;-    if count > layers.len() {-        return err(format!(-            "a .mamaps sparse building table has {count} entries for a body with {} layer(s)",-            layers.len(),-        ));-    }-    let mut at = 4usize;-    let mut table = Vec::with_capacity(count);-    let mut previous: Option<u8> = None;-    for _ in 0..count {-        if at + 5 > buf.len() {-            return err("a .mamaps sparse building table ends inside an entry header");-        }-        let layer_id = buf[at];-        let n = u32::from_le_bytes([buf[at + 1], buf[at + 2], buf[at + 3], buf[at + 4]]) as usize;-        at += 5;-        if previous.is_some_and(|p| layer_id <= p) {-            return err("a .mamaps sparse building table's entries are not ordered by layer id");-        }-        previous = Some(layer_id);-        let Some(layer) = layers.iter().find(|l| l.layer_id == layer_id) else {-            return err(format!(-                "a .mamaps sparse building table names layer {layer_id}, which the body does not carry"-            ));-        };-        if n != layer.features.len() {-            return err(format!(-                "a .mamaps sparse building table gives layer {layer_id} {n} bit(s) for {} feature(s)",-                layer.features.len(),-            ));-        }-        let bitlen = n.div_ceil(8);-        if at + bitlen > buf.len() {-            return err("a .mamaps sparse building table ends inside its bitset");-        }-        let bits = &buf[at..at + bitlen];-        at += bitlen;-        let mut attrs = Vec::with_capacity(n);-        for i in 0..n {-            if bits[i / 8] & (1u8 << (i % 8)) == 0 {-                attrs.push(BuildingAttrs::default());-                continue;-            }-            if at + BUILDING_ATTRS_V10_LEN > buf.len() {-                return err("a .mamaps sparse building record runs past the table");-            }-            let o = at;-            let roof_shape = buf[o + 6] & 0x07;-            if roof_shape > ROOF_SHAPE_MAX {-                return err(format!(-                    "a .mamaps sparse building record has roof shape {roof_shape}"-                ));-            }-            let roof_orientation =-                if buf[o + 6] & 0x08 != 0 { ROOF_ORIENT_ACROSS } else { ROOF_ORIENT_ALONG };-            let has_bcol = buf[o + 6] & 0x10 != 0;-            let has_rcol = buf[o + 6] & 0x20 != 0;-            if buf[o + 6] & 0xC0 != 0 {-                return err("a .mamaps sparse building record sets reserved flag bits");-            }-            let bcol = u32::from_le_bytes([buf[o + 8], buf[o + 9], buf[o + 10], 0xFF]);-            let rcol = u32::from_le_bytes([buf[o + 11], buf[o + 12], buf[o + 13], 0xFF]);-            if !has_bcol && (buf[o + 8] != 0 || buf[o + 9] != 0 || buf[o + 10] != 0) {-                return err("a .mamaps sparse building record carries a colour it disclaims");-            }-            if !has_rcol && (buf[o + 11] != 0 || buf[o + 12] != 0 || buf[o + 13] != 0) {-                return err("a .mamaps sparse building record carries a colour it disclaims");-            }-            attrs.push(BuildingAttrs {-                height: u16::from_le_bytes([buf[o], buf[o + 1]]),-                min_height: u16::from_le_bytes([buf[o + 2], buf[o + 3]]),-                roof_height: u16::from_le_bytes([buf[o + 4], buf[o + 5]]),-                roof_shape,-                roof_direction: buf[o + 7],-                roof_orientation,-                building_colour: if has_bcol { bcol } else { 0 },-                roof_colour: if has_rcol { rcol } else { 0 },-            });-            at += BUILDING_ATTRS_V10_LEN;-        }-        table.push((layer_id, attrs));-    }-    let aligned = align4(at);-    if aligned > buf.len() {-        return err("a .mamaps sparse building table's padding runs past the body");-    }-    Ok((table, aligned))-}--/// Serialise a sparse S3DB table, 4-byte aligned. Layers with no tagged-/// buildings are omitted entirely (the reader restores all-default); the-/// inverse of [`parse_sparse_buildings`].-pub fn serialize_sparse_buildings(buildings: &[(u8, Vec<BuildingAttrs>)], out: &mut Vec<u8>) {-    let present: Vec<(&u8, &Vec<BuildingAttrs>)> = buildings-        .iter()-        .map(|(id, v)| (id, v))-        .filter(|(_, v)| v.iter().any(|a| !is_default_attrs(a)))-        .collect();-    out.extend_from_slice(&(present.len() as u32).to_le_bytes());-    for (layer_id, entries) in present {-        out.push(*layer_id);-        out.extend_from_slice(&(entries.len() as u32).to_le_bytes());-        let mut bits = vec![0u8; entries.len().div_ceil(8)];-        for (i, a) in entries.iter().enumerate() {-            if !is_default_attrs(a) {-                bits[i / 8] |= 1u8 << (i % 8);-            }-        }-        out.extend_from_slice(&bits);-        for a in entries {-            if is_default_attrs(a) {-                continue;-            }-            out.extend_from_slice(&a.height.to_le_bytes());-            out.extend_from_slice(&a.min_height.to_le_bytes());-            out.extend_from_slice(&a.roof_height.to_le_bytes());-            out.push(pack_attrs(a));-            out.push(a.roof_direction);-            // RGB24: alpha is always FF-or-absent, presence in the packed flags.-            out.push((a.building_colour & 0xFF) as u8);-            out.push(((a.building_colour >> 8) & 0xFF) as u8);-            out.push(((a.building_colour >> 16) & 0xFF) as u8);-            out.push((a.roof_colour & 0xFF) as u8);-            out.push(((a.roof_colour >> 8) & 0xFF) as u8);-            out.push(((a.roof_colour >> 16) & 0xFF) as u8);-        }-    }-    while out.len() % 4 != 0 {-        out.push(0);-    }-}+include!("tables_extra_s1.rs");
library/tilecodec/src/main/rust/src/mamaps/body/tables_extra_s1.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/tables_extra_s1.rs b/library/tilecodec/src/main/rust/src/mamaps/body/tables_extra_s1.rsnew file mode 100644index 0000000000..ae071bc46a--- /dev/null+++ b/library/tilecodec/src/main/rust/src/mamaps/body/tables_extra_s1.rs@@ -0,0 +1,145 @@+/// Parse the v10 sparse S3DB table: `u32` layer count, then per layer a `u8`+/// id, a `u32` feature count, a bitset of the features carrying tags+/// (`(n+7)/8` bytes), and the packed 14-byte non-default entries in feature+/// order. Expands to the dense model (defaults filled), so the reader API is+/// unchanged. Returns the table and the bytes consumed.+pub(crate) fn parse_sparse_buildings(+    buf: &[u8],+    layers: &[Layer],+) -> Result<(LayerTable<BuildingAttrs>, usize)> {+    use super::model::{ROOF_ORIENT_ACROSS, ROOF_ORIENT_ALONG};+    if buf.len() < 4 {+        return err("a .mamaps sparse building table ends before its count");+    }+    let count = u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize;+    if count > layers.len() {+        return err(format!(+            "a .mamaps sparse building table has {count} entries for a body with {} layer(s)",+            layers.len(),+        ));+    }+    let mut at = 4usize;+    let mut table = Vec::with_capacity(count);+    let mut previous: Option<u8> = None;+    for _ in 0..count {+        if at + 5 > buf.len() {+            return err("a .mamaps sparse building table ends inside an entry header");+        }+        let layer_id = buf[at];+        let n = u32::from_le_bytes([buf[at + 1], buf[at + 2], buf[at + 3], buf[at + 4]]) as usize;+        at += 5;+        if previous.is_some_and(|p| layer_id <= p) {+            return err("a .mamaps sparse building table's entries are not ordered by layer id");+        }+        previous = Some(layer_id);+        let Some(layer) = layers.iter().find(|l| l.layer_id == layer_id) else {+            return err(format!(+                "a .mamaps sparse building table names layer {layer_id}, which the body does not carry"+            ));+        };+        if n != layer.features.len() {+            return err(format!(+                "a .mamaps sparse building table gives layer {layer_id} {n} bit(s) for {} feature(s)",+                layer.features.len(),+            ));+        }+        let bitlen = n.div_ceil(8);+        if at + bitlen > buf.len() {+            return err("a .mamaps sparse building table ends inside its bitset");+        }+        let bits = &buf[at..at + bitlen];+        at += bitlen;+        let mut attrs = Vec::with_capacity(n);+        for i in 0..n {+            if bits[i / 8] & (1u8 << (i % 8)) == 0 {+                attrs.push(BuildingAttrs::default());+                continue;+            }+            if at + BUILDING_ATTRS_V10_LEN > buf.len() {+                return err("a .mamaps sparse building record runs past the table");+            }+            let o = at;+            let roof_shape = buf[o + 6] & 0x07;+            if roof_shape > ROOF_SHAPE_MAX {+                return err(format!(+                    "a .mamaps sparse building record has roof shape {roof_shape}"+                ));+            }+            let roof_orientation =+                if buf[o + 6] & 0x08 != 0 { ROOF_ORIENT_ACROSS } else { ROOF_ORIENT_ALONG };+            let has_bcol = buf[o + 6] & 0x10 != 0;+            let has_rcol = buf[o + 6] & 0x20 != 0;+            if buf[o + 6] & 0xC0 != 0 {+                return err("a .mamaps sparse building record sets reserved flag bits");+            }+            let bcol = u32::from_le_bytes([buf[o + 8], buf[o + 9], buf[o + 10], 0xFF]);+            let rcol = u32::from_le_bytes([buf[o + 11], buf[o + 12], buf[o + 13], 0xFF]);+            if !has_bcol && (buf[o + 8] != 0 || buf[o + 9] != 0 || buf[o + 10] != 0) {+                return err("a .mamaps sparse building record carries a colour it disclaims");+            }+            if !has_rcol && (buf[o + 11] != 0 || buf[o + 12] != 0 || buf[o + 13] != 0) {+                return err("a .mamaps sparse building record carries a colour it disclaims");+            }+            attrs.push(BuildingAttrs {+                height: u16::from_le_bytes([buf[o], buf[o + 1]]),+                min_height: u16::from_le_bytes([buf[o + 2], buf[o + 3]]),+                roof_height: u16::from_le_bytes([buf[o + 4], buf[o + 5]]),+                roof_shape,+                roof_direction: buf[o + 7],+                roof_orientation,+                building_colour: if has_bcol { bcol } else { 0 },+                roof_colour: if has_rcol { rcol } else { 0 },+            });+            at += BUILDING_ATTRS_V10_LEN;+        }+        table.push((layer_id, attrs));+    }+    let aligned = align4(at);+    if aligned > buf.len() {+        return err("a .mamaps sparse building table's padding runs past the body");+    }+    Ok((table, aligned))+}++/// Serialise a sparse S3DB table, 4-byte aligned. Layers with no tagged+/// buildings are omitted entirely (the reader restores all-default); the+/// inverse of [`parse_sparse_buildings`].+pub fn serialize_sparse_buildings(buildings: &[(u8, Vec<BuildingAttrs>)], out: &mut Vec<u8>) {+    let present: Vec<(&u8, &Vec<BuildingAttrs>)> = buildings+        .iter()+        .map(|(id, v)| (id, v))+        .filter(|(_, v)| v.iter().any(|a| !is_default_attrs(a)))+        .collect();+    out.extend_from_slice(&(present.len() as u32).to_le_bytes());+    for (layer_id, entries) in present {+        out.push(*layer_id);+        out.extend_from_slice(&(entries.len() as u32).to_le_bytes());+        let mut bits = vec![0u8; entries.len().div_ceil(8)];+        for (i, a) in entries.iter().enumerate() {+            if !is_default_attrs(a) {+                bits[i / 8] |= 1u8 << (i % 8);+            }+        }+        out.extend_from_slice(&bits);+        for a in entries {+            if is_default_attrs(a) {+                continue;+            }+            out.extend_from_slice(&a.height.to_le_bytes());+            out.extend_from_slice(&a.min_height.to_le_bytes());+            out.extend_from_slice(&a.roof_height.to_le_bytes());+            out.push(pack_attrs(a));+            out.push(a.roof_direction);+            // RGB24: alpha is always FF-or-absent, presence in the packed flags.+            out.push((a.building_colour & 0xFF) as u8);+            out.push(((a.building_colour >> 8) & 0xFF) as u8);+            out.push(((a.building_colour >> 16) & 0xFF) as u8);+            out.push((a.roof_colour & 0xFF) as u8);+            out.push(((a.roof_colour >> 8) & 0xFF) as u8);+            out.push(((a.roof_colour >> 16) & 0xFF) as u8);+        }+    }+    while out.len() % 4 != 0 {+        out.push(0);+    }+}
library/tilecodec/src/main/rust/src/mamaps/body/tables_s1.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/tables_s1.rs b/library/tilecodec/src/main/rust/src/mamaps/body/tables_s1.rsnew file mode 100644index 0000000000..b20d8c6bca--- /dev/null+++ b/library/tilecodec/src/main/rust/src/mamaps/body/tables_s1.rs@@ -0,0 +1,218 @@+/// Parse the carriageway table: a `u8` [`MarkingConvention`] byte for the whole tile, three+/// reserved bytes, then the same framing [`parse_lanes`] uses — a `u32` entry count, then per entry+/// a `u8` layer id, three reserved bytes, a `u32` record count and that many fixed 6-byte records+/// (`u8` forward, `u8` backward, `u32` solid divider bits, little-endian).+///+/// The convention leads rather than trailing so it is readable without walking the entries, and it+/// is per tile rather than per record because a tile never meaningfully spans two conventions.+///+/// Validation matches [`parse_lanes`] exactly: an entry must name a layer the body carries, entries+/// ascend and are distinct by layer id, and a layer's record vector is exactly as long as its+/// feature vector — a mismatch would misattribute every road's carriageway after the first.+pub(crate) fn parse_carriageways(+    buf: &[u8],+    layers: &[Layer],+) -> Result<(LayerTable<Carriageway>, MarkingConvention, usize)> {+    if buf.len() < 8 {+        return err("a .mamaps carriageway table ends before its header");+    }+    let convention = MarkingConvention::from_byte(buf[0])?;+    if buf[1] != 0 || u16::from_le_bytes([buf[2], buf[3]]) != 0 {+        return err("a .mamaps carriageway table has non-zero reserved bytes");+    }+    let count = u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]) as usize;+    if count > layers.len() {+        return err(format!(+            "a .mamaps carriageway table has {count} entries for a body with {} layer(s)",+            layers.len(),+        ));+    }+    let mut at = 8usize;+    let mut table = Vec::with_capacity(count);+    let mut previous: Option<u8> = None;+    for _ in 0..count {+        if at + 8 > buf.len() {+            return err("a .mamaps carriageway table ends inside an entry header");+        }+        let layer_id = buf[at];+        if buf[at + 1] != 0 || u16::from_le_bytes([buf[at + 2], buf[at + 3]]) != 0 {+            return err("a .mamaps carriageway table entry has non-zero reserved bytes");+        }+        let feat_len =+            u32::from_le_bytes([buf[at + 4], buf[at + 5], buf[at + 6], buf[at + 7]]) as usize;+        at += 8;+        if previous.is_some_and(|p| layer_id <= p) {+            return err("a .mamaps carriageway table's entries are not ordered by layer id");+        }+        previous = Some(layer_id);+        let Some(layer) = layers.iter().find(|l| l.layer_id == layer_id) else {+            return err(format!(+                "a .mamaps carriageway table names layer {layer_id}, which the body does not carry"+            ));+        };+        if feat_len != layer.features.len() {+            return err(format!(+                "a .mamaps carriageway table gives layer {layer_id} {feat_len} record(s) for {} \+                 feature(s)",+                layer.features.len(),+            ));+        }+        // Bounded against the slice before allocating, so a corrupt count cannot ask for a+        // gigabyte of `Vec` — the same discipline `parse_lanes` and `parse_layer` apply.+        let bytes = feat_len.checked_mul(CARRIAGEWAY_RECORD_LEN).ok_or_else(|| {+            crate::proto::Error("a .mamaps carriageway table overflows".to_string())+        })?;+        if at + bytes > buf.len() {+            return err("a .mamaps carriageway table's records run past the table");+        }+        let mut rows = Vec::with_capacity(feat_len);+        for _ in 0..feat_len {+            rows.push(Carriageway {+                forward: buf[at],+                backward: buf[at + 1],+                solid_dividers: u32::from_le_bytes([+                    buf[at + 2],+                    buf[at + 3],+                    buf[at + 4],+                    buf[at + 5],+                ]),+            });+            at += CARRIAGEWAY_RECORD_LEN;+        }+        table.push((layer_id, rows));+    }+    let aligned = align4(at);+    if aligned > buf.len() {+        return err("a .mamaps carriageway table's padding runs past the body");+    }+    Ok((table, convention, aligned))+}++/// Serialise a carriageway table, 4-byte aligned. The inverse of [`parse_carriageways`].+pub fn serialize_carriageways(+    carriageways: &[(u8, Vec<Carriageway>)],+    convention: MarkingConvention,+    out: &mut Vec<u8>,+) {+    out.push(convention.to_byte());+    out.extend_from_slice(&[0u8; 3]);+    out.extend_from_slice(&(carriageways.len() as u32).to_le_bytes());+    for (layer_id, entries) in carriageways {+        out.push(*layer_id);+        out.extend_from_slice(&[0u8; 3]);+        out.extend_from_slice(&(entries.len() as u32).to_le_bytes());+        for row in entries {+            out.push(row.forward);+            out.push(row.backward);+            out.extend_from_slice(&row.solid_dividers.to_le_bytes());+        }+    }+    while out.len() % 4 != 0 {+        out.push(0);+    }+}++/// Parse the per-tile heightmap: a `u16` grid side length `dim`, then `dim * dim` `u16` samples,+/// row-major. Returns the grid and the bytes consumed (including 4-byte alignment padding).+///+/// A zero `dim` is refused rather than read as an empty grid: an elevation-free tile omits the+/// section (the flag is clear) instead of writing a degenerate one, so a zero here is corruption.+pub(crate) fn parse_heightmap(buf: &[u8]) -> Result<(Heightmap, usize)> {+    if buf.len() < 2 {+        return err("a .mamaps heightmap ends before its dimension");+    }+    let dim = u16::from_le_bytes([buf[0], buf[1]]);+    if dim == 0 {+        return err("a .mamaps heightmap has a zero dimension");+    }+    let cells = dim as usize * dim as usize;+    let bytes = cells+        .checked_mul(2)+        .ok_or_else(|| crate::proto::Error("a .mamaps heightmap's grid overflows".to_string()))?;+    let mut at = 2usize;+    if at + bytes > buf.len() {+        return err("a .mamaps heightmap's samples run past the body");+    }+    let mut samples = Vec::with_capacity(cells);+    for i in 0..cells {+        let o = at + i * 2;+        samples.push(u16::from_le_bytes([buf[o], buf[o + 1]]));+    }+    at += bytes;+    let aligned = align4(at);+    if aligned > buf.len() {+        return err("a .mamaps heightmap's padding runs past the body");+    }+    Ok((Heightmap { dim, samples }, aligned))+}++/// Serialise a per-tile heightmap, 4-byte aligned. The inverse of [`parse_heightmap`].+pub fn serialize_heightmap(grid: &Heightmap, out: &mut Vec<u8>) {+    out.extend_from_slice(&grid.dim.to_le_bytes());+    for &s in &grid.samples {+        out.extend_from_slice(&s.to_le_bytes());+    }+    while out.len() % 4 != 0 {+        out.push(0);+    }+}++/// The MED (LOCO-I) prediction for sample `(r, c)` of a `d x d` grid from already-known+/// neighbours: left, up and up-left. First row predicts from the left, first column from above,+/// the first sample from sea level (32768). Shared by the encoder and the decoder so they agree.+#[inline]+fn med_predict(s: &[u16], d: usize, r: usize, c: usize) -> u16 {+    if r == 0 && c == 0 {+        return 32768;+    }+    if r == 0 {+        return s[c - 1];+    }+    if c == 0 {+        return s[(r - 1) * d];+    }+    let (l, u, ul) =+        (s[r * d + c - 1] as i32, s[(r - 1) * d + c] as i32, s[(r - 1) * d + c - 1] as i32);+    let (lo, hi) = (l.min(u), l.max(u));+    let p = if ul >= hi {+        lo+    } else if ul <= lo {+        hi+    } else {+        l + u - ul+    };+    p as u16+}++/// Serialise a heightmap as v11 MED residuals: the same `dim` + `dim*dim` u16 layout as+/// [`serialize_heightmap`], each sample replaced by `zigzag((sample - prediction) mod 2^16)`.+/// Flat or smoothly sloping ground becomes runs of tiny values, which is what zstd needs.+pub fn serialize_heightmap_residual(grid: &Heightmap, out: &mut Vec<u8>) {+    let d = grid.dim as usize;+    out.extend_from_slice(&grid.dim.to_le_bytes());+    for r in 0..d {+        for c in 0..d {+            let v = grid.samples[r * d + c];+            let e = v.wrapping_sub(med_predict(&grid.samples, d, r, c)) as i16;+            let zz = ((e << 1) ^ (e >> 15)) as u16;+            out.extend_from_slice(&zz.to_le_bytes());+        }+    }+    while out.len() % 4 != 0 {+        out.push(0);+    }+}++/// Undo [`serialize_heightmap_residual`] in place, in raster order so every prediction reads+/// samples already reconstructed.+pub(crate) fn unresidual_heightmap(grid: &mut Heightmap) {+    let d = grid.dim as usize;+    for r in 0..d {+        for c in 0..d {+            let zz = grid.samples[r * d + c];+            let e = ((zz >> 1) as i16) ^ -((zz & 1) as i16);+            let p = med_predict(&grid.samples, d, r, c);+            grid.samples[r * d + c] = p.wrapping_add(e as u16);+        }+    }+}
library/tilecodec/src/main/rust/src/mamaps/body/tests.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/tests.rs b/library/tilecodec/src/main/rust/src/mamaps/body/tests.rsindex 705dcc6568..75c97ed607 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/tests.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/tests.rs@@ -412,142 +412,4 @@ fn a_body_carrying_two_layers_with_one_id_is_refused() {     assert!(serialize(&body).is_err()); } -/// A corrupt body must fail here, not by indexing past a slice or allocating on a count it-/// read out of the same corrupt bytes.-#[test]-fn a_corrupt_body_is_refused_rather_than_decoded() {-    let good = serialize(&sample()).expect("serialize");-    assert!(Body::parse(&good[..BODY_HEADER_LEN - 1]).is_err(), "shorter than the header");-    assert!(Body::parse(&good[..good.len() - 4]).is_err(), "declares more than it is");--    let cases: &[(&str, BodyMutator)] = &[-        ("bad magic", |b| b[0] = b'X'),-        ("a newer body version", |b| b[3] = 99),-        ("a zero extent", |b| b[8..10].copy_from_slice(&0u16.to_le_bytes())),-        ("a dirty reserved word", |b| b[12] = 1),-        ("a layer count past the index", |b| b[10] = 200),-        ("a layer payload outside the body", |b| {-            b[20..24].copy_from_slice(&999_999u32.to_le_bytes())-        }),-        ("a layer payload starting inside the index", |b| {-            b[20..24].copy_from_slice(&0u32.to_le_bytes())-        }),-    ];-    for (what, break_it) in cases {-        let mut bytes = good.clone();-        break_it(&mut bytes);-        assert!(Body::parse(&bytes).is_err(), "{what} should be refused");-    }-}--/// Geometry type is validated on parse, and points genuinely round-trip (`places` and `poi`-/// labels are the only features that carry them).-#[test]-fn an_unknown_geometry_type_is_refused_but_points_round_trip() {-    let mut bytes = serialize(&sample()).expect("serialize");-    // The first layer's first feature record: water, at the aligned payload start.-    let at = align4(BODY_HEADER_LEN + 2 * LAYER_INDEX_LEN);-    bytes[at + 4] = 0;-    assert!(Body::parse(&bytes).is_err(), "geometry type 0");-    bytes[at + 4] = 7;-    assert!(Body::parse(&bytes).is_err(), "an unknown geometry type");-    bytes[at + 4] = GEOM_POLYGON;-    assert!(Body::parse(&bytes).is_ok(), "and the sample is otherwise fine");--    // A point genuinely round-trips: one feature, one single-point part, and a name.-    let mut poi = Layer::new(dict::LAYER_POI);-    poi.features.push(Feature {-        kind: 1,-        kind_detail: dict::NONE,-        geom_type: GEOM_POINT,-        flags: 0,-        name_idx: 1,-        parts_offset: 0,-        part_count: 1,-        transit_color: 0,-        transit_ordinal: 0,-        transit_lanes: 0,-        transit_taper: 0,-        lane_count: 0,-    });-    poi.parts.push(Part { coord_start: 0, point_count: 1, winding: WINDING_OUTER });-    poi.coords = vec![(100, 200)];-    let body = Body {-        extent: DEFAULT_EXTENT,-        layers: vec![poi],-        names: vec!["Cafe".to_string()],-        ids: Vec::new(),-        turn_lanes: Vec::new(),-        buildings: Vec::new(),-        heightmap: None,-        carriageways: Vec::new(),-        convention: None,-        region_links: Vec::new(),-    };-    let parsed = Body::parse(&serialize(&body).expect("serialize")).expect("parse");-    assert_eq!(parsed, body);-    let feature = &parsed.layer(dict::LAYER_POI).expect("poi").features[0];-    assert_eq!(feature.name(&parsed), Some("Cafe"));-}--/// v1 is gone. A body carrying that version byte is a body from an archive this reader no-/// longer speaks, and reading it with 24-byte records would silently misparse every field.-#[test]-fn a_v1_body_is_refused_outright() {-    let mut bytes = serialize(&sample()).expect("serialize");-    bytes[3] = 1;-    assert!(Body::parse(&bytes).is_err(), "a v1 body version");-    bytes[3] = 2;-    assert!(Body::parse(&bytes).is_err(), "a v2 body version");-    bytes[3] = crate::mamaps::header::FORMAT_VERSION;-    assert!(Body::parse(&bytes).is_ok(), "and v3 is otherwise fine");-}--/// The id table is parallel to a layer's features and survives a round trip alongside the-/// name table, which is the case that matters: `poi` carries both.-#[test]-fn the_id_table_round_trips_beside_the_name_table() {-    let mut poi = Layer::new(dict::LAYER_POI);-    for name_idx in 1..=2u16 {-        poi.features.push(Feature {-            kind: 1,-            kind_detail: dict::NONE,-            geom_type: GEOM_POINT,-            flags: 0,-            name_idx,-            parts_offset: u32::from(name_idx) - 1,-            part_count: 1,-            transit_color: 0,-            transit_ordinal: 0,-            transit_lanes: 0,-            transit_taper: 0,-            lane_count: 0,-        });-        poi.parts.push(Part {-            coord_start: u32::from(name_idx) - 1,-            point_count: 1,-            winding: WINDING_OUTER,-        });-    }-    poi.coords = vec![(10, 20), (30, 40)];-    let body = Body {-        extent: DEFAULT_EXTENT,-        layers: vec![poi],-        names: vec!["Cafe".to_string(), "Bar".to_string()],-        // A real OSM id and ID_NONE for a feature the generator could not attribute.-        ids: vec![(dict::LAYER_POI, vec![12_345_678_901, ID_NONE])],-        turn_lanes: Vec::new(),-        buildings: Vec::new(),-        heightmap: None,-        carriageways: Vec::new(),-        convention: None,-        region_links: Vec::new(),-    };-    let bytes = serialize(&body).expect("serialize");-    let parsed = Body::parse(&bytes).expect("parse");-    assert_eq!(parsed, body);-    assert_eq!(parsed.feature_id(dict::LAYER_POI, 0), Some(12_345_678_901));-    assert_eq!(parsed.feature_id(dict::LAYER_POI, 1), Some(ID_NONE));-    assert_eq!(parsed.feature_id(dict::LAYER_POI, 2), None, "past the table");-    assert_eq!(parsed.feature_id(dict::LAYER_ROADS, 0), None, "a layer with no ids");-}+include!("tests_s1.rs");
library/tilecodec/src/main/rust/src/mamaps/body/tests_extra.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/tests_extra.rs b/library/tilecodec/src/main/rust/src/mamaps/body/tests_extra.rsindex 48f16e310f..9dc2e4d970 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/tests_extra.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/tests_extra.rs@@ -389,160 +389,4 @@ fn serialising_the_same_body_twice_gives_the_same_bytes() {     assert_eq!(serialize(&sample()).expect("a"), serialize(&reordered).expect("b")); } -#[test]-fn a_layer_with_more_than_65535_features_round_trips_via_extended_encoding() {-    let mut layer = Layer::new(10);-    let n = 70000usize;-    for i in 0..n {-        layer.features.push(Feature {-            kind: 1,-            kind_detail: 0,-            geom_type: GEOM_LINE,-            flags: 0,-            name_idx: NAME_NONE,-            parts_offset: i as u32,-            part_count: 1,-            transit_color: 0,-            transit_ordinal: 0,-            transit_lanes: 0,-            transit_taper: 0,-            lane_count: 0,-        });-        layer.parts.push(Part {-            coord_start: (i * 2) as u32,-            point_count: 2,-            winding: WINDING_OUTER,-        });-        layer.coords.push((0, 0));-        layer.coords.push((1, 1));-    }-    let body = Body {-        extent: DEFAULT_EXTENT,-        layers: vec![layer],-        names: Vec::new(),-        ids: Vec::new(),-        turn_lanes: Vec::new(),-        buildings: Vec::new(),-        heightmap: None,-        carriageways: Vec::new(),-        convention: None,-        region_links: Vec::new(),-    };-    let bytes = serialize(&body).expect("extended tile must serialize");-    assert_eq!(bytes[11], BODY_FLAG_EXTENDED_COUNTS, "extended flag set");-    let parsed = Body::parse(&bytes).expect("must parse extended");-    assert_eq!(parsed.layers[0].features.len(), n);-    assert_eq!(parsed.layers[0].parts.len(), n);-    // Non-extended path stays byte-identical for common case.-    let small_body = Body {-        extent: DEFAULT_EXTENT,-        layers: vec![{-            let mut l = Layer::new(10);-            l.features.push(Feature {-                kind: 1,-                kind_detail: 0,-                geom_type: GEOM_LINE,-                flags: 0,-                name_idx: NAME_NONE,-                parts_offset: 0,-                part_count: 1,-                transit_color: 0,-                transit_ordinal: 0,-                transit_lanes: 0,-                transit_taper: 0,-                lane_count: 0,-            });-            l.parts.push(Part { coord_start: 0, point_count: 2, winding: WINDING_OUTER });-            l.coords.extend_from_slice(&[(0, 0), (1, 1)]);-            l-        }],-        names: Vec::new(),-        ids: Vec::new(),-        turn_lanes: Vec::new(),-        buildings: Vec::new(),-        heightmap: None,-        carriageways: Vec::new(),-        convention: None,-        region_links: Vec::new(),-    };-    let small_bytes = serialize(&small_body).expect("small tile");-    assert_eq!(small_bytes[11], 0, "common path no flag, byte-identical");-    assert_eq!(small_bytes[12..16], [0, 0, 0, 0], "reserved still zero for common path");-}--/// The S3DB building table rides beside the name and id tables, dense-parallel to the-/// `buildings` layer's features: a tagged building carries its height, roof and colours, a-/// plain one a default record, and both survive the round trip. This is the wire half of the-/// 3D building extrusion.-#[test]-fn the_building_table_round_trips_dense_parallel_to_features() {-    let mut buildings = Layer::new(dict::LAYER_BUILDINGS);-    for i in 0..3u32 {-        buildings.features.push(Feature {-            kind: 51,-            kind_detail: 0,-            geom_type: GEOM_POLYGON,-            flags: 0,-            name_idx: NAME_NONE,-            parts_offset: i,-            part_count: 1,-            transit_color: 0,-            transit_ordinal: 0,-            transit_lanes: 0,-            transit_taper: 0,-            lane_count: 0,-        });-        buildings.parts.push(Part { coord_start: i * 4, point_count: 4, winding: WINDING_OUTER });-        let b = i as i16;-        buildings.coords.extend_from_slice(&[(0, b), (10, b), (10, b + 10), (0, b + 10)]);-    }-    // A tall gabled tower with colours, a floating glass part, and a plain default building.-    let attrs = vec![-        BuildingAttrs {-            height: 1200,-            min_height: 0,-            roof_height: 300,-            roof_shape: ROOF_GABLED,-            roof_direction: 64,-            roof_orientation: ROOF_ORIENT_ACROSS,-            building_colour: 0xFF_C8_A0_78,-            roof_colour: 0xFF_80_20_20,-        },-        BuildingAttrs {-            height: 400,-            min_height: 250,-            roof_height: 0,-            roof_shape: ROOF_FLAT,-            roof_direction: 0,-            roof_orientation: ROOF_ORIENT_ALONG,-            building_colour: 0,-            roof_colour: 0,-        },-        BuildingAttrs::default(),-    ];-    let body = Body {-        extent: DEFAULT_EXTENT,-        layers: vec![buildings],-        names: Vec::new(),-        ids: Vec::new(),-        turn_lanes: Vec::new(),-        buildings: vec![(dict::LAYER_BUILDINGS, attrs.clone())],-        heightmap: None,-        carriageways: Vec::new(),-        convention: None,-        region_links: Vec::new(),-    };-    let bytes = serialize(&body).expect("serialize");-    // The body carries the reader's own version byte, so an older reader rejects it cleanly.-    // Asserted against the constant rather than a literal: this test is about the building-    // table, and pinning the number here made every later format bump fail here first.-    assert_eq!(bytes[3], crate::mamaps::header::FORMAT_VERSION, "the body's format version");-    assert_ne!(bytes[11] & BODY_FLAG_BUILDING_TABLE, 0, "the building flag is set");-    let parsed = Body::parse(&bytes).expect("parse");-    assert_eq!(parsed, body);-    assert_eq!(parsed.building_attrs(dict::LAYER_BUILDINGS, 0), Some(attrs[0]));-    assert_eq!(parsed.building_attrs(dict::LAYER_BUILDINGS, 1), Some(attrs[1]));-    assert_eq!(parsed.building_attrs(dict::LAYER_BUILDINGS, 2), Some(BuildingAttrs::default()),);-    assert_eq!(parsed.building_attrs(dict::LAYER_BUILDINGS, 3), None, "past the table");-    assert_eq!(parsed.building_attrs(dict::LAYER_ROADS, 0), None, "a layer with no table");-}+include!("tests_extra_s1.rs");
library/tilecodec/src/main/rust/src/mamaps/body/tests_extra_s1.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/tests_extra_s1.rs b/library/tilecodec/src/main/rust/src/mamaps/body/tests_extra_s1.rsnew file mode 100644index 0000000000..3affe06145--- /dev/null+++ b/library/tilecodec/src/main/rust/src/mamaps/body/tests_extra_s1.rs@@ -0,0 +1,157 @@+#[test]+fn a_layer_with_more_than_65535_features_round_trips_via_extended_encoding() {+    let mut layer = Layer::new(10);+    let n = 70000usize;+    for i in 0..n {+        layer.features.push(Feature {+            kind: 1,+            kind_detail: 0,+            geom_type: GEOM_LINE,+            flags: 0,+            name_idx: NAME_NONE,+            parts_offset: i as u32,+            part_count: 1,+            transit_color: 0,+            transit_ordinal: 0,+            transit_lanes: 0,+            transit_taper: 0,+            lane_count: 0,+        });+        layer.parts.push(Part {+            coord_start: (i * 2) as u32,+            point_count: 2,+            winding: WINDING_OUTER,+        });+        layer.coords.push((0, 0));+        layer.coords.push((1, 1));+    }+    let body = Body {+        extent: DEFAULT_EXTENT,+        layers: vec![layer],+        names: Vec::new(),+        ids: Vec::new(),+        turn_lanes: Vec::new(),+        buildings: Vec::new(),+        heightmap: None,+        carriageways: Vec::new(),+        convention: None,+        region_links: Vec::new(),+    };+    let bytes = serialize(&body).expect("extended tile must serialize");+    assert_eq!(bytes[11], BODY_FLAG_EXTENDED_COUNTS, "extended flag set");+    let parsed = Body::parse(&bytes).expect("must parse extended");+    assert_eq!(parsed.layers[0].features.len(), n);+    assert_eq!(parsed.layers[0].parts.len(), n);+    // Non-extended path stays byte-identical for common case.+    let small_body = Body {+        extent: DEFAULT_EXTENT,+        layers: vec![{+            let mut l = Layer::new(10);+            l.features.push(Feature {+                kind: 1,+                kind_detail: 0,+                geom_type: GEOM_LINE,+                flags: 0,+                name_idx: NAME_NONE,+                parts_offset: 0,+                part_count: 1,+                transit_color: 0,+                transit_ordinal: 0,+                transit_lanes: 0,+                transit_taper: 0,+                lane_count: 0,+            });+            l.parts.push(Part { coord_start: 0, point_count: 2, winding: WINDING_OUTER });+            l.coords.extend_from_slice(&[(0, 0), (1, 1)]);+            l+        }],+        names: Vec::new(),+        ids: Vec::new(),+        turn_lanes: Vec::new(),+        buildings: Vec::new(),+        heightmap: None,+        carriageways: Vec::new(),+        convention: None,+        region_links: Vec::new(),+    };+    let small_bytes = serialize(&small_body).expect("small tile");+    assert_eq!(small_bytes[11], 0, "common path no flag, byte-identical");+    assert_eq!(small_bytes[12..16], [0, 0, 0, 0], "reserved still zero for common path");+}++/// The S3DB building table rides beside the name and id tables, dense-parallel to the+/// `buildings` layer's features: a tagged building carries its height, roof and colours, a+/// plain one a default record, and both survive the round trip. This is the wire half of the+/// 3D building extrusion.+#[test]+fn the_building_table_round_trips_dense_parallel_to_features() {+    let mut buildings = Layer::new(dict::LAYER_BUILDINGS);+    for i in 0..3u32 {+        buildings.features.push(Feature {+            kind: 51,+            kind_detail: 0,+            geom_type: GEOM_POLYGON,+            flags: 0,+            name_idx: NAME_NONE,+            parts_offset: i,+            part_count: 1,+            transit_color: 0,+            transit_ordinal: 0,+            transit_lanes: 0,+            transit_taper: 0,+            lane_count: 0,+        });+        buildings.parts.push(Part { coord_start: i * 4, point_count: 4, winding: WINDING_OUTER });+        let b = i as i16;+        buildings.coords.extend_from_slice(&[(0, b), (10, b), (10, b + 10), (0, b + 10)]);+    }+    // A tall gabled tower with colours, a floating glass part, and a plain default building.+    let attrs = vec![+        BuildingAttrs {+            height: 1200,+            min_height: 0,+            roof_height: 300,+            roof_shape: ROOF_GABLED,+            roof_direction: 64,+            roof_orientation: ROOF_ORIENT_ACROSS,+            building_colour: 0xFF_C8_A0_78,+            roof_colour: 0xFF_80_20_20,+        },+        BuildingAttrs {+            height: 400,+            min_height: 250,+            roof_height: 0,+            roof_shape: ROOF_FLAT,+            roof_direction: 0,+            roof_orientation: ROOF_ORIENT_ALONG,+            building_colour: 0,+            roof_colour: 0,+        },+        BuildingAttrs::default(),+    ];+    let body = Body {+        extent: DEFAULT_EXTENT,+        layers: vec![buildings],+        names: Vec::new(),+        ids: Vec::new(),+        turn_lanes: Vec::new(),+        buildings: vec![(dict::LAYER_BUILDINGS, attrs.clone())],+        heightmap: None,+        carriageways: Vec::new(),+        convention: None,+        region_links: Vec::new(),+    };+    let bytes = serialize(&body).expect("serialize");+    // The body carries the reader's own version byte, so an older reader rejects it cleanly.+    // Asserted against the constant rather than a literal: this test is about the building+    // table, and pinning the number here made every later format bump fail here first.+    assert_eq!(bytes[3], crate::mamaps::header::FORMAT_VERSION, "the body's format version");+    assert_ne!(bytes[11] & BODY_FLAG_BUILDING_TABLE, 0, "the building flag is set");+    let parsed = Body::parse(&bytes).expect("parse");+    assert_eq!(parsed, body);+    assert_eq!(parsed.building_attrs(dict::LAYER_BUILDINGS, 0), Some(attrs[0]));+    assert_eq!(parsed.building_attrs(dict::LAYER_BUILDINGS, 1), Some(attrs[1]));+    assert_eq!(parsed.building_attrs(dict::LAYER_BUILDINGS, 2), Some(BuildingAttrs::default()),);+    assert_eq!(parsed.building_attrs(dict::LAYER_BUILDINGS, 3), None, "past the table");+    assert_eq!(parsed.building_attrs(dict::LAYER_ROADS, 0), None, "a layer with no table");+}
library/tilecodec/src/main/rust/src/mamaps/body/tests_s1.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/tests_s1.rs b/library/tilecodec/src/main/rust/src/mamaps/body/tests_s1.rsnew file mode 100644index 0000000000..14ed6683f2--- /dev/null+++ b/library/tilecodec/src/main/rust/src/mamaps/body/tests_s1.rs@@ -0,0 +1,139 @@+/// A corrupt body must fail here, not by indexing past a slice or allocating on a count it+/// read out of the same corrupt bytes.+#[test]+fn a_corrupt_body_is_refused_rather_than_decoded() {+    let good = serialize(&sample()).expect("serialize");+    assert!(Body::parse(&good[..BODY_HEADER_LEN - 1]).is_err(), "shorter than the header");+    assert!(Body::parse(&good[..good.len() - 4]).is_err(), "declares more than it is");++    let cases: &[(&str, BodyMutator)] = &[+        ("bad magic", |b| b[0] = b'X'),+        ("a newer body version", |b| b[3] = 99),+        ("a zero extent", |b| b[8..10].copy_from_slice(&0u16.to_le_bytes())),+        ("a dirty reserved word", |b| b[12] = 1),+        ("a layer count past the index", |b| b[10] = 200),+        ("a layer payload outside the body", |b| {+            b[20..24].copy_from_slice(&999_999u32.to_le_bytes())+        }),+        ("a layer payload starting inside the index", |b| {+            b[20..24].copy_from_slice(&0u32.to_le_bytes())+        }),+    ];+    for (what, break_it) in cases {+        let mut bytes = good.clone();+        break_it(&mut bytes);+        assert!(Body::parse(&bytes).is_err(), "{what} should be refused");+    }+}++/// Geometry type is validated on parse, and points genuinely round-trip (`places` and `poi`+/// labels are the only features that carry them).+#[test]+fn an_unknown_geometry_type_is_refused_but_points_round_trip() {+    let mut bytes = serialize(&sample()).expect("serialize");+    // The first layer's first feature record: water, at the aligned payload start.+    let at = align4(BODY_HEADER_LEN + 2 * LAYER_INDEX_LEN);+    bytes[at + 4] = 0;+    assert!(Body::parse(&bytes).is_err(), "geometry type 0");+    bytes[at + 4] = 7;+    assert!(Body::parse(&bytes).is_err(), "an unknown geometry type");+    bytes[at + 4] = GEOM_POLYGON;+    assert!(Body::parse(&bytes).is_ok(), "and the sample is otherwise fine");++    // A point genuinely round-trips: one feature, one single-point part, and a name.+    let mut poi = Layer::new(dict::LAYER_POI);+    poi.features.push(Feature {+        kind: 1,+        kind_detail: dict::NONE,+        geom_type: GEOM_POINT,+        flags: 0,+        name_idx: 1,+        parts_offset: 0,+        part_count: 1,+        transit_color: 0,+        transit_ordinal: 0,+        transit_lanes: 0,+        transit_taper: 0,+        lane_count: 0,+    });+    poi.parts.push(Part { coord_start: 0, point_count: 1, winding: WINDING_OUTER });+    poi.coords = vec![(100, 200)];+    let body = Body {+        extent: DEFAULT_EXTENT,+        layers: vec![poi],+        names: vec!["Cafe".to_string()],+        ids: Vec::new(),+        turn_lanes: Vec::new(),+        buildings: Vec::new(),+        heightmap: None,+        carriageways: Vec::new(),+        convention: None,+        region_links: Vec::new(),+    };+    let parsed = Body::parse(&serialize(&body).expect("serialize")).expect("parse");+    assert_eq!(parsed, body);+    let feature = &parsed.layer(dict::LAYER_POI).expect("poi").features[0];+    assert_eq!(feature.name(&parsed), Some("Cafe"));+}++/// v1 is gone. A body carrying that version byte is a body from an archive this reader no+/// longer speaks, and reading it with 24-byte records would silently misparse every field.+#[test]+fn a_v1_body_is_refused_outright() {+    let mut bytes = serialize(&sample()).expect("serialize");+    bytes[3] = 1;+    assert!(Body::parse(&bytes).is_err(), "a v1 body version");+    bytes[3] = 2;+    assert!(Body::parse(&bytes).is_err(), "a v2 body version");+    bytes[3] = crate::mamaps::header::FORMAT_VERSION;+    assert!(Body::parse(&bytes).is_ok(), "and v3 is otherwise fine");+}++/// The id table is parallel to a layer's features and survives a round trip alongside the+/// name table, which is the case that matters: `poi` carries both.+#[test]+fn the_id_table_round_trips_beside_the_name_table() {+    let mut poi = Layer::new(dict::LAYER_POI);+    for name_idx in 1..=2u16 {+        poi.features.push(Feature {+            kind: 1,+            kind_detail: dict::NONE,+            geom_type: GEOM_POINT,+            flags: 0,+            name_idx,+            parts_offset: u32::from(name_idx) - 1,+            part_count: 1,+            transit_color: 0,+            transit_ordinal: 0,+            transit_lanes: 0,+            transit_taper: 0,+            lane_count: 0,+        });+        poi.parts.push(Part {+            coord_start: u32::from(name_idx) - 1,+            point_count: 1,+            winding: WINDING_OUTER,+        });+    }+    poi.coords = vec![(10, 20), (30, 40)];+    let body = Body {+        extent: DEFAULT_EXTENT,+        layers: vec![poi],+        names: vec!["Cafe".to_string(), "Bar".to_string()],+        // A real OSM id and ID_NONE for a feature the generator could not attribute.+        ids: vec![(dict::LAYER_POI, vec![12_345_678_901, ID_NONE])],+        turn_lanes: Vec::new(),+        buildings: Vec::new(),+        heightmap: None,+        carriageways: Vec::new(),+        convention: None,+        region_links: Vec::new(),+    };+    let bytes = serialize(&body).expect("serialize");+    let parsed = Body::parse(&bytes).expect("parse");+    assert_eq!(parsed, body);+    assert_eq!(parsed.feature_id(dict::LAYER_POI, 0), Some(12_345_678_901));+    assert_eq!(parsed.feature_id(dict::LAYER_POI, 1), Some(ID_NONE));+    assert_eq!(parsed.feature_id(dict::LAYER_POI, 2), None, "past the table");+    assert_eq!(parsed.feature_id(dict::LAYER_ROADS, 0), None, "a layer with no ids");+}
library/tilecodec/src/main/rust/src/mamaps/read/archive.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/read/archive.rs b/library/tilecodec/src/main/rust/src/mamaps/read/archive.rsindex 00a986e44a..db45f3ecb6 100644--- a/library/tilecodec/src/main/rust/src/mamaps/read/archive.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/read/archive.rs@@ -45,493 +45,4 @@ enum TileAddress {     Cold { root: RootEntry, offset: u32 }, } -impl<R: RangeReader> MamapsArchive<R> {-    /// The archive's trained dictionaries, when its bodies use them (planet5).-    pub fn zdicts(&self) -> Option<&crate::mamaps::zdict::ZDicts> {-        self.zdicts.as_deref()-    }--    /// The reader this archive was opened on.-    ///-    /// So a caller can act on something it only learns from the header — the `build_id`, which-    /// decides whether the reader's disk cache is still addressing this build.-    pub fn reader(&self) -> &R {-        &self.reader-    }-    /// One range request: the header, the dictionary and the root index all live in the prefix.-    ///-    /// A file whose prefix does not hold all three is refused rather than fetched again. The-    /// writer asserts the budget, so a file that misses it was not written by this codec, and-    /// silently paying an extra round trip per open is exactly the cost the layout exists to-    /// avoid.-    ///-    /// The archive gets a private leaf cache. Readers that should share one —-    /// a surface's tile workers — want-    /// [`open_with_cache`](MamapsArchive::open_with_cache) instead.-    pub fn open(reader: R) -> Result<MamapsArchive<R>> {-        Self::open_with_cache(reader, Arc::new(LeafCache::new()))-    }--    /// [`open`](MamapsArchive::open) over a caller-supplied leaf cache.-    ///-    /// Every archive opened over the same [`LeafCache`] shares parsed leaves:-    /// the first worker to need a cold leaf fetches, inflates and parses it,-    /// and the rest take the cached copy. Thread-safe — `tile` and-    /// `tile_bytes` take `&self` — so one cache serves a whole surface.-    pub fn open_with_cache(reader: R, leaves: Arc<LeafCache>) -> Result<MamapsArchive<R>> {-        let prefix = reader.read(0, OPEN_PREFIX_BYTES)?;-        let header = Header::parse(&prefix)?;-        let section = |offset: u64, len: u64, what: &str| -> Result<&[u8]> {-            let end = offset + len;-            if end > prefix.len() as u64 {-                return err(format!(-                    "{what} ends at byte {end}, outside the {OPEN_PREFIX_BYTES} byte prefix a \-                     .mamaps open reads -- this archive was not written by this codec",-                ));-            }-            Ok(&prefix[offset as usize..end as usize])-        };-        let dictionary = Dictionary::parse(section(-            header.dict_offset,-            header.dict_len as u64,-            "the dictionary",-        )?)?;-        dictionary.check_matches_schema()?;-        if dictionary.layers.len() != header.layer_count as usize {-            return err("a .mamaps header and dictionary disagree on the layer count");-        }-        let root = index::parse_root(section(-            header.root_offset,-            header.root_len as u64,-            "the root index",-        )?)?;-        if root.len() != header.leaf_count as usize {-            return err(format!(-                "a .mamaps header declares {} leaves but its root has {} entries",-                header.leaf_count,-                root.len(),-            ));-        }-        // Planet5: one more read on open for the dictionaries, never one per tile.-        let zdicts = if header.compression == crate::mamaps::header::COMPRESSION_ZSTD_DICT {-            let (start, end) = zdict_extent(&header)?;-            let bytes = if end <= prefix.len() as u64 {-                prefix[start as usize..end as usize].to_vec()-            } else {-                reader.read(start, (end - start) as u32)?-            };-            if bytes.len() as u64 != end - start {-                return err("a .mamaps dictionary section was cut short");-            }-            Some(Arc::new(crate::mamaps::zdict::ZDicts::parse(&bytes)?))-        } else {-            None-        };-        Ok(MamapsArchive { reader, header, dictionary, root, leaves, zdicts })-    }--    /// The decoded body for a tile, or `None` when the archive does not hold it.-    ///-    /// `None` rather than an error: most of a coastal viewport is off the edge of coverage, and-    /// that is the ordinary answer rather than a fault.-    /// Decompress a stored frame for `tile_id`: a body as is, or -- for a superblock (header-    /// v11) -- the tile's member body, the decompressed block kept in the shared cache so its-    /// other members cost no decompress.-    fn decode_stored(&self, abs_offset: u64, stored: &[u8], tile_id: u64) -> Result<Vec<u8>> {-        let raw = decompress_with(self.header.compression, stored, self.zdicts.as_deref())?;-        if crate::mamaps::superblock::is_superblock(&raw) {-            let raw = Arc::new(raw);-            let body = crate::mamaps::superblock::resolve(raw.as_ref().clone(), tile_id);-            crate::mamaps::superblock::shared_cache().put(self.header.build_id, abs_offset, raw);-            return body;-        }-        Ok(raw)-    }--    /// The member body of `tile_id` from an already-cached superblock at `abs_offset`.-    fn cached_member(&self, abs_offset: u64, tile_id: u64) -> Option<Result<Vec<u8>>> {-        if self.header.flags & crate::mamaps::header::FLAG_SUPERBLOCKS == 0 {-            return None;-        }-        let sb = crate::mamaps::superblock::shared_cache().get(self.header.build_id, abs_offset)?;-        Some(match crate::mamaps::superblock::member(&sb, tile_id) {-            Ok(Some(b)) => Ok(b.to_vec()),-            Ok(None) => err(format!(-                "tile {tile_id} is not a member of the superblock its leaf entry addresses"-            )),-            Err(e) => Err(e),-        })-    }--    pub fn tile(&self, z: u8, x: u32, y: u32) -> Result<Option<Body>> {-        let Some(bytes) = self.tile_bytes(z, x, y)? else { return Ok(None) };-        Ok(Some(Body::parse(&bytes)?))-    }--    /// The decoded bodies for many tiles at once, in request order with one slot per tile.-    ///-    /// The cold path (`tile_bytes`) costs one range read for a cached leaf and two for a cold-    /// one — and the second cannot start until the first lands, so serving tiles one at a time-    /// serialises every tile behind every other on a high-latency radio. Batching overlaps the-    /// latency instead: every cold leaf the batch needs is fetched concurrently first (one-    /// request per distinct leaf, p

Diff truncated.