Modern Apps git

← Modern-Apps.git

library:map: a .mamaps codec, shaped like what the renderer draws

Commit
769230753332b92c70230ca654208b8e1160e18f
Author
vayun-mathur <[email protected]>
When
2026-08-28 00:03 UTC (3 months ago)
Parents
b30c701

Diff

library/tilecodec/src/main/rust/Cargo.toml
diff --git a/library/tilecodec/src/main/rust/Cargo.toml b/library/tilecodec/src/main/rust/Cargo.tomlindex 33b99f3828..4185aeb4d6 100644--- a/library/tilecodec/src/main/rust/Cargo.toml+++ b/library/tilecodec/src/main/rust/Cargo.toml@@ -1,4 +1,4 @@-# The PMTiles v3 and MVT 2.1 codec, shared by the offline tiler and the app.+# The PMTiles v3, MVT 2.1 and `.mamaps` codecs, shared by the offline tiler and the app. # # Extracted from `scripts/maps/tile_build`, which is still its older consumer. # The Android vector renderer in `:library:map` needs to read exactly the archives@@ -14,6 +14,12 @@ # host and cross-compiles for Android with no C toolchain and nothing to configure. # PMTiles gzips both its directories and its tiles, so the DEFLATE side is needed # as well as INFLATE.+#+# That single-pure-Rust-dependency rule is also what settled `.mamaps` compression.+# The obvious choice on paper is zstd, but its encoder is C, so adding it would end+# the property this whole file exists to preserve. `.mamaps` bodies are therefore raw+# DEFLATE through the same `miniz_oxide`, and the format's `compression` header byte+# keeps a swap open if a pure-Rust zstd encoder ever becomes worth the dependency.  [package] name = "tilecodec"@@ -21,7 +27,14 @@ version = "0.1.0" edition = "2021" publish = false license = "GPL-2.0-only"-description = "PMTiles v3 + Mapbox Vector Tile 2.1 codec shared by the Maps tiler and the Android renderer"+description = "PMTiles v3, Mapbox Vector Tile 2.1 and .mamaps codecs shared by the Maps tiler and the Android renderer"++[features]+# The `.mamaps` writer. Off by default: Android reads archives and never writes one,+# so gating it keeps the interner out of the cdylib and, more usefully, makes it a+# compile error rather than a review comment if the read path ever grows a dependency+# on the write path. `scripts/maps` enables it.+write = []  [lib] name = "tilecodec"
library/tilecodec/src/main/rust/src/lib.rs
diff --git a/library/tilecodec/src/main/rust/src/lib.rs b/library/tilecodec/src/main/rust/src/lib.rsindex 7e5de97a23..270f7659e2 100644--- a/library/tilecodec/src/main/rust/src/lib.rs+++ b/library/tilecodec/src/main/rust/src/lib.rs@@ -25,6 +25,12 @@ //!     for both its directories and its tiles. //!   * [`pmtiles`] — the v3 container, read and write, including Hilbert tile ids //!     and the root/leaf directory split.+//!   * [`mamaps`] — the container the Vulkan renderer reads: geometry only,+//!     pre-clipped, attributes interned to integers, flat little-endian structs.+//!     PMTiles and MVT are what the `maps` app still needs, because it renders+//!     through MapLibre; this is what everything else is moving to, and the two+//!     live side by side for the transition. Its writer is behind the `write`+//!     feature, so Android links only the read half. //! //! Nothing here allocates a thread, opens a socket or touches a GPU. The reader the //! app uses over HTTP range requests is [`stream`], which is built on top of@@ -32,6 +38,7 @@ //! to supply.  pub mod gz;+pub mod mamaps; pub mod mvt; pub mod pmtiles; pub mod proto;
library/tilecodec/src/main/rust/src/mamaps/body.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body.rs b/library/tilecodec/src/main/rust/src/mamaps/body.rsnew file mode 100644index 0000000000..04de4c100e--- /dev/null+++ b/library/tilecodec/src/main/rust/src/mamaps/body.rs@@ -0,0 +1,661 @@+//! One tile body: every layer's geometry, flat and renderer-shaped.+//!+//! # What is not here+//!+//! **Triangles.** Pre-tessellating would bake the style's layer set into the data, so a restyle+//! would mean a rebuild — and the whole point of splitting one data-driven layer into several is+//! that it is a *paint* decision.+//!+//! **Points.** The renderer decodes them and throws them away, so they are not carried. A+//! geometry type is line or polygon and nothing else.+//!+//! **A property map.** A feature's whole attribute surface is `kind`, `kind_detail` and three+//! bits, because that is all the style filters on. No per-tile string table, no keys, no values.+//!+//! # Why all layers share one body+//!+//! Splitting per layer would multiply a cold tile's range requests by seven, and the renderer+//! wants every style layer for one tile at once anyway. One body, one request.+//!+//! # Layout+//!+//! ```text+//! [BodyHeader 16][LayerIndex × n][per layer: FeatureRecord[] PartEntry[] coords]+//! ```+//!+//! Every section is 4-byte aligned so a reader takes zero-copy slices, and coordinates are+//! `i16` pairs in extent units with room either side for the clip buffer.+//!+//! `raw_len` lives in the body header, which is **outside** the compressed frame, so a+//! decompressing reader knows the exact output size before it starts: an exact-length read from+//! the leaf entry and a single allocation from here.++use crate::proto::{err, Result};++pub const BODY_HEADER_LEN: usize = 16;+pub const LAYER_INDEX_LEN: usize = 12;+pub const FEATURE_RECORD_LEN: usize = 16;+pub const PART_ENTRY_LEN: usize = 12;++/// A feature whose geometry is one or more open paths.+pub const GEOM_LINE: u8 = 1;+/// A feature whose geometry is one exterior ring plus its holes.+pub const GEOM_POLYGON: u8 = 2;++pub const FLAG_IS_TUNNEL: u8 = 1 << 0;+pub const FLAG_IS_BRIDGE: u8 = 1 << 1;+pub const FLAG_IS_LINK: u8 = 1 << 2;+/// `kind_detail` is a number, not an id into+/// [`dict::DETAILS`](super::dict::DETAILS).+///+/// What lets `boundaries` carry an admin level in the same field a road carries `service` in: the+/// style compares an admin level with `<=`, so interning it would mean interning every integer.+pub const FLAG_DETAIL_NUMERIC: u8 = 1 << 3;++const KNOWN_FEATURE_FLAGS: u8 =+    FLAG_IS_TUNNEL | FLAG_IS_BRIDGE | FLAG_IS_LINK | FLAG_DETAIL_NUMERIC;++/// A ring wound counter-clockwise: the outside of a polygon.+pub const WINDING_OUTER: u16 = 0;+/// A ring wound clockwise: a hole.+pub const WINDING_HOLE: u16 = 1;++/// The tile grid a body's coordinates are in. 4096, as MVT uses, so nothing downstream rescales.+pub const DEFAULT_EXTENT: u16 = 4096;++/// One feature.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct Feature {+    /// An id into [`dict::KINDS`](super::dict::KINDS), or+    /// [`dict::NONE`](super::dict::NONE).+    pub kind: u16,+    /// An id into [`dict::DETAILS`](super::dict::DETAILS), or a plain number when+    /// [`FLAG_DETAIL_NUMERIC`] is set.+    pub kind_detail: u16,+    pub geom_type: u8,+    pub flags: u8,+    /// Where this feature's parts start in the layer's part table.+    pub parts_offset: u32,+    pub part_count: u32,+}++impl Feature {+    pub fn is_tunnel(&self) -> bool {+        self.flags & FLAG_IS_TUNNEL != 0+    }++    pub fn is_bridge(&self) -> bool {+        self.flags & FLAG_IS_BRIDGE != 0+    }++    pub fn is_link(&self) -> bool {+        self.flags & FLAG_IS_LINK != 0+    }++    /// The numeric `kind_detail`, e.g. a boundary's admin level, or `None` when the field is an+    /// interned id.+    pub fn detail_number(&self) -> Option<u16> {+        (self.flags & FLAG_DETAIL_NUMERIC != 0).then_some(self.kind_detail)+    }+}++/// One path: a line, or one ring of a polygon.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct Part {+    /// Where this part's points start in the layer's coordinate arena, in points not bytes.+    pub coord_start: u32,+    pub point_count: u32,+    /// [`WINDING_OUTER`] or [`WINDING_HOLE`], stated rather than derived.+    ///+    /// Explicit because the generator already computed the signed area in `f64` with no frame+    /// budget, and a reader recovering it from `i16` coordinates that have been clipped and+    /// quantised can get a near-degenerate ring wrong.+    pub winding: u16,+}++impl Part {+    pub fn is_hole(&self) -> bool {+        self.winding == WINDING_HOLE+    }+}++/// One layer's features, parts and coordinates, decoded.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Layer {+    pub layer_id: u8,+    pub features: Vec<Feature>,+    pub parts: Vec<Part>,+    /// `x, y` pairs in extent units.+    pub coords: Vec<(i16, i16)>,+}++impl Layer {+    pub fn new(layer_id: u8) -> Layer {+        Layer { layer_id, features: Vec::new(), parts: Vec::new(), coords: Vec::new() }+    }++    /// The points of one part, as a slice of the arena.+    pub fn points(&self, part: &Part) -> &[(i16, i16)] {+        let start = part.coord_start as usize;+        &self.coords[start..start + part.point_count as usize]+    }++    /// The parts of one feature.+    pub fn parts_of(&self, feature: &Feature) -> &[Part] {+        let start = feature.parts_offset as usize;+        &self.parts[start..start + feature.part_count as usize]+    }+}++/// A whole tile.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Body {+    pub extent: u16,+    pub layers: Vec<Layer>,+}++impl Body {+    pub fn new(extent: u16) -> Body {+        Body { extent, layers: Vec::new() }+    }++    pub fn layer(&self, layer_id: u8) -> Option<&Layer> {+        self.layers.iter().find(|l| l.layer_id == layer_id)+    }++    /// The decompressed size a body's bytes will occupy, read without decoding anything else.+    ///+    /// Outside the compressed frame on purpose: it is what lets a reader allocate exactly once.+    /// Needs only the first eight bytes, so it can be answered from a frame's uncompressed prefix.+    pub fn raw_len(bytes: &[u8]) -> Result<u32> {+        if bytes.len() < 8 {+            return err("a .mamaps body is too short to declare its own length");+        }+        Ok(u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]))+    }++    /// Body header: `0..4` magic-and-version, `4..8` raw_len, `8..10` extent, `10` layer_count,+    /// `11` flags, `12..16` reserved.+    pub fn parse(buf: &[u8]) -> Result<Body> {+        if buf.len() < BODY_HEADER_LEN {+            return err("a .mamaps body is shorter than its own header");+        }+        if buf[0..3] != *b"MBD" {+            return err("not a .mamaps tile body (bad magic)");+        }+        if buf[3] != super::header::FORMAT_VERSION {+            return err(format!("unsupported .mamaps body version {}", buf[3]));+        }+        let raw_len = u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]) as usize;+        if raw_len != buf.len() {+            return err(format!(+                "a .mamaps body declares {raw_len} bytes but is {}",+                buf.len(),+            ));+        }+        let extent = u16::from_le_bytes([buf[8], buf[9]]);+        if extent == 0 {+            return err("a .mamaps body has a zero extent");+        }+        let layer_count = buf[10] as usize;+        if u32::from_le_bytes([buf[12], buf[13], buf[14], buf[15]]) != 0 {+            return err("a .mamaps body has a non-zero reserved word");+        }++        let index_end = BODY_HEADER_LEN + layer_count * LAYER_INDEX_LEN;+        if index_end > buf.len() {+            return err("a .mamaps body's layer index runs past its end");+        }+        let mut layers = Vec::with_capacity(layer_count);+        let mut previous: Option<u8> = None;+        for i in 0..layer_count {+            let at = BODY_HEADER_LEN + i * LAYER_INDEX_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 layer_id = buf[at];+            // Ascending and distinct, so `Body::layer` is unambiguous and a corrupt body cannot+            // present two layers with one id.+            if previous.is_some_and(|p| layer_id <= p) {+                return err("a .mamaps body's layers are not ordered by id");+            }+            previous = Some(layer_id);+            let feature_count = u16::from_le_bytes([buf[at + 2], buf[at + 3]]) as usize;+            let (offset, length) = (u32_at(4) as usize, u32_at(8) as usize);+            let end = offset.checked_add(length).ok_or_else(|| {+                crate::proto::Error("a .mamaps layer's extent overflows".to_string())+            })?;+            if offset < index_end || end > buf.len() {+                return err("a .mamaps layer's payload is outside the body");+            }+            layers.push(parse_layer(layer_id, feature_count, &buf[offset..end])?);+        }+        Ok(Body { extent, layers })+    }+}++/// One layer's payload: features, then parts, then the coordinate arena.+///+/// Every count is bounded by the slice it is read from before anything is allocated, so a corrupt+/// body cannot ask for a gigabyte of `Vec`.+fn parse_layer(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) {+            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,+            parts_offset: u32_at(8),+            part_count: u32_at(12),+        };+        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 + coords_needed * 4 > buf.len() {+        return err("a .mamaps layer's coordinates run past its payload");+    }+    let mut coords = Vec::with_capacity(coords_needed);+    for i in 0..coords_needed {+        let at = coords_at + i * 4;+        coords.push((+            i16::from_le_bytes([buf[at], buf[at + 1]]),+            i16::from_le_bytes([buf[at + 2], buf[at + 3]]),+        ));+    }+    Ok(Layer { layer_id, features, parts, coords })+}++/// Round up to the next 4-byte boundary, so every section starts where a reader can slice it.+pub(crate) fn align4(at: usize) -> usize {+    (at + 3) & !3+}++/// Serialise a body.+///+/// Deliberately available without the `write` feature: a synthetic body is how the reader's own+/// tests get something to read, and `mamaps_dump` round-trips one to check a body is sane.+pub fn serialize(body: &Body) -> Result<Vec<u8>> {+    let mut layers = body.layers.clone();+    // Ascending by id, which the parser requires and `Body::layer` assumes. Sorted rather than+    // rejected, because a caller assembling a tile per style layer has no reason to care.+    layers.sort_by_key(|l| l.layer_id);+    if layers.windows(2).any(|pair| pair[0].layer_id == pair[1].layer_id) {+        return err("a .mamaps body cannot carry two layers with the same id");+    }+    for layer in &layers {+        if layer.features.len() > u16::MAX as usize {+            return err(format!(+                "layer {} has {} features, past the {} a .mamaps body can index",+                layer.layer_id,+                layer.features.len(),+                u16::MAX,+            ));+        }+    }++    let index_end = BODY_HEADER_LEN + layers.len() * LAYER_INDEX_LEN;+    let mut payloads: Vec<(u8, u16, Vec<u8>)> = Vec::with_capacity(layers.len());+    for layer in &layers {+        let mut out = Vec::new();+        for feature in &layer.features {+            out.extend_from_slice(&feature.kind.to_le_bytes());+            out.extend_from_slice(&feature.kind_detail.to_le_bytes());+            out.push(feature.geom_type);+            out.push(feature.flags);+            out.extend_from_slice(&0u16.to_le_bytes());+            out.extend_from_slice(&feature.parts_offset.to_le_bytes());+            out.extend_from_slice(&feature.part_count.to_le_bytes());+        }+        for part in &layer.parts {+            out.extend_from_slice(&part.coord_start.to_le_bytes());+            out.extend_from_slice(&part.point_count.to_le_bytes());+            out.extend_from_slice(&part.winding.to_le_bytes());+            out.extend_from_slice(&0u16.to_le_bytes());+        }+        while out.len() % 4 != 0 {+            out.push(0);+        }+        for (x, y) in &layer.coords {+            out.extend_from_slice(&x.to_le_bytes());+            out.extend_from_slice(&y.to_le_bytes());+        }+        payloads.push((layer.layer_id, layer.features.len() as u16, out));+    }++    let mut offset = align4(index_end);+    let mut index = Vec::with_capacity(layers.len() * LAYER_INDEX_LEN);+    for (layer_id, feature_count, payload) in &payloads {+        index.push(*layer_id);+        index.push(0);+        index.extend_from_slice(&feature_count.to_le_bytes());+        index.extend_from_slice(&(offset as u32).to_le_bytes());+        index.extend_from_slice(&(payload.len() as u32).to_le_bytes());+        offset += payload.len();+    }++    let mut out = Vec::with_capacity(offset);+    out.extend_from_slice(b"MBD");+    out.push(super::header::FORMAT_VERSION);+    // Patched below, once the length is known.+    out.extend_from_slice(&0u32.to_le_bytes());+    out.extend_from_slice(&body.extent.to_le_bytes());+    out.push(layers.len() as u8);+    out.push(0);+    out.extend_from_slice(&0u32.to_le_bytes());+    out.extend_from_slice(&index);+    while out.len() % 4 != 0 {+        out.push(0);+    }+    for (_, _, payload) in &payloads {+        out.extend_from_slice(payload);+    }+    let raw_len = out.len() as u32;+    out[4..8].copy_from_slice(&raw_len.to_le_bytes());+    Ok(out)+}++#[cfg(test)]+mod tests {+    use super::*;+    use crate::mamaps::dict;++    /// A tile with one polygon carrying a hole and one road, which between them exercise every+    /// field the format has.+    fn sample() -> Body {+        let mut water = Layer::new(dict::LAYER_WATER);+        water.features.push(Feature {+            kind: 4,+            kind_detail: dict::NONE,+            geom_type: GEOM_POLYGON,+            flags: 0,+            parts_offset: 0,+            part_count: 2,+        });+        water.parts.push(Part { coord_start: 0, point_count: 4, winding: WINDING_OUTER });+        water.parts.push(Part { coord_start: 4, point_count: 4, winding: WINDING_HOLE });+        water.coords = vec![+            (0, 0),+            (4096, 0),+            (4096, 4096),+            (0, 4096),+            (1000, 1000),+            (1000, 2000),+            (2000, 2000),+            (2000, 1000),+        ];++        let mut roads = Layer::new(dict::LAYER_ROADS);+        roads.features.push(Feature {+            kind: 45,+            kind_detail: 4,+            geom_type: GEOM_LINE,+            flags: FLAG_IS_BRIDGE | FLAG_IS_LINK,+            parts_offset: 0,+            part_count: 1,+        });+        roads.parts.push(Part { coord_start: 0, point_count: 3, winding: WINDING_OUTER });+        roads.coords = vec![(-64, 10), (2048, 2048), (4160, 4000)];++        Body { extent: DEFAULT_EXTENT, layers: vec![roads, water] }+    }++    #[test]+    fn a_body_round_trips_with_its_layers_in_id_order() {+        let bytes = serialize(&sample()).expect("should serialize");+        let parsed = Body::parse(&bytes).expect("should parse");+        assert_eq!(parsed.extent, DEFAULT_EXTENT);+        // Sorted on the way out, whatever order the caller assembled them in.+        assert_eq!(+            parsed.layers.iter().map(|l| l.layer_id).collect::<Vec<_>>(),+            vec![dict::LAYER_WATER, dict::LAYER_ROADS],+        );+        let expected = {+            let mut body = sample();+            body.layers.sort_by_key(|l| l.layer_id);+            body+        };+        assert_eq!(parsed, expected);+    }++    #[test]+    fn every_fixed_record_is_the_width_the_format_declares() {+        // A stride that drifted would misread every record after the first.+        let bytes = serialize(&sample()).expect("serialize");+        assert_eq!(&bytes[0..3], b"MBD");+        assert_eq!(Body::raw_len(&bytes).expect("raw_len"), bytes.len() as u32);+        // Two layers: header, two index entries, then payloads.+        assert_eq!(BODY_HEADER_LEN + 2 * LAYER_INDEX_LEN, 40);+        assert_eq!(FEATURE_RECORD_LEN, 16);+        assert_eq!(PART_ENTRY_LEN, 12);+    }++    /// `raw_len` is read from the body header, which sits outside the compressed frame, so a+    /// decompressing reader knows the output size before it starts and allocates once.+    #[test]+    fn raw_len_is_readable_from_the_first_eight_bytes_alone() {+        let bytes = serialize(&sample()).expect("serialize");+        assert_eq!(Body::raw_len(&bytes[..8]).expect("raw_len"), bytes.len() as u32);+        assert!(Body::raw_len(&bytes[..7]).is_err(), "too short to declare a length");+    }++    #[test]+    fn every_layer_payload_starts_four_byte_aligned() {+        // What lets a reader take zero-copy slices of the coordinate arena.+        let bytes = serialize(&sample()).expect("serialize");+        let layer_count = bytes[10] as usize;+        for i in 0..layer_count {+            let at = BODY_HEADER_LEN + i * LAYER_INDEX_LEN;+            let offset =+                u32::from_le_bytes([bytes[at + 4], bytes[at + 5], bytes[at + 6], bytes[at + 7]]);+            assert_eq!(offset % 4, 0, "layer {i} starts at {offset}");+        }+    }++    #[test]+    fn a_features_geometry_reads_back_through_the_part_table() {+        let bytes = serialize(&sample()).expect("serialize");+        let body = Body::parse(&bytes).expect("parse");+        let water = body.layer(dict::LAYER_WATER).expect("water");+        let feature = &water.features[0];+        let parts = water.parts_of(feature);+        assert_eq!(parts.len(), 2);+        assert!(!parts[0].is_hole(), "the exterior is outer");+        assert!(parts[1].is_hole());+        assert_eq!(water.points(&parts[0]).len(), 4);+        assert_eq!(water.points(&parts[1])[0], (1000, 1000));++        let roads = body.layer(dict::LAYER_ROADS).expect("roads");+        let road = &roads.features[0];+        assert!(road.is_bridge() && road.is_link() && !road.is_tunnel());+        assert_eq!(road.detail_number(), None, "an interned detail, not a number");+        // Coordinates may leave the tile: the clip keeps a buffer either side.+        assert_eq!(roads.points(&roads.parts_of(road)[0])[0], (-64, 10));+    }++    /// A boundary's admin level shares the field a road's `service` uses, discriminated by a flag,+    /// because the style compares an admin level with `<=` rather than matching a name.+    #[test]+    fn a_numeric_detail_is_a_number_and_an_interned_one_is_not() {+        let mut boundaries = Layer::new(dict::LAYER_BOUNDARIES);+        boundaries.features.push(Feature {+            kind: dict::NONE,+            kind_detail: 2,+            geom_type: GEOM_LINE,+            flags: FLAG_DETAIL_NUMERIC,+            parts_offset: 0,+            part_count: 1,+        });+        boundaries.parts.push(Part { coord_start: 0, point_count: 2, winding: WINDING_OUTER });+        boundaries.coords = vec![(0, 0), (100, 100)];+        let bytes = serialize(&Body { extent: DEFAULT_EXTENT, layers: vec![boundaries] })+            .expect("serialize");+        let body = Body::parse(&bytes).expect("parse");+        let feature = &body.layer(dict::LAYER_BOUNDARIES).expect("boundaries").features[0];+        assert_eq!(feature.detail_number(), Some(2), "admin level 2, a country border");+    }++    #[test]+    fn an_empty_body_is_valid_and_is_what_an_ocean_tile_costs() {+        let bytes = serialize(&Body::new(DEFAULT_EXTENT)).expect("serialize");+        assert_eq!(bytes.len(), BODY_HEADER_LEN, "nothing but the header");+        let body = Body::parse(&bytes).expect("parse");+        assert!(body.layers.is_empty());+        assert_eq!(body.extent, DEFAULT_EXTENT);+    }++    #[test]+    fn a_layer_with_no_features_still_round_trips() {+        let body = Body { extent: DEFAULT_EXTENT, layers: vec![Layer::new(dict::LAYER_EARTH)] };+        let parsed = Body::parse(&serialize(&body).expect("serialize")).expect("parse");+        assert_eq!(parsed, body);+    }++    #[test]+    fn a_body_carrying_two_layers_with_one_id_is_refused() {+        let body = Body {+            extent: DEFAULT_EXTENT,+            layers: vec![Layer::new(dict::LAYER_WATER), Layer::new(dict::LAYER_WATER)],+        };+        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, fn(&mut Vec<u8>))] = &[+            ("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");+        }+    }++    /// Points are not carried at all: the renderer decoded them and threw them away, so a body+    /// claiming one is a body written by something that misunderstood the format.+    #[test]+    fn a_point_geometry_is_refused_because_this_format_has_none() {+        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] = 3;+        assert!(Body::parse(&bytes).is_err(), "a point");+        bytes[at + 4] = GEOM_POLYGON;+        assert!(Body::parse(&bytes).is_ok(), "and the sample is otherwise fine");+    }++    #[test]+    fn a_feature_or_part_pointing_outside_its_own_tables_is_refused() {+        let at = align4(BODY_HEADER_LEN + 2 * LAYER_INDEX_LEN);+        let cases: &[(&str, usize, u32)] = &[+            ("a part table past the payload", at + 8, 9_999),+            ("a feature with no geometry", at + 12, 0),+            ("more parts than the payload holds", at + 12, 9_999),+        ];+        for (what, offset, value) in cases {+            let mut bytes = serialize(&sample()).expect("serialize");+            bytes[*offset..*offset + 4].copy_from_slice(&value.to_le_bytes());+            assert!(Body::parse(&bytes).is_err(), "{what} should be refused");+        }+    }++    #[test]+    fn a_winding_that_is_neither_outer_nor_hole_is_refused() {+        let mut bytes = serialize(&sample()).expect("serialize");+        // Water's part table follows its single 16-byte feature record.+        let at = align4(BODY_HEADER_LEN + 2 * LAYER_INDEX_LEN) + FEATURE_RECORD_LEN;+        bytes[at + 8..at + 10].copy_from_slice(&7u16.to_le_bytes());+        assert!(Body::parse(&bytes).is_err());+    }++    #[test]+    fn an_unknown_feature_flag_is_refused() {+        let mut bytes = serialize(&sample()).expect("serialize");+        let at = align4(BODY_HEADER_LEN + 2 * LAYER_INDEX_LEN);+        bytes[at + 5] = 0x80;+        assert!(Body::parse(&bytes).is_err());+    }++    /// Byte-for-byte the same input gives byte-for-byte the same body, because nothing in the+    /// encoder iterates a hash map. Invariant 5 of the plan's list, at the body level.+    #[test]+    fn serialising_the_same_body_twice_gives_the_same_bytes() {+        assert_eq!(serialize(&sample()).expect("a"), serialize(&sample()).expect("b"));+        // And assembling the layers in the other order does too, because they are sorted.+        let mut reordered = sample();+        reordered.layers.reverse();+        assert_eq!(serialize(&sample()).expect("a"), serialize(&reordered).expect("b"));+    }+}
library/tilecodec/src/main/rust/src/mamaps/dict.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/dict.rs b/library/tilecodec/src/main/rust/src/mamaps/dict.rsnew file mode 100644index 0000000000..6cf9450386--- /dev/null+++ b/library/tilecodec/src/main/rust/src/mamaps/dict.rs@@ -0,0 +1,331 @@+//! The archive-wide dictionary: layer names, `kind`s and `kind_detail`s, interned to integers.+//!+//! This is the largest single win over MVT. There, every tile carries its own string table and+//! every feature carries a key/value property map, so the renderer paid a `String` allocation per+//! feature per tile to read the one property it actually looks at. Here a feature's whole+//! attribute surface is two `u16`s and three bits, because that is all the style filters on.+//!+//! # Why the table is a constant and not observed+//!+//! Ids come from [`SCHEMA`]'s position, never from the order a build happened to encounter+//! values in. Two consequences, both load-bearing:+//!+//! * A California archive has a **byte-identical** dictionary to a planet one, so the section is+//!   comparable across builds and a diff of two archives is a diff of their tiles.+//! * An id never shifts between builds, so a cached tile from yesterday's archive cannot be+//!   reinterpreted against today's dictionary and come out a different colour. The+//!   [`build_id`](super::header::Header::build_id) still invalidates the cache; this makes the+//!   failure impossible rather than merely unlikely.+//!+//! The dictionary is still written to the file. A reader validates its own compiled-in table+//! against it on open, and `mamaps_dump` needs the names to print without linking the schema.+//!+//! # Size+//!+//! Seven layers, 52 kinds and 4 details, at a length byte each: comfortably under 1 KiB, which is+//! what lets the header, the dictionary and the root index share one 16 KiB opening read.++use crate::proto::{err, Result};++/// `kind` and `kind_detail` id 0: the feature carries none.+///+/// Not a sentinel a reader has to guess at — the unfiltered layers (`earth`'s land, the+/// `landcover` fallback) genuinely have no `kind`, and the style draws them by matching+/// everything.+pub const NONE: u16 = 0;++/// The layers this format carries, in draw order.+///+/// A layer's id **is** its index here. Seven, which is what the style draws; the format has no+/// room for an eighth without a version bump, and that is deliberate — a layer nothing paints is+/// bytes every reader downloads and discards.+pub const LAYERS: &[&str] =+    &["earth", "water", "landcover", "landuse", "roads", "boundaries", "buildings"];++pub const LAYER_EARTH: u8 = 0;+pub const LAYER_WATER: u8 = 1;+pub const LAYER_LANDCOVER: u8 = 2;+pub const LAYER_LANDUSE: u8 = 3;+pub const LAYER_ROADS: u8 = 4;+pub const LAYER_BOUNDARIES: u8 = 5;+pub const LAYER_BUILDINGS: u8 = 6;++/// Every `kind` value the schema can emit, id 1 upward. Index 0 is [`NONE`].+///+/// Grouped by the layer that introduced each value and **append-only**: inserting in the middle+/// would renumber everything after it, which is the one thing this table exists to prevent. A+/// value shared by two layers appears once, because ids are archive-wide.+pub const KINDS: &[&str] = &[+    // earth+    "island",+    // water+    "bay",+    "fjord",+    "lake",+    "ocean",+    "river",+    "sea",+    "strait",+    "stream",+    "water",+    // landcover+    "grassland",+    "barren",+    "urban_area",+    "farmland",+    "glacier",+    "scrub",+    // landuse. `grassland` and `scrub` are already above and are not repeated.+    "national_park",+    "park",+    "cemetery",+    "protected_area",+    "nature_reserve",+    "forest",+    "golf_course",+    "wood",+    "grass",+    "military",+    "naval_base",+    "airfield",+    "allotments",+    "village_green",+    "playground",+    "hospital",+    "industrial",+    "school",+    "university",+    "college",+    "beach",+    "zoo",+    "aerodrome",+    "runway",+    "taxiway",+    "pedestrian",+    "dam",+    "pier",+    // roads+    "highway",+    "major_road",+    "minor_road",+    "path",+    "other",+    "rail",+    // buildings+    "building",+    "building_part",+];++/// Every `kind_detail` value, id 1 upward. Index 0 is [`NONE`].+///+/// A separate table from [`KINDS`], so `runway` as a `landuse` kind and `runway` as a road's+/// detail are different ids. They describe different things and collapsing them would make a+/// road's detail collide with a polygon's kind.+///+/// `boundaries` does not appear here: its detail is a numeric admin level carried in the same+/// field under [`super::body::FLAG_DETAIL_NUMERIC`], because an admin level is an integer the+/// style compares with `<=` rather than a name it matches.+pub const DETAILS: &[&str] = &["runway", "taxiway", "pier", "service"];++/// The interned tables as the archive carries them.+///+/// Parsed from the file rather than assumed, so a reader can tell a mismatched archive from a+/// mismatched reader.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Dictionary {+    pub layers: Vec<String>,+    pub kinds: Vec<String>,+    pub details: Vec<String>,+}++impl Dictionary {+    /// The compiled-in schema, which is what a writer always emits.+    pub fn schema() -> Dictionary {+        let owned = |table: &[&str]| table.iter().map(|s| s.to_string()).collect();+        Dictionary { layers: owned(LAYERS), kinds: owned(KINDS), details: owned(DETAILS) }+    }++    pub fn layer_name(&self, id: u8) -> Option<&str> {+        self.layers.get(id as usize).map(String::as_str)+    }++    /// The name of a `kind` id, or `None` for [`NONE`] and for anything past the table.+    pub fn kind_name(&self, id: u16) -> Option<&str> {+        (id != NONE).then(|| self.kinds.get(id as usize - 1).map(String::as_str)).flatten()+    }++    pub fn detail_name(&self, id: u16) -> Option<&str> {+        (id != NONE).then(|| self.details.get(id as usize - 1).map(String::as_str)).flatten()+    }++    /// Three counted tables back to back, then zero padding to a 4-byte boundary.+    ///+    /// Each table is a `u16` count followed by that many `u8`-length-prefixed strings. Padding+    /// so the root index that follows starts aligned and a reader can slice it zero-copy.+    pub fn serialize(&self) -> Vec<u8> {+        let mut out = Vec::with_capacity(1024);+        for table in [&self.layers, &self.kinds, &self.details] {+            out.extend_from_slice(&(table.len() as u16).to_le_bytes());+            for name in table {+                out.push(name.len() as u8);+                out.extend_from_slice(name.as_bytes());+            }+        }+        while out.len() % 4 != 0 {+            out.push(0);+        }+        out+    }++    pub fn parse(buf: &[u8]) -> Result<Dictionary> {+        let mut at = 0usize;+        let mut table = |what: &str, limit: usize| -> Result<Vec<String>> {+            if at + 2 > buf.len() {+                return err(format!("a .mamaps dictionary ends before its {what} count"));+            }+            let count = u16::from_le_bytes([buf[at], buf[at + 1]]) as usize;+            at += 2;+            if count > limit {+                return err(format!(+                    "a .mamaps dictionary declares {count} {what}, past the {limit} this format allows"+                ));+            }+            let mut names = Vec::with_capacity(count);+            for _ in 0..count {+                if at >= buf.len() {+                    return err(format!("a .mamaps dictionary ends inside its {what}"));+                }+                let len = buf[at] as usize;+                at += 1;+                if at + len > buf.len() {+                    return err(format!("a .mamaps {what} name runs past the dictionary"));+                }+                let name = std::str::from_utf8(&buf[at..at + len])+                    .map_err(|_| crate::proto::Error(format!("a .mamaps {what} name is not UTF-8")))?;+                names.push(name.to_string());+                at += len;+            }+            Ok(names)+        };+        // A layer id is a `u8` and a kind id a `u16`, so those are the real ceilings; naming them+        // here is what stops a corrupt count from asking for a gigabyte of `String`s.+        let layers = table("layer", u8::MAX as usize)?;+        let kinds = table("kind", u16::MAX as usize - 1)?;+        let details = table("kind_detail", u16::MAX as usize - 1)?;+        Ok(Dictionary { layers, kinds, details })+    }++    /// Refuse an archive whose tables are not the ones this build was compiled against.+    ///+    /// A **whole-table** comparison rather than a length check: the point of a constant table is+    /// that id 17 means `national_park` in every archive ever written, so an archive that+    /// disagrees anywhere would render some layer in the wrong colour with no other symptom.+    pub fn check_matches_schema(&self) -> Result<()> {+        let schema = Dictionary::schema();+        for (what, ours, theirs) in [+            ("layer", &schema.layers, &self.layers),+            ("kind", &schema.kinds, &self.kinds),+            ("kind_detail", &schema.details, &self.details),+        ] {+            if ours == theirs {+                continue;+            }+            let first = ours+                .iter()+                .zip(theirs.iter())+                .position(|(a, b)| a != b)+                .unwrap_or(ours.len().min(theirs.len()));+            return err(format!(+                "a .mamaps {what} table disagrees with this build's schema from id {first} \+                 ({} entries here, {} in the archive)",+                ours.len(),+                theirs.len(),+            ));+        }+        Ok(())+    }+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn the_dictionary_round_trips_and_stays_under_a_kilobyte() {+        let schema = Dictionary::schema();+        let bytes = schema.serialize();+        assert!(bytes.len() < 1024, "the dictionary is {} bytes", bytes.len());+        assert_eq!(bytes.len() % 4, 0, "the root index after it must start aligned");+        assert_eq!(Dictionary::parse(&bytes).expect("should parse"), schema);+    }++    /// **The invariant the whole table exists for.** An id is a position, so a value's id must+    /// not depend on anything a build observed. Pinned as literals: a diff that moves an entry+    /// shows up here as a changed number rather than as a recoloured map.+    #[test]+    fn kind_ids_are_positions_in_a_constant_table() {+        let d = Dictionary::schema();+        assert_eq!(d.kind_name(1), Some("island"), "the first kind");+        assert_eq!(d.kind_name(10), Some("water"));+        assert_eq!(d.kind_name(17), Some("national_park"));+        assert_eq!(d.kind_name(45), Some("highway"));+        assert_eq!(d.kind_name(52), Some("building_part"), "the last kind");+        assert_eq!(d.kind_name(NONE), None, "id 0 is `this feature has no kind`");+        assert_eq!(d.kind_name(53), None, "past the table");+        assert_eq!(d.detail_name(4), Some("service"));+        assert_eq!(d.layer_name(LAYER_ROADS), Some("roads"));+        assert_eq!(d.layer_name(7), None);+    }++    /// A duplicate would give one value two ids, so half the features carrying it would filter+    /// against a style whitelist and half would not.+    #[test]+    fn no_value_appears_twice_in_a_table() {+        for (what, table) in [("layer", LAYERS), ("kind", KINDS), ("detail", DETAILS)] {+            let mut seen: Vec<&str> = table.to_vec();+            seen.sort_unstable();+            let before = seen.len();+            seen.dedup();+            assert_eq!(before, seen.len(), "the {what} table repeats a value");+        }+    }++    /// Ids are `u8` for a layer and `u16` for the rest, and a name's length is one byte.+    #[test]+    fn every_table_fits_the_field_that_carries_its_ids() {+        assert!(LAYERS.len() <= u8::MAX as usize);+        assert!(KINDS.len() < u16::MAX as usize);+        assert!(DETAILS.len() < u16::MAX as usize);+        for name in LAYERS.iter().chain(KINDS).chain(DETAILS) {+            assert!(!name.is_empty(), "an empty name would be indistinguishable from padding");+            assert!(name.len() <= u8::MAX as usize, "`{name}` needs a longer length prefix");+        }+    }++    #[test]+    fn an_archive_whose_tables_differ_is_refused() {+        assert!(Dictionary::schema().check_matches_schema().is_ok());+        let mut renamed = Dictionary::schema();+        renamed.kinds[16] = "national_parks".to_string();+        let message = renamed.check_matches_schema().expect_err("should be refused").0;+        assert!(message.contains("from id 16"), "{message}");+        let mut short = Dictionary::schema();+        short.details.pop();+        assert!(short.check_matches_schema().is_err());+    }++    #[test]+    fn a_truncated_or_implausible_dictionary_is_refused() {+        let bytes = Dictionary::schema().serialize();+        for cut in [0, 1, 2, 5, 40, bytes.len() - 4] {+            assert!(Dictionary::parse(&bytes[..cut]).is_err(), "truncated at {cut}");+        }+        // A count no length field could carry, which is how a corrupt section would otherwise+        // ask for a gigabyte of `String`s.+        assert!(Dictionary::parse(&[0xFF, 0xFF]).is_err());+        // A name whose length runs off the end.+        assert!(Dictionary::parse(&[1, 0, 200, b'a']).is_err());+        // A name that is not text.+        assert!(Dictionary::parse(&[1, 0, 1, 0xFF]).is_err());+    }+}
library/tilecodec/src/main/rust/src/mamaps/header.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/header.rs b/library/tilecodec/src/main/rust/src/mamaps/header.rsnew file mode 100644index 0000000000..7565b41645--- /dev/null+++ b/library/tilecodec/src/main/rust/src/mamaps/header.rs@@ -0,0 +1,406 @@+//! The `.mamaps` header: 128 fixed bytes that locate every other section.+//!+//! Every section is found **only** through an offset declared here. Nothing is inferred from+//! layout, because layout is not fixed: the real 137 GB PMTiles archive puts its leaf+//! directories *after* its tile data, and a reader that assumed otherwise would address the+//! wrong bytes. The same freedom is deliberately kept here.+//!+//! The header is small enough that it always arrives inside the reader's opening prefix+//! together with the dictionary and the root index, which is what makes a cold open one range+//! request. [`super::write`] asserts that budget rather than letting a build silently cost every+//! reader a third round trip.++use crate::proto::{err, Result};++pub const MAGIC: &[u8; 7] = b"MAMAPS\0";++/// Bumped only for a change a reader cannot ignore. The archive carries a+/// [`build_id`](Header::build_id) for "same format, different data".+pub const FORMAT_VERSION: u8 = 1;++pub const HEADER_LEN: usize = 128;++/// Bodies are compressed frames; clear means the body is stored raw.+pub const FLAG_BODIES_COMPRESSED: u16 = 1 << 0;+/// At least one leaf entry has a `run_length` above 1, so a reader must honour runs.+pub const FLAG_RUN_LENGTH_PRESENT: u16 = 1 << 1;+/// Ring winding and hole containment were normalised at build time.+///+/// What lets `tess::fill`'s repair pass be skipped: with this set, every polygon part group has+/// exactly one CCW outer and its holes are CW and strictly inside it.+pub const FLAG_RINGS_VALIDATED: u16 = 1 << 2;++const KNOWN_FLAGS: u16 =+    FLAG_BODIES_COMPRESSED | FLAG_RUN_LENGTH_PRESENT | FLAG_RINGS_VALIDATED;++/// Bodies stored as written.+pub const COMPRESSION_NONE: u8 = 0;+/// Raw DEFLATE, one independent frame per body.+///+/// Not zstd, which is what a container designed on paper would reach for. This crate's whole+/// dependency list is `miniz_oxide` — pure Rust, so it cross-compiles for+/// `aarch64-linux-android` with no C toolchain and nothing to configure — and zstd's encoder+/// would end that. Not gzip either: gzip costs 18 bytes of framing per body and existed only+/// because MapLibre requires it, which nothing reading this format does.+pub const COMPRESSION_DEFLATE: u8 = 1;++/// The deepest zoom a `tile_id_lo` can span inside one leaf. See [`super::index`].+pub const MAX_ZOOM: u8 = 22;++/// What a reader must know before it can address anything.+///+/// Field order **is** wire order, and the byte map is in [`Header::parse`]. Lengths are `u32`+/// wherever a section cannot plausibly exceed 4 GiB; offsets are `u64` without exception,+/// because the data section on its own is already past that on a planet build.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Header {+    pub flags: u16,+    pub compression: u8,+    pub layer_count: u8,+    pub min_zoom: u8,+    pub max_zoom: u8,+    /// Identifies the *data*, not the format: hashed over the generator revision, the input+    /// digest, the zoom range, the layer set and the simplification parameters.+    ///+    /// This is the only thing standing between republishing under a stable `immutable` URL and+    /// every existing reader serving stale tiles forever. It costs no extra request, because it+    /// is already in the prefix a reader fetches to open the archive at all.+    pub build_id: u64,+    /// The whole file, so a truncated download is caught on open rather than at the first tile+    /// that happens to land past the end.+    pub file_len: u64,+    pub dict_offset: u64,+    pub dict_len: u32,+    /// Leaf entries per leaf. A power of two, doubled at build time when the root would not fit.+    pub leaf_entry_capacity: u32,+    pub root_offset: u64,+    pub root_len: u32,+    pub leaf_count: u32,+    pub leaf_offset: u64,+    pub leaf_len: u32,+    pub data_offset: u64,+    pub data_len: u64,+    /// Tiles that resolve to a body, counting every id a run covers.+    pub tiles_addressed: u64,+    /// Bodies actually stored, after run-length and content dedup.+    pub bodies_written: u64,+    pub min_lon_e7: i32,+    pub min_lat_e7: i32,+    pub max_lon_e7: i32,+    pub max_lat_e7: i32,+}++impl Header {+    pub fn compressed(&self) -> bool {+        self.flags & FLAG_BODIES_COMPRESSED != 0+    }++    pub fn rings_validated(&self) -> bool {+        self.flags & FLAG_RINGS_VALIDATED != 0+    }++    /// Read a header out of the opening prefix.+    ///+    /// Byte map, all little-endian: `0..7` magic, `7` format version, `8..10` header_len,+    /// `10..12` flags, `12` compression, `13` layer_count, `14` min_zoom, `15` max_zoom,+    /// `16..24` build_id, `24..32` file_len, `32..40` dict_offset, `40..44` dict_len,+    /// `44..48` leaf_entry_capacity, `48..56` root_offset, `56..60` root_len, `60..64`+    /// leaf_count, `64..72` leaf_offset, `72..76` leaf_len, `76..80` reserved, `80..88`+    /// data_offset, `88..96` data_len, `96..104` tiles_addressed, `104..112` bodies_written,+    /// `112..128` the bbox as four `i32` of degrees times 1e7.+    ///+    /// Every `u64` sits on an 8-byte boundary so a reader may take them as aligned loads.+    pub fn parse(buf: &[u8]) -> Result<Header> {+        if buf.len() < HEADER_LEN {+            return err(format!("a .mamaps header is {HEADER_LEN} bytes, got {}", buf.len()));+        }+        if &buf[0..7] != MAGIC {+            return err("not a .mamaps archive (bad magic)");+        }+        if buf[7] != FORMAT_VERSION {+            return err(format!(+                "unsupported .mamaps format version {} (this reader speaks {FORMAT_VERSION})",+                buf[7],+            ));+        }+        let u16_at = |o: usize| u16::from_le_bytes([buf[o], buf[o + 1]]);+        let u32_at = |o: usize| u32::from_le_bytes([buf[o], buf[o + 1], buf[o + 2], buf[o + 3]]);+        let i32_at = |o: usize| i32::from_le_bytes([buf[o], buf[o + 1], buf[o + 2], buf[o + 3]]);+        let u64_at = |o: usize| {+            u64::from_le_bytes([+                buf[o],+                buf[o + 1],+                buf[o + 2],+                buf[o + 3],+                buf[o + 4],+                buf[o + 5],+                buf[o + 6],+                buf[o + 7],+            ])+        };++        let header_len = u16_at(8);+        if header_len as usize != HEADER_LEN {+            return err(format!("a .mamaps header declares {header_len} bytes, not {HEADER_LEN}"));+        }+        let flags = u16_at(10);+        // An unknown flag means the writer recorded something about the bodies that this reader+        // would ignore, and every flag in this format changes how a body must be handled. Better+        // to refuse the archive than to draw it wrong.+        if flags & !KNOWN_FLAGS != 0 {+            return err(format!("a .mamaps header sets unknown flags {:#06X}", flags & !KNOWN_FLAGS));+        }+        // Reserved bytes are checked rather than skipped, so a later version cannot put a field+        // here and have this reader silently ignore it.+        if u32_at(76) != 0 {+            return err("a .mamaps header has a non-zero reserved word");+        }+        let header = Header {+            flags,+            compression: buf[12],+            layer_count: buf[13],+            min_zoom: buf[14],+            max_zoom: buf[15],+            build_id: u64_at(16),+            file_len: u64_at(24),+            dict_offset: u64_at(32),+            dict_len: u32_at(40),+            leaf_entry_capacity: u32_at(44),+            root_offset: u64_at(48),+            root_len: u32_at(56),+            leaf_count: u32_at(60),+            leaf_offset: u64_at(64),+            leaf_len: u32_at(72),+            data_offset: u64_at(80),+            data_len: u64_at(88),+            tiles_addressed: u64_at(96),+            bodies_written: u64_at(104),+            min_lon_e7: i32_at(112),+            min_lat_e7: i32_at(116),+            max_lon_e7: i32_at(120),+            max_lat_e7: i32_at(124),+        };+        header.check()?;+        Ok(header)+    }++    /// Everything a later read would otherwise discover the hard way.+    ///+    /// A corrupt or hostile header must not be able to name a section that overlaps another, runs+    /// past the file, or is implausibly large — because every subsequent read takes its length+    /// from a field here, and a wrong length is a read that either fails somewhere uninformative+    /// or poisons a disk cache entry with a body of the wrong size.+    fn check(&self) -> Result<()> {+        if !matches!(self.compression, COMPRESSION_NONE | COMPRESSION_DEFLATE) {+            return err(format!("unknown .mamaps compression {}", self.compression));+        }+        if self.compressed() != (self.compression != COMPRESSION_NONE) {+            return err("a .mamaps header disagrees with itself about whether bodies are compressed");+        }+        if self.min_zoom > self.max_zoom || self.max_zoom > MAX_ZOOM {+            return err(format!(+                "a .mamaps header declares an impossible zoom range {}..={}",+                self.min_zoom, self.max_zoom,+            ));+        }+        if !self.leaf_entry_capacity.is_power_of_two() {+            return err(format!(+                "a .mamaps leaf capacity of {} is not a power of two",+                self.leaf_entry_capacity,+            ));+        }+        if self.leaf_count == 0 {+            return err("a .mamaps archive needs at least one leaf");+        }+        if self.file_len < HEADER_LEN as u64 {+            return err(format!("a .mamaps header declares a {} byte file", self.file_len));+        }+        let sections = [+            ("the dictionary", self.dict_offset, self.dict_len as u64),+            ("the root index", self.root_offset, self.root_len as u64),+            ("the leaf index", self.leaf_offset, self.leaf_len as u64),+            ("the tile data", self.data_offset, self.data_len),+        ];+        for (what, offset, len) in sections {+            if offset < HEADER_LEN as u64 {+                return err(format!("{what} overlaps the .mamaps header"));+            }+            match offset.checked_add(len) {+                Some(end) if end <= self.file_len => {}+                _ => return err(format!("{what} runs past the end of the .mamaps file")),+            }+        }+        // Pairwise, because a writer that patched one offset and not another would otherwise+        // produce a file whose index and data disagree about where a body lives.+        for (i, (what, offset, len)) in sections.iter().enumerate() {+            for (other, other_offset, other_len) in &sections[i + 1..] {+                if *len == 0 || *other_len == 0 {+                    continue;+                }+                if *offset < other_offset + other_len && *other_offset < offset + len {+                    return err(format!("{what} and {other} overlap in the .mamaps file"));+                }+            }+        }+        if self.root_len as usize % super::index::ROOT_ENTRY_LEN != 0 {+            return err(format!(+                "a .mamaps root index of {} bytes is not a whole number of {} byte entries",+                self.root_len,+                super::index::ROOT_ENTRY_LEN,+            ));+        }+        if self.bodies_written > self.tiles_addressed {+            return err("a .mamaps header stores more bodies than it addresses tiles");+        }+        Ok(())+    }++    pub fn serialize(&self) -> Vec<u8> {+        let mut out = Vec::with_capacity(HEADER_LEN);+        out.extend_from_slice(MAGIC);+        out.push(FORMAT_VERSION);+        out.extend_from_slice(&(HEADER_LEN as u16).to_le_bytes());+        out.extend_from_slice(&self.flags.to_le_bytes());+        out.push(self.compression);+        out.push(self.layer_count);+        out.push(self.min_zoom);+        out.push(self.max_zoom);+        out.extend_from_slice(&self.build_id.to_le_bytes());+        out.extend_from_slice(&self.file_len.to_le_bytes());+        out.extend_from_slice(&self.dict_offset.to_le_bytes());+        out.extend_from_slice(&self.dict_len.to_le_bytes());+        out.extend_from_slice(&self.leaf_entry_capacity.to_le_bytes());+        out.extend_from_slice(&self.root_offset.to_le_bytes());+        out.extend_from_slice(&self.root_len.to_le_bytes());+        out.extend_from_slice(&self.leaf_count.to_le_bytes());+        out.extend_from_slice(&self.leaf_offset.to_le_bytes());+        out.extend_from_slice(&self.leaf_len.to_le_bytes());+        out.extend_from_slice(&0u32.to_le_bytes());+        out.extend_from_slice(&self.data_offset.to_le_bytes());+        out.extend_from_slice(&self.data_len.to_le_bytes());+        out.extend_from_slice(&self.tiles_addressed.to_le_bytes());+        out.extend_from_slice(&self.bodies_written.to_le_bytes());+        for v in [self.min_lon_e7, self.min_lat_e7, self.max_lon_e7, self.max_lat_e7] {+            out.extend_from_slice(&v.to_le_bytes());+        }+        debug_assert_eq!(out.len(), HEADER_LEN);+        out+    }+}++#[cfg(test)]+mod tests {+    use super::*;++    /// A header naming sections that do not overlap, in a file big enough to hold them.+    fn plausible() -> Header {+        Header {+            flags: FLAG_BODIES_COMPRESSED,+            compression: COMPRESSION_DEFLATE,+            layer_count: 7,+            min_zoom: 0,+            max_zoom: 14,+            build_id: 0x0123_4567_89AB_CDEF,+            file_len: 4096,+            dict_offset: 128,+            dict_len: 512,+            leaf_entry_capacity: 4096,+            root_offset: 640,+            root_len: 64,+            leaf_count: 2,+            leaf_offset: 704,+            leaf_len: 32,+            data_offset: 736,+            data_len: 3360,+            tiles_addressed: 9,+            bodies_written: 4,+            min_lon_e7: -1_242_000_000,+            min_lat_e7: 324_000_000,+            max_lon_e7: -1_140_000_000,+            max_lat_e7: 420_000_000,+        }+    }++    #[test]+    fn a_header_round_trips_through_its_own_bytes() {+        let header = plausible();+        let bytes = header.serialize();+        assert_eq!(bytes.len(), HEADER_LEN, "the header is a fixed 128 bytes");+        assert_eq!(Header::parse(&bytes).expect("should parse"), header);+    }++    #[test]+    fn every_u64_field_is_eight_byte_aligned() {+        // So a reader may take them as aligned loads out of a zero-copy prefix slice.+        for offset in [16, 24, 32, 48, 64, 80, 88, 96, 104] {+            assert_eq!(offset % 8, 0, "a u64 sits at byte {offset}");+        }+    }++    #[test]+    fn a_header_with_trailing_bytes_still_parses() {+        // It arrives inside a 16 KiB prefix, never on its own.+        let mut bytes = plausible().serialize();+        bytes.extend_from_slice(&[0xAB; 1024]);+        assert!(Header::parse(&bytes).is_ok());+    }++    #[test]+    fn a_truncated_or_foreign_header_is_refused() {+        let bytes = plausible().serialize();+        assert!(Header::parse(&bytes[..HEADER_LEN - 1]).is_err(), "short");+        let mut wrong_magic = bytes.clone();+        wrong_magic[0] = b'P';+        assert!(Header::parse(&wrong_magic).is_err(), "PMTiles is not this format");+        let mut wrong_version = bytes.clone();+        wrong_version[7] = FORMAT_VERSION + 1;+        assert!(Header::parse(&wrong_version).is_err(), "a newer format");+    }++    /// An unknown flag means the writer said something about the bodies this reader would+    /// ignore, and every flag here changes how a body must be handled.+    #[test]+    fn an_unknown_flag_or_a_dirty_reserved_word_is_refused() {+        let mut bytes = plausible().serialize();+        bytes[11] = 0x80;+        assert!(Header::parse(&bytes).is_err(), "an unknown flag");+        let mut bytes = plausible().serialize();+        bytes[76] = 1;+        assert!(Header::parse(&bytes).is_err(), "a reserved word a later version may claim");+    }++    /// Every later read takes its length from a header field, so a header that names an+    /// impossible section has to fail here rather than somewhere uninformative.+    #[test]+    fn a_header_whose_sections_do_not_fit_the_file_is_refused() {+        let cases: &[(&str, fn(&mut Header))] = &[+            ("data past the end", |h| h.data_len = 1 << 40),+            ("a section inside the header", |h| h.dict_offset = 8),+            ("the dictionary over the root", |h| h.dict_len = 600),+            ("a file shorter than the header", |h| h.file_len = 8),+            ("a zoom range inverted", |h| h.min_zoom = 15),+            ("a zoom past the renderer's maximum", |h| h.max_zoom = 30),+            ("a leaf capacity that is not a power of two", |h| h.leaf_entry_capacity = 3000),+            ("no leaves at all", |h| h.leaf_count = 0),+            ("an unknown compression", |h| h.compression = 9),+            ("more bodies than addressed tiles", |h| h.bodies_written = 10),+            ("a root that is not whole entries", |h| h.root_len = 63),+            ("a flag that contradicts the compression byte", |h| {+                h.compression = COMPRESSION_NONE;+            }),+        ];+        for (what, break_it) in cases {+            let mut header = plausible();+            break_it(&mut header);+            assert!(Header::parse(&header.serialize()).is_err(), "{what} should be refused");+        }+    }++    #[test]+    fn an_offset_length_pair_cannot_overflow_into_looking_valid() {+        let mut header = plausible();+        header.data_offset = u64::MAX - 8;+        header.data_len = 64;+        assert!(Header::parse(&header.serialize()).is_err(), "the end wraps");+    }+}
library/tilecodec/src/main/rust/src/mamaps/index.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/index.rs b/library/tilecodec/src/main/rust/src/mamaps/index.rsnew file mode 100644index 0000000000..7b2bb07b46--- /dev/null+++ b/library/tilecodec/src/main/rust/src/mamaps/index.rs@@ -0,0 +1,350 @@+//! The two-level index: a root of fixed-stride entries, each pointing at one leaf.+//!+//! Both levels are **uncompressed and fixed stride**, which is the whole design. The root can+//! then be used straight out of the bytes a reader already fetched to read the header, with no+//! inflate step and no sequential decode — and a leaf can be binary-searched, because+//! [`LeafEntry::tile_id_lo`] is absolute within its leaf rather than a delta from the entry+//! before it.+//!+//! # The prefix budget+//!+//! A reader opens with one 16 KiB read. Header (128) plus dictionary (under 1 KiB) leaves about+//! 15 KiB, which is 476 root entries; at 4096 tiles each that addresses 1.95 M tiles without a+//! second request. California needs under 100 leaves. Past 1.95 M,+//! [`Header::leaf_entry_capacity`](super::header::Header::leaf_entry_capacity) doubles rather+//! than the root growing — the same trick `pmtiles::split_entries` uses, and for the same reason.+//!+//! [`super::write`] **asserts** the budget. A root that does not fit is a build failure, never a+//! silent third round trip charged to every reader forever.+//!+//! # Addressing+//!+//! Tile ids are `pmtiles::tile_id` unchanged: space-filling, zoom-major and monotonic. Those are+//! exactly the three properties the generator's spill bucketing and pyramid ranges already depend+//! on, so inventing a curve here would buy nothing and break that coupling.++use crate::proto::{err, Result};++pub const ROOT_ENTRY_LEN: usize = 32;+pub const LEAF_ENTRY_LEN: usize = 16;++/// One leaf's worth of the tile-id space.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct RootEntry {+    /// The first tile id this leaf covers. Ascending across the root, so it binary-searches.+    pub base_tile_id: u64,+    /// Where the leaf's entries start, relative to+    /// [`Header::leaf_offset`](super::header::Header::leaf_offset).+    pub leaf_offset: u64,+    /// What every [`LeafEntry::offset_delta`] in this leaf is relative to, itself relative to+    /// [`Header::data_offset`](super::header::Header::data_offset).+    ///+    /// Two levels of relative offset so a leaf entry's own offset field stays 32-bit: a planet+    /// data section is past 4 GiB, but one leaf's 4096 bodies are not.+    pub base_data_offset: u64,+    pub leaf_entry_count: u32,+}++/// One tile, or a run of consecutive tiles that share a body.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct LeafEntry {+    /// This entry's first tile id, **less its leaf's `base_tile_id`**.+    ///+    /// Absolute within the leaf rather than a delta from the previous entry, so a lookup is a+    /// binary search rather than a walk from the front. `u32` bounds a leaf's id span; the writer+    /// asserts and splits rather than leaving that as a panic waiting past z15.+    pub tile_id_lo: u32,+    /// How many consecutive tile ids share this body. Never zero.+    ///+    /// What makes ocean and empty tiles nearly free: on the planet archive, run-length and+    /// content dedup together collapse 1.57 M addressed tiles to 1.03 M stored bodies.+    pub run_length: u32,+    /// Where the body starts, relative to this leaf's `base_data_offset`.+    pub offset_delta: u32,+    /// The body's stored length — compressed, if the header says bodies are.+    pub length: u32,+}++pub fn serialize_root(entries: &[RootEntry]) -> Vec<u8> {+    let mut out = Vec::with_capacity(entries.len() * ROOT_ENTRY_LEN);+    for e in entries {+        out.extend_from_slice(&e.base_tile_id.to_le_bytes());+        out.extend_from_slice(&e.leaf_offset.to_le_bytes());+        out.extend_from_slice(&e.base_data_offset.to_le_bytes());+        out.extend_from_slice(&e.leaf_entry_count.to_le_bytes());+        out.extend_from_slice(&0u32.to_le_bytes());+    }+    debug_assert_eq!(out.len(), entries.len() * ROOT_ENTRY_LEN);+    out+}++pub fn parse_root(buf: &[u8]) -> Result<Vec<RootEntry>> {+    if buf.len() % ROOT_ENTRY_LEN != 0 {+        return err(format!(+            "a .mamaps root index of {} bytes is not a whole number of {ROOT_ENTRY_LEN} byte entries",+            buf.len(),+        ));+    }+    let mut out = Vec::with_capacity(buf.len() / ROOT_ENTRY_LEN);+    for chunk in buf.chunks_exact(ROOT_ENTRY_LEN) {+        if u32::from_le_bytes([chunk[28], chunk[29], chunk[30], chunk[31]]) != 0 {+            return err("a .mamaps root entry has a non-zero reserved word");+        }+        out.push(RootEntry {+            base_tile_id: u64_at(chunk, 0),+            leaf_offset: u64_at(chunk, 8),+            base_data_offset: u64_at(chunk, 16),+            leaf_entry_count: u32::from_le_bytes([chunk[24], chunk[25], chunk[26], chunk[27]]),+        });+    }+    // Ascending, or the binary search below would silently return the wrong leaf rather than+    // failing. Checked once on open, not per lookup.+    if out.windows(2).any(|pair| pair[1].base_tile_id <= pair[0].base_tile_id) {+        return err("a .mamaps root index is not ordered by tile id");+    }+    Ok(out)+}++pub fn serialize_leaf(entries: &[LeafEntry]) -> Vec<u8> {+    let mut out = Vec::with_capacity(entries.len() * LEAF_ENTRY_LEN);+    for e in entries {+        out.extend_from_slice(&e.tile_id_lo.to_le_bytes());+        out.extend_from_slice(&e.run_length.to_le_bytes());+        out.extend_from_slice(&e.offset_delta.to_le_bytes());+        out.extend_from_slice(&e.length.to_le_bytes());+    }+    out+}++pub fn parse_leaf(buf: &[u8]) -> Result<Vec<LeafEntry>> {+    if buf.len() % LEAF_ENTRY_LEN != 0 {+        return err(format!(+            "a .mamaps leaf of {} bytes is not a whole number of {LEAF_ENTRY_LEN} byte entries",+            buf.len(),+        ));+    }+    let mut out = Vec::with_capacity(buf.len() / LEAF_ENTRY_LEN);+    for chunk in buf.chunks_exact(LEAF_ENTRY_LEN) {+        let at = |o: usize| u32::from_le_bytes([chunk[o], chunk[o + 1], chunk[o + 2], chunk[o + 3]]);+        let entry = LeafEntry {+            tile_id_lo: at(0),+            run_length: at(4),+            offset_delta: at(8),+            length: at(12),+        };+        // A zero run covers no tile, so it could never be found — but it would also make the+        // `tile_id_lo + run_length` bound below reject the entry's own first tile.+        if entry.run_length == 0 {+            return err("a .mamaps leaf entry covers zero tiles");+        }+        out.push(entry);+    }+    if out.windows(2).any(|pair| pair[1].tile_id_lo <= pair[0].tile_id_lo) {+        return err("a .mamaps leaf is not ordered by tile id");+    }+    Ok(out)+}++fn u64_at(buf: &[u8], o: usize) -> u64 {+    u64::from_le_bytes([+        buf[o],+        buf[o + 1],+        buf[o + 2],+        buf[o + 3],+        buf[o + 4],+        buf[o + 5],+        buf[o + 6],+        buf[o + 7],+    ])+}++/// The leaf covering `want`: the last entry whose `base_tile_id <= want`.+///+/// No upper bound check, because the root partitions the whole id space — the last leaf owns+/// everything past its base, and whether the tile is actually *in* it is the leaf's answer.+pub fn find_leaf(root: &[RootEntry], want: u64) -> Option<&RootEntry> {+    match root.binary_search_by(|e| e.base_tile_id.cmp(&want)) {+        Ok(i) => root.get(i),+        Err(0) => None,+        Err(i) => root.get(i - 1),+    }+}++/// The entry covering `want`, which is a leaf-relative id.+pub fn find_tile(leaf: &[LeafEntry], want: u32) -> Option<&LeafEntry> {+    let entry = match leaf.binary_search_by(|e| e.tile_id_lo.cmp(&want)) {+        Ok(i) => leaf.get(i)?,+        Err(0) => return None,+        Err(i) => leaf.get(i - 1)?,+    };+    // Inside the run, or the archive simply does not hold this tile — which is the ordinary+    // answer anywhere off the edge of its coverage, not an error.+    (want - entry.tile_id_lo < entry.run_length).then_some(entry)+}++/// Does `span` fit the `u32` a [`LeafEntry::tile_id_lo`] carries?+///+/// Asked by the writer before it commits to a leaf boundary. A leaf covering a wide stretch of a+/// deep zoom can span more than 4 G ids, and finding that out by truncation would put a body at+/// the wrong tile with no diagnostic at all.+pub fn span_fits(span: u64) -> bool {+    span <= u32::MAX as u64+}++#[cfg(test)]+mod tests {+    use super::*;+    use crate::pmtiles::{tile_id, tile_zxy, zoom_base};++    fn root_of(bases: &[u64]) -> Vec<RootEntry> {+        bases+            .iter()+            .enumerate()+            .map(|(i, base)| RootEntry {+                base_tile_id: *base,+                leaf_offset: (i * 64) as u64,+                base_data_offset: (i * 1000) as u64,+                leaf_entry_count: 4,+            })+            .collect()+    }++    #[test]+    fn a_root_entry_is_thirty_two_bytes_and_a_leaf_entry_sixteen() {+        // Fixed stride is what lets the root be used straight out of the opening prefix.+        assert_eq!(serialize_root(&root_of(&[0, 5])).len(), 2 * ROOT_ENTRY_LEN);+        assert_eq!(+            serialize_leaf(&[LeafEntry {+                tile_id_lo: 0,+                run_length: 1,+                offset_delta: 0,+                length: 9,+            }])+            .len(),+            LEAF_ENTRY_LEN,+        );+    }++    #[test]+    fn both_levels_round_trip() {+        let root = root_of(&[0, 4096, 8192]);+        assert_eq!(parse_root(&serialize_root(&root)).expect("root"), root);+        let leaf = vec![+            LeafEntry { tile_id_lo: 0, run_length: 3, offset_delta: 0, length: 40 },+            LeafEntry { tile_id_lo: 3, run_length: 1, offset_delta: 40, length: 12 },+            LeafEntry { tile_id_lo: 9, run_length: 2, offset_delta: 52, length: 7 },+        ];+        assert_eq!(parse_leaf(&serialize_leaf(&leaf)).expect("leaf"), leaf);+    }++    /// **Invariant 1 of the plan's verification list.** Header plus dictionary plus root must fit+    /// the one 16 KiB read a reader opens with, at a scale well past California.+    #[test]+    fn a_root_addressing_two_million_tiles_fits_the_opening_prefix() {+        let prefix = crate::stream::OPEN_PREFIX_BYTES as usize;+        let dictionary = super::super::dict::Dictionary::schema().serialize().len();+        let budget = prefix - super::super::header::HEADER_LEN - dictionary;+        let entries = budget / ROOT_ENTRY_LEN;+        assert!(entries >= 476, "only {entries} root entries fit the prefix");+        assert!(+            entries * 4096 >= 1_950_000,+            "{} tiles addressable in one request",+            entries * 4096,+        );+        // And the bytes really are that size, not merely the arithmetic.+        let root = root_of(&(0..entries as u64).map(|i| i * 4096).collect::<Vec<_>>());+        let bytes = serialize_root(&root);+        assert!(+            super::super::header::HEADER_LEN + dictionary + bytes.len() <= prefix,+            "header + dictionary + {} root entries is {} bytes",+            entries,+            super::super::header::HEADER_LEN + dictionary + bytes.len(),+        );+    }++    #[test]+    fn a_lookup_finds_the_leaf_that_covers_a_tile() {+        let root = root_of(&[100, 200, 300]);+        assert_eq!(find_leaf(&root, 99), None, "before the first leaf");+        assert_eq!(find_leaf(&root, 100).map(|e| e.base_tile_id), Some(100), "exactly the base");+        assert_eq!(find_leaf(&root, 150).map(|e| e.base_tile_id), Some(100));+        assert_eq!(find_leaf(&root, 200).map(|e| e.base_tile_id), Some(200));+        // The last leaf owns everything past its base; whether the tile is in it is its answer.+        assert_eq!(find_leaf(&root, 9_999).map(|e| e.base_tile_id), Some(300));+        assert_eq!(find_leaf(&[], 1), None);+    }++    #[test]+    fn a_run_covers_its_whole_span_and_nothing_past_it() {+        let leaf = vec![+            LeafEntry { tile_id_lo: 10, run_length: 4, offset_delta: 0, length: 8 },+            LeafEntry { tile_id_lo: 20, run_length: 1, offset_delta: 8, length: 8 },+        ];+        assert!(find_tile(&leaf, 9).is_none(), "before the first entry");+        for want in 10..14 {+            assert_eq!(find_tile(&leaf, want).map(|e| e.tile_id_lo), Some(10), "{want} is in the run");+        }+        // A hole between the runs is the ordinary answer off the edge of coverage.+        for want in [14, 15, 19, 21, 5000] {+            assert!(find_tile(&leaf, want).is_none(), "{want} is not stored");+        }+        assert_eq!(find_tile(&leaf, 20).map(|e| e.tile_id_lo), Some(20));+    }++    #[test]+    fn an_unordered_or_impossible_index_is_refused() {+        let mut root = root_of(&[0, 4096]);+        root.swap(0, 1);+        assert!(parse_root(&serialize_root(&root)).is_err(), "descending bases");+        let repeated = root_of(&[7, 7]);+        assert!(parse_root(&serialize_root(&repeated)).is_err(), "two leaves at one base");+        assert!(parse_root(&[0u8; ROOT_ENTRY_LEN - 1]).is_err(), "a partial entry");++        let leaf = vec![+            LeafEntry { tile_id_lo: 5, run_length: 1, offset_delta: 0, length: 1 },+            LeafEntry { tile_id_lo: 5, run_length: 1, offset_delta: 1, length: 1 },+        ];+        assert!(parse_leaf(&serialize_leaf(&leaf)).is_err(), "two entries at one id");+        let empty_run = vec![LeafEntry { tile_id_lo: 0, run_length: 0, offset_delta: 0, length: 1 }];+        assert!(parse_leaf(&serialize_leaf(&empty_run)).is_err(), "a run covering no tile");+        assert!(parse_leaf(&[0u8; LEAF_ENTRY_LEN + 1]).is_err(), "a partial entry");+    }++    #[test]+    fn a_reserved_word_a_later_version_may_claim_is_checked() {+        let mut bytes = serialize_root(&root_of(&[0]));+        bytes[28] = 1;+        assert!(parse_root(&bytes).is_err());+    }++    /// **Invariant 4.** The generator's spill buckets and its per-zoom passes both key on+    /// `zoom_base(z)..zoom_base(z + 1)`, so a leaf boundary landing inside a zoom is fine but the+    /// ids themselves must stay zoom-major and monotonic. This pins the property this index+    /// inherits rather than re-derives.+    #[test]+    fn tile_ids_stay_zoom_major_and_monotonic_across_the_archives_range() {+        for z in 0..=14u8 {+            let (lo, hi) = (zoom_base(z), zoom_base(z + 1));+            let n = 1u64 << z;+            for (x, y) in [(0, 0), (n / 2, n / 2), (n - 1, n - 1)] {+                let id = tile_id(z, x, y);+                assert!((lo..hi).contains(&id), "z{z}/{x}/{y} is outside its zoom's range");+                assert_eq!(tile_zxy(id), (z, x, y), "the id does not round trip");+            }+        }+        // And every zoom's whole range precedes the next, which is what makes a root ordered by+        // tile id also ordered by zoom.+        for z in 0..14u8 {+            assert!(zoom_base(z + 1) > zoom_base(z));+        }+    }++    #[test]+    fn a_leaf_span_wider_than_a_u32_is_rejected_rather_than_truncated() {+        assert!(span_fits(u32::MAX as u64));+        assert!(!span_fits(u32::MAX as u64 + 1));+        // Real: one z15 leaf covering a wide stretch is nowhere near this, but a z16 archive+        // built with a large capacity could be, and truncation would put a body at another tile.+        assert!(span_fits(4096));+    }+}
library/tilecodec/src/main/rust/src/mamaps/mod.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/mod.rs b/library/tilecodec/src/main/rust/src/mamaps/mod.rsnew file mode 100644index 0000000000..17c93580f0--- /dev/null+++ b/library/tilecodec/src/main/rust/src/mamaps/mod.rs@@ -0,0 +1,398 @@+//! `.mamaps` — the container the Vulkan renderer reads, shaped like what it draws.+//!+//! # Why not MVT inside PMTiles+//!+//! Because almost none of it is used. An MVT tile is protobuf varints, a per-tile string table and+//! an arbitrary key/value property map per feature; the renderer reads exactly **one** property+//! (`kind`, as a `String`), handles two of the four geometry types, and decodes points only to+//! throw them away. Everything else is bytes every device downloads, inflates and discards.+//!+//! So: geometry only, pre-clipped, pre-simplified, attributes interned to integers, flat+//! little-endian structs. Not pre-tessellated — triangles would bake the style's layer set into the+//! data, and which layer a feature belongs to is a paint decision.+//!+//! # The sections+//!+//! ```text+//! [header 128][dictionary][root index][leaf indices][tile data]+//! ```+//!+//! Order on disk is **not** part of the format. Every section is located only by a header-declared+//! offset, because the real 137 GB PMTiles archive puts its leaves after its tile data and a reader+//! that assumed layout would address the wrong bytes.+//!+//! * [`header`] — 128 fixed bytes, including the `build_id` that makes republishing under an+//!   `immutable` URL safe.+//! * [`dict`] — layer names and the `kind`/`kind_detail` tables, **pre-seeded from a constant+//!   schema table** so an id never shifts between builds.+//! * [`index`] — a fixed-stride root and fixed-stride leaves, uncompressed so the root is usable+//!   straight out of the opening prefix.+//! * [`body`] — one per tile, with every layer inside it.+//! * [`read`] — open in one request, a warm tile in one, a cold tile in two, never three.+//! * `write` — the builder, behind the `write` feature.+//!+//! # What the `write` feature is for+//!+//! Android reads archives; it never writes one. Gating the builder keeps the interner and the+//! DEFLATE *encoder* out of the `aarch64-linux-android` cdylib, and — more usefully — makes it a+//! compile error rather than a review comment if the read path ever grows a dependency on the write+//! path.++pub mod body;+pub mod dict;+pub mod header;+pub mod index;+pub mod read;++#[cfg(feature = "write")]+pub mod write;++pub use body::Body;+pub use dict::Dictionary;+pub use header::Header;+pub use read::MamapsArchive;++#[cfg(all(test, feature = "write"))]+mod tests {+    use super::*;+    use crate::mamaps::body::{Feature, Layer, Part, DEFAULT_EXTENT, GEOM_LINE, WINDING_OUTER};+    use crate::mamaps::write::{Options, StreamWriter};+    use crate::pmtiles::{tile_id, zoom_base};+    use crate::proto::Result;+    use crate::stream::{RangeReader, OPEN_PREFIX_BYTES};+    use std::cell::RefCell;++    /// A [`RangeReader`] over bytes in memory that logs every range asked for, so a test can assert+    /// on the **number of round trips** as well as on the bytes. The same shape `stream.rs` uses.+    struct Counting {+        bytes: Vec<u8>,+        requests: RefCell<Vec<(u64, u32)>>,+    }++    impl RangeReader for Counting {+        fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {+            self.requests.borrow_mut().push((offset, length));+            if offset >= self.bytes.len() as u64 {+                return Ok(Vec::new());+            }+            // Short rather than failing, as the trait specifies.+            let end = (offset + length as u64).min(self.bytes.len() as u64);+            Ok(self.bytes[offset as usize..end as usize].to_vec())+        }+    }++    /// A one-line body whose contents depend on `seed`, so two tiles differ unless asked not to.+    fn body_for(seed: i16) -> Body {+        let mut roads = Layer::new(dict::LAYER_ROADS);+        roads.features.push(Feature {+            kind: 45,+            kind_detail: dict::NONE,+            geom_type: GEOM_LINE,+            flags: 0,+            parts_offset: 0,+            part_count: 1,+        });+        roads.parts.push(Part { coord_start: 0, point_count: 2, winding: WINDING_OUTER });+        roads.coords = vec![(0, 0), (seed, seed)];+        Body { extent: DEFAULT_EXTENT, layers: vec![roads] }+    }++    /// An archive of `(z, x, y, seed)` tiles, fed in ascending id order as the writer requires.+    fn archive(tiles: &[(u8, u64, u64, i16)], options: Options) -> Vec<u8> {+        let mut rows: Vec<(u64, i16)> =+            tiles.iter().map(|(z, x, y, seed)| (tile_id(*z, *x, *y), *seed)).collect();+        rows.sort_by_key(|(id, _)| *id);+        let mut writer = StreamWriter::new(options).expect("options");+        for (id, seed) in rows {+            writer.append(id, &body_for(seed)).expect("append");+        }+        writer.finish().expect("finish")+    }++    fn open(bytes: Vec<u8>) -> MamapsArchive<Counting> {+        MamapsArchive::open(Counting { bytes, requests: RefCell::new(Vec::new()) }).expect("open")+    }++    #[test]+    fn a_tile_written_reads_back_exactly() {+        let bytes = archive(&[(0, 0, 0, 100), (1, 0, 0, 200), (1, 1, 1, 300)], Options::default());+        let mut a = open(bytes);+        for (z, x, y, seed) in [(0u8, 0u32, 0u32, 100i16), (1, 0, 0, 200), (1, 1, 1, 300)] {+            let tile = a.tile(z, x, y).expect("read").expect("present");+            assert_eq!(tile, body_for(seed), "z{z}/{x}/{y}");+        }+        // A tile the archive does not hold is `None`, which is the ordinary answer off the edge of+        // coverage rather than a fault.+        assert!(a.tile(1, 0, 1).expect("read").is_none());+        assert!(a.tile(9, 0, 0).expect("read").is_none(), "past max_zoom");+        assert!(a.tile(1, 9, 9).expect("read").is_none(), "off the world");+    }++    #[test]+    fn a_tile_reads_back_uncompressed_too() {+        let options = Options { compress: false, ..Options::default() };+        let mut a = open(archive(&[(0, 0, 0, 7)], options));+        assert!(!a.header.compressed());+        assert_eq!(a.tile(0, 0, 0).expect("read").expect("present"), body_for(7));+    }++    /// **Invariant 2 of the plan's verification list.** The whole container shape exists to hold+    /// this: open is one request, a warm tile is one, a cold tile is two, and nothing is ever+    /// three.+    #[test]+    fn open_is_one_request_a_warm_tile_one_a_cold_tile_two_and_never_three() {+        // Enough tiles to need more than one leaf, so a cold tile really does have a leaf to+        // fetch. Sixteen entries per leaf: z0 plus all of z1..z3 is 85 tiles, so six leaves.+        let mut tiles: Vec<(u8, u64, u64, i16)> = Vec::new();+        for z in 0..=3u8 {+            for x in 0..(1u64 << z) {+                for y in 0..(1u64 << z) {+                    tiles.push((z, x, y, (tile_id(z, x, y) + 1) as i16));+                }+            }+        }+        let options = Options { leaf_entry_capacity: 16, ..Options::default() };+        let mut a = open(archive(&tiles, options));+        assert!(a.header.leaf_count > 1, "this test needs several leaves");+        assert_eq!(+            a.reader.requests.borrow().as_slice(),+            &[(0, OPEN_PREFIX_BYTES)],+            "a cold open is one request: header, dictionary and root all live in the prefix",+        );++        let count = |a: &MamapsArchive<Counting>| a.reader.requests.borrow().len();+        a.reader.requests.borrow_mut().clear();+        assert!(a.tile(3, 0, 0).expect("read").is_some());+        assert_eq!(count(&a), 2, "a cold tile is a leaf plus a body");++        a.reader.requests.borrow_mut().clear();+        assert!(a.tile(3, 1, 1).expect("read").is_some());+        assert_eq!(count(&a), 1, "its leaf is now cached, so only the body");++        // And nothing anywhere costs three, at any zoom, warm or cold.+        for (z, x, y, _) in &tiles {+            a.reader.requests.borrow_mut().clear();+            let _ = a.tile(*z, *x as u32, *y as u32).expect("read");+            let n = count(&a);+            assert!(n <= 2, "z{z}/{x}/{y} cost {n} requests");+        }+    }++    /// **Invariant 3.** Every read's length comes from a header or entry field, so the request log+    /// can be checked against the fields rather than against a sentinel or a guess. A read of the+    /// wrong length does not merely fail: `tile::cache` stores a `206` whose body length equals the+    /// request, so it poisons that range for every later read.+    #[test]+    fn every_read_takes_its_length_from_a_declared_field() {+        let mut a = open(archive(&[(0, 0, 0, 1), (1, 0, 0, 2)], Options::default()));+        let (leaf_len, leaf_offset) = (a.header.leaf_len, a.header.leaf_offset);+        a.reader.requests.borrow_mut().clear();+        assert!(a.tile(1, 0, 0).expect("read").is_some());+        let requests = a.reader.requests.borrow().clone();+        assert_eq!(requests.len(), 2);+        // The leaf: offset and length both from the root entry and the header.+        assert_eq!(requests[0].0, leaf_offset, "the leaf is where the header says");+        assert!(requests[0].1 as u64 <= leaf_len as u64, "and no longer than the section it is in");+        assert_eq!(+            requests[0].1 as usize % index::LEAF_ENTRY_LEN,+            0,+            "a leaf read is a whole number of entries",+        );+        // The body: inside the data section, at a length from its own leaf entry.+        assert!(requests[1].0 >= a.header.data_offset);+        assert!(requests[1].0 + requests[1].1 as u64 <= a.header.data_offset + a.header.data_len);+    }++    /// A short reply must fail loudly rather than be decoded or cached.+    #[test]+    fn a_range_that_comes_back_short_is_refused() {+        let full = archive(&[(0, 0, 0, 1), (1, 0, 0, 2)], Options::default());+        let truncated = full[..full.len() - 8].to_vec();+        let mut a =+            MamapsArchive::open(Counting { bytes: truncated, requests: RefCell::new(Vec::new()) })+                .expect("the prefix is intact, so open still works");+        let failure = a.tile(1, 0, 0).expect_err("the last body is cut off");+        assert!(failure.0.contains("got"), "{}", failure.0);+    }++    /// **What makes ocean and empty tiles nearly free.** Consecutive identical bodies collapse to+    /// one entry *and* one body; non-consecutive ones share the body through the content bucket.+    #[test]+    fn identical_tiles_share_one_body_whether_or_not_they_are_consecutive() {+        // Every z1 tile the same, and z0 different, so the run cannot swallow everything.+        let bytes = archive(&[(0, 0, 0, 9), (1, 0, 0, 5), (1, 1, 0, 5), (1, 1, 1, 5), (1, 0, 1, 5)], Options::default());+        let header = Header::parse(&bytes).expect("header");+        assert_eq!(header.tiles_addressed, 5);+        assert_eq!(header.bodies_written, 2, "one distinct z1 body plus z0's");+        assert!(header.flags & header::FLAG_RUN_LENGTH_PRESENT != 0, "a run was used");+        // And all four still read back.+        let mut a = open(bytes);+        for (x, y) in [(0u32, 0u32), (1, 0), (1, 1), (0, 1)] {+            assert_eq!(a.tile(1, x, y).expect("read").expect("present"), body_for(5));+        }+        assert_eq!(a.tile(0, 0, 0).expect("read").expect("present"), body_for(9));+    }++    /// Content dedup across a leaf boundary, which is the case that made a leaf's+    /// `base_data_offset` the *minimum* of its chunk rather than its first entry: a tile in a later+    /// leaf can point at a body written for an earlier one.+    #[test]+    fn a_tile_can_share_a_body_written_for_an_earlier_leaf() {+        // Ids ascend, seeds alternate, so no run ever forms and the repeats are all non-adjacent.+        let mut tiles: Vec<(u8, u64, u64, i16)> = Vec::new();+        for x in 0..8u64 {+            for y in 0..8u64 {+                tiles.push((3, x, y, if (x + y) % 2 == 0 { 11 } else { 22 }));+            }+        }+        let options = Options { leaf_entry_capacity: 4, ..Options::default() };+        let bytes = archive(&tiles, options);+        let header = Header::parse(&bytes).expect("header");+        assert_eq!(header.tiles_addressed, 64);+        assert!(header.bodies_written <= 8, "{} bodies for two shapes", header.bodies_written);+        assert!(header.leaf_count > 4, "this test needs the repeats to cross leaves");+        let mut a = open(bytes);+        for (z, x, y, seed) in &tiles {+            let tile = a.tile(*z, *x as u32, *y as u32).expect("read").expect("present");+            assert_eq!(tile, body_for(*seed), "z{z}/{x}/{y}");+        }+    }++    /// **Invariant 5.** Byte-identical output for identical input, twice over. Nothing in the emit+    /// path iterates a hash map: the dictionary is a constant table, layers are sorted by id and+    /// the content bucket is only ever probed.+    #[test]+    fn two_builds_of_the_same_input_are_byte_identical() {+        let tiles: Vec<(u8, u64, u64, i16)> =+            (0..4u64).flat_map(|x| (0..4u64).map(move |y| (2u8, x, y, (x * 4 + y) as i16))).collect();+        let first = archive(&tiles, Options::default());+        let second = archive(&tiles, Options::default());+        assert_eq!(first, second);+        // And feeding the same tiles in a different order gives the same file, because `archive`+        // sorts by id and the writer's output depends on nothing else. This is what stands in for+        // "identical at 1/2/3/32 threads": a threaded producer differs only in arrival order.+        let mut shuffled = tiles.clone();+        shuffled.reverse();+        assert_eq!(first, archive(&shuffled, Options::default()));+    }++    /// The dictionary is the same bytes whatever the archive covers, which is what makes a diff of+    /// two archives a diff of their tiles.+    #[test]+    fn a_small_archive_has_the_same_dictionary_as_a_large_one() {+        let small = archive(&[(0, 0, 0, 1)], Options::default());+        let large: Vec<(u8, u64, u64, i16)> =+            (0..8u64).flat_map(|x| (0..8u64).map(move |y| (3u8, x, y, (x * 8 + y) as i16))).collect();+        let large = archive(&large, Options::default());+        let dict_of = |bytes: &[u8]| {+            let h = Header::parse(bytes).expect("header");+            bytes[h.dict_offset as usize..(h.dict_offset + h.dict_len as u64) as usize].to_vec()+        };+        assert_eq!(dict_of(&small), dict_of(&large));+        assert_eq!(dict_of(&small), Dictionary::schema().serialize());+    }++    /// **Invariant 4.** Ids must ascend, and the writer refuses rather than sorting: the index is+    /// built as bodies arrive, and a caller feeding them out of order is a caller whose bucketing+    /// broke.+    #[test]+    fn appending_out_of_order_or_outside_the_zoom_range_is_refused() {+        let mut writer = StreamWriter::new(Options::default()).expect("options");+        writer.append(tile_id(1, 1, 1), &body_for(1)).expect("first");+        assert!(writer.append(tile_id(0, 0, 0), &body_for(2)).is_err(), "descending");+        assert!(writer.append(tile_id(1, 1, 1), &body_for(2)).is_err(), "repeated");++        let options = Options { min_zoom: 2, max_zoom: 3, ..Options::default() };+        let mut writer = StreamWriter::new(options).expect("options");+        assert!(writer.append(tile_id(0, 0, 0), &body_for(1)).is_err(), "shallower than min_zoom");+        assert!(writer.append(tile_id(4, 0, 0), &body_for(1)).is_err(), "deeper than max_zoom");+        assert!(writer.append(tile_id(2, 0, 0), &body_for(1)).is_ok());+    }++    /// And the ids the index is built on are the same zoom-major ones the generator's spill buckets+    /// use, so its `zoom_base(z)..zoom_base(z + 1)` ranges are provably untouched by this format.+    #[test]+    fn stored_ids_are_ascending_and_land_in_their_own_zooms_range() {+        let mut tiles: Vec<(u8, u64, u64, i16)> = Vec::new();+        for z in 0..=3u8 {+            for x in 0..(1u64 << z) {+                tiles.push((z, x, 0, (z as i16 + 1) * 10));+            }+        }+        let bytes = archive(&tiles, Options { leaf_entry_capacity: 4, ..Options::default() });+        let stored = read::read_all(&bytes).expect("read_all");+        assert!(stored.windows(2).all(|p| p[1].0 > p[0].0), "ascending across leaves");+        for (id, _, _) in &stored {+            let (z, _, _) = crate::pmtiles::tile_zxy(*id);+            assert!((zoom_base(z)..zoom_base(z + 1)).contains(id), "id {id} is outside z{z}");+        }+        let addressed: u32 = stored.iter().map(|(_, run, _)| run).sum();+        assert_eq!(addressed as usize, tiles.len(), "every tile is addressed exactly once");+    }++    /// **Invariant 1, end to end.** A root that will not fit the opening prefix is a build failure,+    /// and the escape is a bigger leaf rather than a bigger root — so a build that would have cost+    /// every reader a third round trip instead grows its leaves and still opens in one.+    #[test]+    fn a_root_too_large_for_the_prefix_grows_its_leaves_instead() {+        // 4096 z6 tiles at one entry per leaf would need 4096 root entries, which is 128 KiB. The+        // writer must double the capacity until the root fits.+        let tiles: Vec<(u8, u64, u64, i16)> =+            (0..64u64).flat_map(|x| (0..64u64).map(move |y| (6u8, x, y, (x * 64 + y) as i16))).collect();+        let options = Options { leaf_entry_capacity: 1, max_zoom: 6, ..Options::default() };+        let bytes = archive(&tiles, options);+        let header = Header::parse(&bytes).expect("header");+        assert!(header.leaf_entry_capacity > 1, "the capacity grew to {}", header.leaf_entry_capacity);+        let prefix = header::HEADER_LEN as u64 + header.dict_len as u64 + header.root_len as u64;+        assert!(prefix <= OPEN_PREFIX_BYTES as u64, "the prefix is {prefix} bytes");+        // And it still opens in one request and reads back.+        let mut a = open(bytes);+        assert_eq!(a.reader.requests.borrow().len(), 1);+        assert_eq!(a.tile(6, 63, 63).expect("read").expect("present"), body_for(63 * 64 + 63));+    }++    #[test]+    fn an_empty_archive_is_refused_rather_than_written() {+        let writer = StreamWriter::new(Options::default()).expect("options");+        assert!(writer.finish().is_err(), "an archive with no tiles addresses nothing");+    }++    #[test]+    fn a_build_id_survives_the_round_trip_and_is_what_invalidates_a_cache() {+        let options = Options { build_id: 0xDEAD_BEEF_0BAD_F00D, ..Options::default() };+        let a = open(archive(&[(0, 0, 0, 1)], options));+        assert_eq!(a.header.build_id, 0xDEAD_BEEF_0BAD_F00D);+        // Republishing the same tiles under a new id gives a different header and the same data,+        // which is exactly what lets a reader notice without a second request.+        let options = Options { build_id: 1, ..Options::default() };+        let other = archive(&[(0, 0, 0, 1)], options);+        assert_ne!(Header::parse(&other).expect("header").build_id, a.header.build_id);+    }++    #[test]+    fn the_rings_validated_flag_is_carried_so_the_renderer_can_gate_its_repair_pass() {+        let plain = open(archive(&[(0, 0, 0, 1)], Options::default()));+        assert!(!plain.header.rings_validated(), "not claimed unless the generator says so");+        let options = Options { rings_validated: true, ..Options::default() };+        let validated = open(archive(&[(0, 0, 0, 1)], options));+        assert!(validated.header.rings_validated());+    }++    /// An archive written against a different schema table must be refused on open, not rendered+    /// with every kind meaning something else.+    #[test]+    fn an_archive_whose_dictionary_is_not_this_schema_is_refused_on_open() {+        let mut bytes = archive(&[(0, 0, 0, 1)], Options::default());+        let header = Header::parse(&bytes).expect("header");+        // `island` is the first kind name; corrupt one byte of it.+        let at = header.dict_offset as usize;+        let island = bytes[at..].windows(6).position(|w| w == b"island").expect("island") + at;+        bytes[island] = b'X';+        let opened = MamapsArchive::open(Counting { bytes, requests: RefCell::new(Vec::new()) });+        let failure = match opened {+            Ok(_) => panic!("an archive written against another schema should be refused"),+            Err(e) => e,+        };+        assert!(failure.0.contains("disagrees with this build's schema"), "{}", failure.0);+    }+}
library/tilecodec/src/main/rust/src/mamaps/read.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/read.rs b/library/tilecodec/src/main/rust/src/mamaps/read.rsnew file mode 100644index 0000000000..725ae94a21--- /dev/null+++ b/library/tilecodec/src/main/rust/src/mamaps/read.rs@@ -0,0 +1,255 @@+//! Reading a `.mamaps` archive over range requests.+//!+//! The cost contract, which is the reason the container is shaped the way it is:+//!+//! | | requests |+//! |---|---|+//! | open | 1 |+//! | a tile whose leaf is cached | 1 |+//! | a tile whose leaf is not | 2 |+//! | ever | never 3 |+//!+//! Open is one request because the header, the dictionary and the root index all fit inside+//! [`OPEN_PREFIX_BYTES`] and none of the three is compressed, so all three are used straight out+//! of the prefix. Sixteen cached leaves at 4096 entries each address 65 536 tiles with no+//! directory traffic at all, which matches the locality the transport was tuned around.+//!+//! **Every read takes its length from a header or entry field.** No sentinel, no length+//! discovered mid-stream, no read-until-it-looks-done — because the disk cache in `tile::cache`+//! only stores a `206` whose body length equals what was asked for, so a read of the wrong length+//! does not merely fail, it poisons that range for every later read.++use crate::mamaps::body::Body;+use crate::mamaps::dict::Dictionary;+use crate::mamaps::header::{Header, COMPRESSION_DEFLATE, COMPRESSION_NONE, HEADER_LEN};+use crate::mamaps::index::{self, LeafEntry, RootEntry};+use crate::pmtiles::tile_id;+use crate::proto::{err, Error, Result};+use crate::stream::{RangeReader, OPEN_PREFIX_BYTES};++/// How many parsed leaves to keep. Sixteen, matching `stream::StreamArchive`, because the access+/// pattern is the same one: a viewport walks a contiguous stretch of the curve.+const MAX_CACHED_LEAVES: usize = 16;++/// An open archive.+pub struct MamapsArchive<R: RangeReader> {+    /// Reachable from the crate so the request-counting tests in [`super`] can assert on the+    /// number of round trips, which is the contract this whole layout exists to hold.+    pub(crate) reader: R,+    pub header: Header,+    pub dictionary: Dictionary,+    root: Vec<RootEntry>,+    /// `(leaf offset, entries)`, most-recently-used last.+    leaves: Vec<(u64, Vec<LeafEntry>)>,+}++impl<R: RangeReader> MamapsArchive<R> {+    /// 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.+    pub fn open(reader: R) -> 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(),+            ));+        }+        Ok(MamapsArchive { reader, header, dictionary, root, leaves: Vec::new() })+    }++    /// 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.+    pub fn tile(&mut 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 decompressed body bytes for a tile, undecoded.+    pub fn tile_bytes(&mut self, z: u8, x: u32, y: u32) -> Result<Option<Vec<u8>>> {+        if z < self.header.min_zoom || z > self.header.max_zoom || z >= 32 {+            return Ok(None);+        }+        let n = 1u64 << z;+        if x as u64 >= n || y as u64 >= n {+            return Ok(None);+        }+        let want = tile_id(z, x as u64, y as u64);+        let Some(root) = index::find_leaf(&self.root, want).copied() else { return Ok(None) };+        // Ahead of the leaf's base is impossible (the root is ordered), so this only rules out a+        // tile past a `u32` of span, which the writer refuses to produce.+        let Ok(offset) = u32::try_from(want - root.base_tile_id) else { return Ok(None) };++        let leaf = self.leaf(&root)?;+        let Some(entry) = index::find_tile(&leaf, offset).copied() else { return Ok(None) };++        // Every bound from a field, checked before the read rather than after it.+        let at = root.base_data_offset + entry.offset_delta as u64;+        if at + entry.length as u64 > self.header.data_len {+            return err("a .mamaps leaf entry runs past the tile data section");+        }+        let stored = self.exact(self.header.data_offset + at, entry.length, "a tile body")?;+        Ok(Some(decompress(self.header.compression, &stored)?))+    }++    /// The parsed leaf a root entry addresses, from the cache or over the wire.+    fn leaf(&mut self, root: &RootEntry) -> Result<Vec<LeafEntry>> {+        if let Some(position) = self.leaves.iter().position(|(offset, _)| *offset == root.leaf_offset)+        {+            // Move to the back: most-recently-used last.+            let hit = self.leaves.remove(position);+            let entries = hit.1.clone();+            self.leaves.push(hit);+            return Ok(entries);+        }+        let len = root.leaf_entry_count as u64 * index::LEAF_ENTRY_LEN as u64;+        if root.leaf_offset + len > self.header.leaf_len as u64 {+            return err("a .mamaps root entry runs past the leaf section");+        }+        let length = u32::try_from(len)+            .map_err(|_| Error("a .mamaps leaf is larger than a single read".to_string()))?;+        let raw = self.exact(self.header.leaf_offset + root.leaf_offset, length, "a leaf")?;+        let entries = index::parse_leaf(&raw)?;+        if self.leaves.len() >= MAX_CACHED_LEAVES {+            self.leaves.remove(0);+        }+        self.leaves.push((root.leaf_offset, entries.clone()));+        Ok(entries)+    }++    /// A read that must come back at its full length.+    ///+    /// A short body means the range was not honoured. Decompressing it would fail somewhere far+    /// less informative, and caching it would poison that range for every later read.+    fn exact(&self, offset: u64, length: u32, what: &str) -> Result<Vec<u8>> {+        let body = self.reader.read(offset, length)?;+        if body.len() != length as usize {+            return err(format!(+                "a .mamaps read of {what} wanted {length} bytes at {offset}, got {}",+                body.len(),+            ));+        }+        Ok(body)+    }+}++/// Inflate one body frame, allocating exactly once.+///+/// The output size comes from the body header, which the writer keeps **outside** the compressed+/// frame precisely so this is possible: the length is known before the first byte is inflated, so+/// there is no grow-and-copy and no guess.+pub fn decompress(compression: u8, stored: &[u8]) -> Result<Vec<u8>> {+    match compression {+        COMPRESSION_NONE => Ok(stored.to_vec()),+        COMPRESSION_DEFLATE => {+            let raw_len = Body::raw_len(stored)? as usize;+            if raw_len < crate::mamaps::body::BODY_HEADER_LEN {+                return err("a .mamaps body frame declares a length shorter than a body header");+            }+            let mut out = vec![0u8; raw_len];+            // The body header is stored uncompressed ahead of the frame, so the frame itself is+            // everything after it and inflates to `raw_len` less that header.+            let header_len = crate::mamaps::body::BODY_HEADER_LEN;+            out[..header_len].copy_from_slice(&stored[..header_len]);+            let written = miniz_oxide::inflate::decompress_slice_iter_to_slice(+                &mut out[header_len..],+                std::iter::once(&stored[header_len..]),+                // Raw DEFLATE, matching what the writer emits: no zlib header, so no adler32+                // either.+                false,+                false,+            )+            .map_err(|e| Error(format!("a .mamaps body will not inflate: {e:?}")))?;+            if written != raw_len - header_len {+                return err(format!(+                    "a .mamaps body inflated to {} bytes, not the {} it declares",+                    written + header_len,+                    raw_len,+                ));+            }+            Ok(out)+        }+        other => err(format!("unknown .mamaps compression {other}")),+    }+}++/// The header, dictionary and root index of a file already in memory.+///+/// What `mamaps_dump` and the writer's own tests open with, so neither needs a `RangeReader`.+pub fn open_prefix(bytes: &[u8]) -> Result<(Header, Dictionary, Vec<RootEntry>)> {+    let header = Header::parse(bytes)?;+    if bytes.len() as u64 != header.file_len {+        return err(format!(+            "a .mamaps file declares {} bytes but is {}",+            header.file_len,+            bytes.len(),+        ));+    }+    let at = |offset: u64, len: u64| &bytes[offset as usize..(offset + len) as usize];+    let dictionary = Dictionary::parse(at(header.dict_offset, header.dict_len as u64))?;+    let root = index::parse_root(at(header.root_offset, header.root_len as u64))?;+    Ok((header, dictionary, root))+}++/// Every stored tile of a file already in memory, as `(tile_id, run_length, body bytes)`.+///+/// One entry per *stored body*, not per addressed tile, so a caller can see the dedup rather than+/// having it expanded away. Ascending by tile id.+pub fn read_all(bytes: &[u8]) -> Result<Vec<(u64, u32, Vec<u8>)>> {+    let (header, dictionary, root) = open_prefix(bytes)?;+    dictionary.check_matches_schema()?;+    let mut out = Vec::new();+    for entry in &root {+        let len = entry.leaf_entry_count as usize * index::LEAF_ENTRY_LEN;+        let at = (header.leaf_offset + entry.leaf_offset) as usize;+        if at + len > bytes.len() {+            return err("a .mamaps root entry runs past the file");+        }+        for tile in index::parse_leaf(&bytes[at..at + len])? {+            let start = (header.data_offset + entry.base_data_offset + tile.offset_delta as u64)+                as usize;+            let end = start + tile.length as usize;+            if end > bytes.len() {+                return err("a .mamaps leaf entry runs past the file");+            }+            out.push((+                entry.base_tile_id + tile.tile_id_lo as u64,+                tile.run_length,+                decompress(header.compression, &bytes[start..end])?,+            ));+        }+    }+    if out.windows(2).any(|pair| pair[1].0 <= pair[0].0) {+        return err("a .mamaps archive's tiles are not in ascending id order");+    }+    Ok(out)+}++/// A sanity bound so a reader can reject a prefix that is not a `.mamaps` file at all before+/// allocating anything, without depending on the reader's own constant.+pub const MIN_FILE_LEN: usize = HEADER_LEN;
library/tilecodec/src/main/rust/src/mamaps/write.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/write.rs b/library/tilecodec/src/main/rust/src/mamaps/write.rsnew file mode 100644index 0000000000..5b34c441b5--- /dev/null+++ b/library/tilecodec/src/main/rust/src/mamaps/write.rs@@ -0,0 +1,373 @@+//! Writing a `.mamaps` archive, streaming and byte-identically.+//!+//! Bodies are appended in ascending tile-id order — which the generator gets for free, because its+//! spill buckets are zoom-major Hilbert ranges — and the index is built as they go. Nothing is+//! held in memory but the entries.+//!+//! # Dedup+//!+//! Two kinds, both of which matter:+//!+//! * **Run-length**, for consecutive identical bodies. An ocean is thousands of consecutive+//!   identical tiles, and a run collapses them to one entry as well as one body.+//! * **Content**, for non-consecutive ones — an FNV-1a bucket confirmed by a full byte compare, the+//!   same pattern `pmtiles::StreamBuilder` uses. Every hit is a fact, not a probability.+//!+//! Together these are what makes empty and ocean tiles nearly free: on the planet PMTiles archive+//! the same two collapse 1.57 M addressed tiles to 1.03 M stored bodies.+//!+//! # Determinism+//!+//! Byte-identical output for identical input, at any thread count, because nothing in the emit+//! path iterates a hash map: the dictionary comes from a constant table, layers are sorted by id,+//! and the bucket map is only ever *probed*, never walked. `pyramid.rs`'s existing byte-identity+//! suite is the precedent and this holds to the same standard.++use std::collections::HashMap;++use crate::mamaps::body::{self, Body};+use crate::mamaps::dict::Dictionary;+use crate::mamaps::header::{+    Header, COMPRESSION_DEFLATE, COMPRESSION_NONE, FLAG_BODIES_COMPRESSED, FLAG_RINGS_VALIDATED,+    FLAG_RUN_LENGTH_PRESENT, HEADER_LEN, MAX_ZOOM,+};+use crate::mamaps::index::{self, LeafEntry, RootEntry};+use crate::proto::{err, Result};+use crate::stream::OPEN_PREFIX_BYTES;++/// Leaf entries per leaf to start with, matching what the published PMTiles archive uses.+pub const DEFAULT_LEAF_CAPACITY: u32 = 4096;++/// DEFLATE level. Nine, as `gz.rs` uses, because a basemap is written once and read forever.+const LEVEL: u8 = 9;++/// What a build declares about itself before the first tile.+pub struct Options {+    pub min_zoom: u8,+    pub max_zoom: u8,+    /// Hashed over the format version, the generator revision, the input digest, the zoom range,+    /// the layer set, the simplification parameters and the schema-table version.+    ///+    /// The writer does not compute it: only the generator knows those inputs. It does carry it, and+    /// a reader's cache marker is `CACHE_FORMAT | URL | build_id`.+    pub build_id: u64,+    pub compress: bool,+    /// Set when the generator normalised ring winding and hole containment, which is what lets the+    /// renderer skip its repair pass.+    pub rings_validated: bool,+    pub leaf_entry_capacity: u32,+    pub min_lon_e7: i32,+    pub min_lat_e7: i32,+    pub max_lon_e7: i32,+    pub max_lat_e7: i32,+}++impl Default for Options {+    fn default() -> Options {+        Options {+            min_zoom: 0,+            max_zoom: 14,+            build_id: 0,+            compress: true,+            rings_validated: false,+            leaf_entry_capacity: DEFAULT_LEAF_CAPACITY,+            min_lon_e7: -1_800_000_000,+            min_lat_e7: -850_511_287,+            max_lon_e7: 1_800_000_000,+            max_lat_e7: 850_511_287,+        }+    }+}++/// Builds an archive in memory, appending bodies in ascending tile-id order.+///+/// In memory rather than through a scratch file, unlike `pmtiles::StreamBuilder`: the data section+/// is the only thing that grows without bound, and the generator that will feed this already+/// spills its *input* to disk, so a second spill here would buy a smaller peak in exchange for a+/// second on-disk format to keep correct. A California archive is a few hundred megabytes. When a+/// planet build needs it, the scratch-file pattern is already written next door.+pub struct StreamWriter {+    options: Options,+    data: Vec<u8>,+    /// One per stored body, ascending by tile id, partitioned into leaves at `finish`.+    ///+    /// The [`LeafEntry::offset_delta`] here is still **absolute** within the data section; it is+    /// rebased onto its leaf's `base_data_offset` by [`Self::partition`].+    entries: Vec<(u64, LeafEntry)>,+    /// `(hash, stored length) -> offsets already written`. Several per key only on a collision,+    /// which is why it is a list. Probed, never iterated.+    seen: HashMap<(u64, u32), Vec<u32>>,+    last_id: Option<u64>,+    tiles_addressed: u64,+    /// Bodies actually appended to `data`, which is what dedup reduces. Distinct from+    /// `entries.len()`, which counts *index* entries: a body shared by two non-adjacent tiles is+    /// one body and two entries.+    distinct: u64,+    runs_used: bool,+}++impl StreamWriter {+    pub fn new(options: Options) -> Result<StreamWriter> {+        if options.min_zoom > options.max_zoom || options.max_zoom > MAX_ZOOM {+            return err(format!(+                "a .mamaps build needs a zoom range inside 0..={MAX_ZOOM}, got {}..={}",+                options.min_zoom, options.max_zoom,+            ));+        }+        if !options.leaf_entry_capacity.is_power_of_two() || options.leaf_entry_capacity == 0 {+            return err(format!(+                "a .mamaps leaf capacity must be a power of two, got {}",+                options.leaf_entry_capacity,+            ));+        }+        Ok(StreamWriter {+            options,+            data: Vec::new(),+            entries: Vec::new(),+            seen: HashMap::new(),+            last_id: None,+            tiles_addressed: 0,+            distinct: 0,+            runs_used: false,+        })+    }++    /// Encode and append one tile. Ids must ascend.+    pub fn append(&mut self, tile_id: u64, body: &Body) -> Result<()> {+        self.append_encoded(tile_id, &body::serialize(body)?)+    }++    /// Append an already-encoded body.+    ///+    /// Ascending ids are a requirement rather than something to sort into place: the index is built+    /// as bodies arrive, and the generator's zoom-major Hilbert buckets already deliver them in+    /// order. A caller that cannot is a caller whose bucketing broke, which is worth failing over.+    pub fn append_encoded(&mut self, tile_id: u64, encoded: &[u8]) -> Result<()> {+        let (z, _, _) = crate::pmtiles::tile_zxy(tile_id);+        if z < self.options.min_zoom || z > self.options.max_zoom {+            return err(format!(+                "tile {tile_id} is at z{z}, outside the declared range {}..={}",+                self.options.min_zoom, self.options.max_zoom,+            ));+        }+        if let Some(previous) = self.last_id {+            if tile_id <= previous {+                return err(format!(+                    "a .mamaps build needs ascending tile ids, got {tile_id} after {previous}"+                ));+            }+        }+        // Parsed rather than trusted: `raw_len` is what a reader allocates from, and a body whose+        // declared length disagrees with its bytes would be caught on device instead of here.+        let raw_len = Body::raw_len(encoded)?;+        if raw_len as usize != encoded.len() {+            return err(format!(+                "a .mamaps body declares {raw_len} bytes but is {}",+                encoded.len(),+            ));+        }+        self.last_id = Some(tile_id);+        self.tiles_addressed += 1;++        let stored = if self.options.compress { compress(encoded) } else { encoded.to_vec() };+        let length = u32::try_from(stored.len())+            .map_err(|_| crate::proto::Error("a .mamaps body is larger than 4 GiB".to_string()))?;++        // Run-length first: a consecutive repeat needs no dedup lookup and no new entry at all.+        if let Some((previous_id, previous)) = self.entries.last_mut() {+            if previous.length == length+                && *previous_id + previous.run_length as u64 == tile_id+                && self.data[previous.offset_delta as usize..][..length as usize] == stored[..]+            {+                previous.run_length += 1;+                self.runs_used = true;+                return Ok(());+            }+        }++        let key = (hash64(&stored), length);+        let offset = match self+            .seen+            .get(&key)+            .and_then(|offsets| {+                offsets+                    .iter()+                    .copied()+                    .find(|&at| self.data[at as usize..][..length as usize] == stored[..])+            }) {+            Some(at) => at,+            None => {+                let at = u32::try_from(self.data.len()).map_err(|_| {+                    crate::proto::Error(+                        "a .mamaps data section past 4 GiB needs a wider offset field".to_string(),+                    )+                })?;+                self.data.extend_from_slice(&stored);+                self.seen.entry(key).or_default().push(at);+                self.distinct += 1;+                at+            }+        };+        self.entries.push((+            tile_id,+            LeafEntry { tile_id_lo: 0, run_length: 1, offset_delta: offset, length },+        ));+        Ok(())+    }++    /// The whole file.+    ///+    /// Section order on disk is header, dictionary, root, leaves, data — but every one of them is+    /// located by a header field, so a later version may reorder them freely.+    pub fn finish(self) -> Result<Vec<u8>> {+        if self.entries.is_empty() {+            return err("a .mamaps archive needs at least one tile");+        }+        let dictionary = Dictionary::schema().serialize();+        let mut capacity = self.options.leaf_entry_capacity;++        // Grow the leaf size until the root fits the opening prefix, which is the same escape the+        // PMTiles writer takes and for the same reason. Twelve doublings takes 4096 to 16 M+        // entries per leaf; a root that still does not fit is a build failure, never a silent+        // third round trip charged to every reader forever.+        let (root, leaves) = loop {+            match self.partition(capacity) {+                Some(split) => {+                    let root_len = split.0.len() * index::ROOT_ENTRY_LEN;+                    if HEADER_LEN + dictionary.len() + root_len <= OPEN_PREFIX_BYTES as usize {+                        break split;+                    }+                }+                // A leaf whose tile-id span will not fit a `u32`. Splitting further makes each+                // leaf narrower, which is the fix.+                None => {}+            }+            if capacity >= 1 << 24 {+                return err(format!(+                    "a .mamaps root index will not fit the {OPEN_PREFIX_BYTES} byte opening \+                     prefix even at {capacity} entries per leaf",+                ));+            }+            capacity *= 2;+        };++        let mut flags = 0u16;+        if self.options.compress {+            flags |= FLAG_BODIES_COMPRESSED;+        }+        if self.runs_used {+            flags |= FLAG_RUN_LENGTH_PRESENT;+        }+        if self.options.rings_validated {+            flags |= FLAG_RINGS_VALIDATED;+        }++        let leaf_bytes: Vec<u8> =+            leaves.iter().flat_map(|leaf| index::serialize_leaf(leaf)).collect();+        let root_bytes = index::serialize_root(&root);+        let dict_offset = HEADER_LEN as u64;+        let root_offset = dict_offset + dictionary.len() as u64;+        let leaf_offset = root_offset + root_bytes.len() as u64;+        let data_offset = leaf_offset + leaf_bytes.len() as u64;++        let header = Header {+            flags,+            compression: if self.options.compress { COMPRESSION_DEFLATE } else { COMPRESSION_NONE },+            layer_count: crate::mamaps::dict::LAYERS.len() as u8,+            min_zoom: self.options.min_zoom,+            max_zoom: self.options.max_zoom,+            build_id: self.options.build_id,+            file_len: data_offset + self.data.len() as u64,+            dict_offset,+            dict_len: dictionary.len() as u32,+            leaf_entry_capacity: capacity,+            root_offset,+            root_len: root_bytes.len() as u32,+            leaf_count: root.len() as u32,+            leaf_offset,+            leaf_len: leaf_bytes.len() as u32,+            data_offset,+            data_len: self.data.len() as u64,+            tiles_addressed: self.tiles_addressed,+            bodies_written: self.distinct,+            min_lon_e7: self.options.min_lon_e7,+            min_lat_e7: self.options.min_lat_e7,+            max_lon_e7: self.options.max_lon_e7,+            max_lat_e7: self.options.max_lat_e7,+        };++        let mut out = Vec::with_capacity(header.file_len as usize);+        out.extend_from_slice(&header.serialize());+        out.extend_from_slice(&dictionary);+        out.extend_from_slice(&root_bytes);+        out.extend_from_slice(&leaf_bytes);+        out.extend_from_slice(&self.data);+        debug_assert_eq!(out.len() as u64, header.file_len);+        // Parsed back before it is handed over, because every check `Header::parse` makes is a+        // check a reader will make on open, and finding out then means finding out on a device.+        Header::parse(&out)?;+        Ok(out)+    }++    /// Chop the entries into leaves of at most `capacity`, rebasing each leaf's ids and offsets.+    ///+    /// `None` when some leaf's tile-id span will not fit the `u32` a [`LeafEntry::tile_id_lo`]+    /// carries. That is a real possibility at a deep zoom with a large capacity, and truncating it+    /// would put a body at the wrong tile with no diagnostic at all -- so the caller splits instead.+    fn partition(&self, capacity: u32) -> Option<(Vec<RootEntry>, Vec<Vec<LeafEntry>>)> {+        let mut root = Vec::new();+        let mut leaves = Vec::new();+        for chunk in self.entries.chunks(capacity as usize) {+            let (base_tile_id, _) = chunk[0];+            // The **minimum** offset in the chunk, not the first. Content dedup lets a tile in+            // this leaf point at a body written for an earlier one, so basing on the first entry+            // would make that delta negative.+            let base_data_offset =+                chunk.iter().map(|(_, e)| e.offset_delta).min().unwrap_or(0) as u64;+            let (last_id, last) = chunk[chunk.len() - 1];+            if !index::span_fits(last_id + last.run_length as u64 - 1 - base_tile_id) {+                return None;+            }+            let mut leaf = Vec::with_capacity(chunk.len());+            for (tile_id, entry) in chunk {+                leaf.push(LeafEntry {+                    tile_id_lo: (tile_id - base_tile_id) as u32,+                    run_length: entry.run_length,+                    offset_delta: entry.offset_delta - base_data_offset as u32,+                    length: entry.length,+                });+            }+            root.push(RootEntry {+                base_tile_id,+                leaf_offset: (leaves.len() * capacity as usize * index::LEAF_ENTRY_LEN) as u64,+                base_data_offset,+                leaf_entry_count: chunk.len() as u32,+            });+            leaves.push(leaf);+        }+        Some((root, leaves))+    }+}++/// Raw DEFLATE over everything but the body header.+///+/// The 16-byte body header is left uncompressed ahead of the frame so a reader can read `raw_len`+/// out of it and allocate the output exactly once, before inflating a single byte.+fn compress(encoded: &[u8]) -> Vec<u8> {+    let header_len = body::BODY_HEADER_LEN;+    let mut out = Vec::with_capacity(encoded.len());+    out.extend_from_slice(&encoded[..header_len]);+    out.extend_from_slice(&miniz_oxide::deflate::compress_to_vec(&encoded[header_len..], LEVEL));+    out+}++/// FNV-1a. Only ever a bucket key — every hit is confirmed by comparing bytes — so it needs to be+/// fast and well spread, not collision-proof.+fn hash64(data: &[u8]) -> u64 {+    let mut h = 0xcbf2_9ce4_8422_2325u64;+    for &b in data {+        h ^= b as u64;+        h = h.wrapping_mul(0x100_0000_01b3);+    }+    h+}