Modern Apps git

← Modern-Apps.git

maps: add a PMTiles v3 reader and writer

Commit
79e0ea264bed871e1eb9d3a9226d5e67ed65ce4c
Author
vayun-mathur <[email protected]>
When
2026-08-21 03:56 UTC (3 months ago)
Parents
ba3301f
Third piece of tile_build. Includes gzip framing over miniz_oxide's raw DEFLATE, since PMTiles gzips both directories and tiles and miniz_oxide provides no gzip layer; MTIME and OS are pinned so an unchanged layer rebuilds byte-identically. The writer deduplicates identical tile bodies and run-length encodes consecutive ids sharing them, which is what collapses a basemap's vast runs of identical ocean tiles, and spills into leaf directories once the root would no longer fit in a single 16 KiB request. Pinned against the real published archive with two committed fixtures: its 127-byte header parses to its known values, and its gzipped root directory re-serializes BYTE-EXACTLY through our own encoder, contiguous-offset shorthand included. Hilbert ids are round-trip tested exhaustively to z6 and shown to fill each zoom contiguously with no gaps, which is what run-length encoding depends on.

Diff

scripts/maps/tile_build/src/gz.rs
diff --git a/scripts/maps/tile_build/src/gz.rs b/scripts/maps/tile_build/src/gz.rsnew file mode 100644index 0000000000..68e3b25aa7--- /dev/null+++ b/scripts/maps/tile_build/src/gz.rs@@ -0,0 +1,209 @@+//! gzip framing over `miniz_oxide`'s raw DEFLATE.+//!+//! PMTiles gzips both its directories and its tiles, and MapLibre's pmtiles+//! plugin expects exactly that, so the tile builder has to produce real gzip+//! streams rather than bare deflate or zlib. `miniz_oxide` only does raw DEFLATE+//! (and zlib), so the 10-byte header, CRC32 and ISIZE trailer are added here.+//!+//! `osm_ingest` gets away with `miniz_oxide` alone because an `.osm.pbf` uses+//! zlib blobs and is only ever read. This crate both reads and writes.++use crate::proto::{err, Error, Result};++const FHCRC: u8 = 1 << 1;+const FEXTRA: u8 = 1 << 2;+const FNAME: u8 = 1 << 3;+const FCOMMENT: u8 = 1 << 4;++/// DEFLATE level. 9 is the usual archive setting: tiles are written once and+/// streamed by range request many times, so bytes matter more than build time.+const LEVEL: u8 = 9;++/// Wrap `data` in a gzip stream.+pub fn compress(data: &[u8]) -> Vec<u8> {+    let body = miniz_oxide::deflate::compress_to_vec(data, LEVEL);+    let mut out = Vec::with_capacity(body.len() + 18);+    out.extend_from_slice(&[+        0x1f, 0x8b, // magic+        0x08, // CM = DEFLATE+        0x00, // FLG: no extra fields+        0x00, 0x00, 0x00, 0x00, // MTIME 0, so output is reproducible+        0x00, // XFL+        0xff, // OS = unknown, again for reproducibility+    ]);+    out.extend_from_slice(&body);+    out.extend_from_slice(&crc32(data).to_le_bytes());+    out.extend_from_slice(&(data.len() as u32).to_le_bytes());+    out+}++/// Unwrap a gzip stream. Tolerates the optional header fields a stream from+/// another producer may carry, since we read files tippecanoe wrote.+pub fn decompress(data: &[u8]) -> Result<Vec<u8>> {+    if data.len() < 18 {+        return err("gzip stream too short");+    }+    if data[0] != 0x1f || data[1] != 0x8b {+        return err("not a gzip stream (bad magic)");+    }+    if data[2] != 0x08 {+        return err(format!("unsupported gzip compression method {}", data[2]));+    }+    let flags = data[3];+    let mut pos = 10usize;+    if flags & FEXTRA != 0 {+        if pos + 2 > data.len() {+            return err("truncated gzip FEXTRA");+        }+        let xlen = u16::from_le_bytes([data[pos], data[pos + 1]]) as usize;+        pos += 2 + xlen;+    }+    for flag in [FNAME, FCOMMENT] {+        if flags & flag != 0 {+            // NUL-terminated string.+            let start = pos;+            while pos < data.len() && data[pos] != 0 {+                pos += 1;+            }+            if pos >= data.len() {+                return err("unterminated gzip header string");+            }+            pos += 1;+            let _ = start;+        }+    }+    if flags & FHCRC != 0 {+        pos += 2;+    }+    // The last 8 bytes are CRC32 + ISIZE, not deflate data.+    if pos + 8 > data.len() {+        return err("truncated gzip stream");+    }+    let body = &data[pos..data.len() - 8];+    let out = miniz_oxide::inflate::decompress_to_vec(body)+        .map_err(|e| Error(format!("gzip inflate failed: {e:?}")))?;++    let tail = &data[data.len() - 8..];+    let want_crc = u32::from_le_bytes([tail[0], tail[1], tail[2], tail[3]]);+    let want_len = u32::from_le_bytes([tail[4], tail[5], tail[6], tail[7]]);+    // Checked, not assumed: a silently corrupt directory would otherwise surface+    // much later as a nonsensical tile offset.+    if want_len != out.len() as u32 {+        return err(format!("gzip length mismatch: header {want_len}, got {}", out.len()));+    }+    let got_crc = crc32(&out);+    if want_crc != got_crc {+        return err(format!("gzip CRC mismatch: header {want_crc:#x}, got {got_crc:#x}"));+    }+    Ok(out)+}++/// IEEE CRC-32, table-built on first use.+fn crc32(data: &[u8]) -> u32 {+    let table = crc_table();+    let mut crc = 0xFFFF_FFFFu32;+    for &b in data {+        crc = table[((crc ^ b as u32) & 0xFF) as usize] ^ (crc >> 8);+    }+    crc ^ 0xFFFF_FFFF+}++fn crc_table() -> &'static [u32; 256] {+    use std::sync::OnceLock;+    static TABLE: OnceLock<[u32; 256]> = OnceLock::new();+    TABLE.get_or_init(|| {+        let mut t = [0u32; 256];+        for (i, slot) in t.iter_mut().enumerate() {+            let mut c = i as u32;+            for _ in 0..8 {+                c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };+            }+            *slot = c;+        }+        t+    })+}++#[cfg(test)]+mod tests {+    use super::*;++    /// The same z11 tile as the MVT fixture, but still gzipped exactly as the+    /// published archive stores it. Proves our reader handles a real producer's+    /// stream, not just our own writer's.+    const REAL_GZ: &[u8] = include_bytes!("../tests/fixtures/v5ca_z11_tile.mvt.gz");+    const REAL_RAW: &[u8] = include_bytes!("../tests/fixtures/v5ca_z11_tile.mvt");++    #[test]+    fn crc32_matches_the_known_check_value() {+        // The standard CRC-32 check value for "123456789".+        assert_eq!(crc32(b"123456789"), 0xCBF4_3926);+        assert_eq!(crc32(b""), 0);+    }++    #[test]+    fn round_trips_including_empty_and_incompressible_input() {+        for case in [+            b"".to_vec(),+            b"hello".to_vec(),+            vec![0u8; 100_000],+            (0..=255u8).cycle().take(50_000).collect::<Vec<_>>(),+        ] {+            let gz = compress(&case);+            assert_eq!(&gz[..3], &[0x1f, 0x8b, 0x08], "gzip magic + method");+            assert_eq!(decompress(&gz).unwrap(), case, "len {}", case.len());+        }+    }++    #[test]+    fn compression_is_reproducible() {+        // MTIME and OS are pinned, so two builds of the same tile are identical+        // and an unchanged layer produces an unchanged archive.+        assert_eq!(compress(b"the same bytes"), compress(b"the same bytes"));+    }++    #[test]+    fn decompresses_a_real_archive_stream() {+        let out = decompress(REAL_GZ).expect("the published tile's gzip stream");+        assert_eq!(out, REAL_RAW, "must inflate to the same MVT bytes");+    }++    #[test]+    fn a_real_stream_survives_our_own_round_trip() {+        let raw = decompress(REAL_GZ).unwrap();+        assert_eq!(decompress(&compress(&raw)).unwrap(), raw);+    }++    #[test]+    fn corruption_is_detected_rather_than_returned() {+        let mut gz = compress(b"important tile bytes");+        let n = gz.len();+        // Flip a bit in the CRC trailer.+        gz[n - 5] ^= 0x01;+        assert!(decompress(&gz).is_err(), "a bad CRC must be rejected");++        let mut gz = compress(b"important tile bytes");+        let n = gz.len();+        // Corrupt the ISIZE trailer.+        gz[n - 1] ^= 0xFF;+        assert!(decompress(&gz).is_err(), "a bad length must be rejected");+    }++    #[test]+    fn non_gzip_input_errors() {+        assert!(decompress(b"not gzip at all, but long enough").is_err());+        assert!(decompress(b"short").is_err());+    }++    #[test]+    fn optional_header_fields_are_skipped() {+        // Hand-build a stream carrying FNAME, which some producers set.+        let body = miniz_oxide::deflate::compress_to_vec(b"payload", LEVEL);+        let mut gz = vec![0x1f, 0x8b, 0x08, FNAME, 0, 0, 0, 0, 0, 0xff];+        gz.extend_from_slice(b"tile.mvt\0");+        gz.extend_from_slice(&body);+        gz.extend_from_slice(&crc32(b"payload").to_le_bytes());+        gz.extend_from_slice(&(7u32).to_le_bytes());+        assert_eq!(decompress(&gz).unwrap(), b"payload");+    }+}
scripts/maps/tile_build/src/lib.rs
diff --git a/scripts/maps/tile_build/src/lib.rs b/scripts/maps/tile_build/src/lib.rsindex d978e26be7..102dbabf65 100644--- a/scripts/maps/tile_build/src/lib.rs+++ b/scripts/maps/tile_build/src/lib.rs@@ -10,11 +10,17 @@ //!     decode-only reader; write half is new. //!   * [`mvt`] — vector tile 2.1 decode/encode. Geometry stays as raw command //!     integers, so lines and polygons pass through without a clipper.+//!   * [`gz`] — gzip framing over `miniz_oxide`'s raw DEFLATE, which PMTiles needs+//!     for both its directories and its tiles.+//!   * [`pmtiles`] — the v3 container, read and write, including Hilbert tile ids+//!     and the root/leaf directory split. //! //! Verified against the published `v5-ca.pmtiles` during development: its header, //! gzipped root directory and gzipped leaf directories all decode with byte-exact //! payload consumption, and a real tile's layers decode to the same names, //! extents and feature counts tippecanoe wrote. +pub mod gz; pub mod mvt;+pub mod pmtiles; pub mod proto;
scripts/maps/tile_build/src/pmtiles.rs
diff --git a/scripts/maps/tile_build/src/pmtiles.rs b/scripts/maps/tile_build/src/pmtiles.rsnew file mode 100644index 0000000000..942a9eb2ea--- /dev/null+++ b/scripts/maps/tile_build/src/pmtiles.rs@@ -0,0 +1,922 @@+//! PMTiles v3 container — read and write.+//!+//! Both halves are needed: reading, because the `transit_stops` layer has to be+//! composited into the existing basemap archive, and writing, because that+//! composite has to come back out as a PMTiles the app can stream.+//!+//! Layout, as verified against the published `v5-ca.pmtiles`:+//!+//! ```text+//! [ 127-byte header ][ root directory ][ metadata ][ leaf directories ][ tile data ]+//! ```+//!+//! The header is fixed-width little-endian; everything else is at an offset it+//! names. Directories and metadata are compressed with `internal_compression`,+//! tiles with `tile_compression` — both gzip in practice.+//!+//! A **directory** is a columnar run of varints:+//!+//! ```text+//! uvarint num_entries+//! num_entries x uvarint  tile_id delta   (first is absolute)+//! num_entries x uvarint  run_length+//! num_entries x uvarint  length+//! num_entries x uvarint  offset          (0 = contiguous with the previous entry)+//! ```+//!+//! `run_length == 0` marks a **leaf pointer**: its offset/length address the leaf+//! directories section instead of tile data. `run_length >= 1` is a tile run, where+//! `run_length` consecutive tile ids all resolve to the same bytes — that is how+//! PMTiles collapses the vast runs of identical ocean tiles.+//!+//! Tile ids are positions along a **Hilbert curve**, offset by the number of tiles+//! in all lower zooms, so a z/x/y maps to a single integer whose neighbours are+//! spatially close. That locality is what lets the app fetch a screenful of tiles+//! in few range requests.++use crate::gz;+use crate::proto::{err, Reader, Result, Writer};+use std::collections::HashMap;++pub const MAGIC: &[u8; 7] = b"PMTiles";+pub const SPEC_VERSION: u8 = 3;+pub const HEADER_LEN: usize = 127;++/// Compression ids from the spec. We only ever emit `Gzip`.+pub const COMPRESSION_NONE: u8 = 1;+pub const COMPRESSION_GZIP: u8 = 2;++/// Tile type ids from the spec.+pub const TILE_TYPE_MVT: u8 = 1;++/// The spec advises keeping the root directory small enough to come back in the+/// same request as the header, so a cold open is one round trip.+const MAX_ROOT_BYTES: usize = 16_384 - HEADER_LEN;++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct Entry {+    pub tile_id: u64,+    /// Relative to `tile_data_offset`, or to `leaf_dirs_offset` when this is a+    /// leaf pointer.+    pub offset: u64,+    pub length: u32,+    /// `0` = leaf pointer; `n >= 1` = this entry covers `tile_id..tile_id + n`.+    pub run_length: u32,+}++#[derive(Debug, Clone)]+pub struct Header {+    pub root_offset: u64,+    pub root_length: u64,+    pub metadata_offset: u64,+    pub metadata_length: u64,+    pub leaf_offset: u64,+    pub leaf_length: u64,+    pub tile_data_offset: u64,+    pub tile_data_length: u64,+    pub addressed_tiles: u64,+    pub tile_entries: u64,+    pub tile_contents: u64,+    pub clustered: bool,+    pub internal_compression: u8,+    pub tile_compression: u8,+    pub tile_type: u8,+    pub min_zoom: u8,+    pub max_zoom: u8,+    pub min_lon_e7: i32,+    pub min_lat_e7: i32,+    pub max_lon_e7: i32,+    pub max_lat_e7: i32,+    pub center_zoom: u8,+    pub center_lon_e7: i32,+    pub center_lat_e7: i32,+}++impl Header {+    pub fn parse(buf: &[u8]) -> Result<Header> {+        if buf.len() < HEADER_LEN {+            return err("PMTiles header shorter than 127 bytes");+        }+        if &buf[0..7] != MAGIC {+            return err("not a PMTiles archive (bad magic)");+        }+        if buf[7] != SPEC_VERSION {+            return err(format!("unsupported PMTiles spec version {}", buf[7]));+        }+        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 i32_at =+            |o: usize| i32::from_le_bytes([buf[o], buf[o + 1], buf[o + 2], buf[o + 3]]);+        Ok(Header {+            root_offset: u64_at(8),+            root_length: u64_at(16),+            metadata_offset: u64_at(24),+            metadata_length: u64_at(32),+            leaf_offset: u64_at(40),+            leaf_length: u64_at(48),+            tile_data_offset: u64_at(56),+            tile_data_length: u64_at(64),+            addressed_tiles: u64_at(72),+            tile_entries: u64_at(80),+            tile_contents: u64_at(88),+            clustered: buf[96] != 0,+            internal_compression: buf[97],+            tile_compression: buf[98],+            tile_type: buf[99],+            min_zoom: buf[100],+            max_zoom: buf[101],+            min_lon_e7: i32_at(102),+            min_lat_e7: i32_at(106),+            max_lon_e7: i32_at(110),+            max_lat_e7: i32_at(114),+            center_zoom: buf[118],+            center_lon_e7: i32_at(119),+            center_lat_e7: i32_at(123),+        })+    }++    pub fn serialize(&self) -> Vec<u8> {+        let mut out = Vec::with_capacity(HEADER_LEN);+        out.extend_from_slice(MAGIC);+        out.push(SPEC_VERSION);+        for v in [+            self.root_offset,+            self.root_length,+            self.metadata_offset,+            self.metadata_length,+            self.leaf_offset,+            self.leaf_length,+            self.tile_data_offset,+            self.tile_data_length,+            self.addressed_tiles,+            self.tile_entries,+            self.tile_contents,+        ] {+            out.extend_from_slice(&v.to_le_bytes());+        }+        out.push(self.clustered as u8);+        out.push(self.internal_compression);+        out.push(self.tile_compression);+        out.push(self.tile_type);+        out.push(self.min_zoom);+        out.push(self.max_zoom);+        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());+        }+        out.push(self.center_zoom);+        out.extend_from_slice(&self.center_lon_e7.to_le_bytes());+        out.extend_from_slice(&self.center_lat_e7.to_le_bytes());+        debug_assert_eq!(out.len(), HEADER_LEN);+        out+    }+}++// --- Hilbert tile ids ---------------------------------------------------------++/// Number of tiles in every zoom below `z`, i.e. the first tile id at `z`.+/// `(4^z - 1) / 3`.+pub fn zoom_base(z: u8) -> u64 {+    // Closed form via the geometric series; exact in u64 up to z=31.+    ((1u64 << (2 * z as u32)) - 1) / 3+}++/// Rotate/flip a quadrant. The canonical Hilbert helper.+fn rot(n: u64, x: &mut u64, y: &mut u64, rx: u64, ry: u64) {+    if ry == 0 {+        if rx == 1 {+            *x = n.wrapping_sub(1).wrapping_sub(*x);+            *y = n.wrapping_sub(1).wrapping_sub(*y);+        }+        std::mem::swap(x, y);+    }+}++/// `(z, x, y)` -> PMTiles tile id.+pub fn tile_id(z: u8, x: u64, y: u64) -> u64 {+    let n = 1u64 << z;+    let (mut x, mut y) = (x, y);+    let mut d = 0u64;+    let mut s = n / 2;+    while s > 0 {+        let rx = u64::from(x & s > 0);+        let ry = u64::from(y & s > 0);+        d += s * s * ((3 * rx) ^ ry);+        rot(n, &mut x, &mut y, rx, ry);+        s /= 2;+    }+    zoom_base(z) + d+}++/// PMTiles tile id -> `(z, x, y)`.+pub fn tile_zxy(id: u64) -> (u8, u64, u64) {+    let mut z = 0u8;+    // Walk up until the next zoom's base passes the id. Bounded by z=31.+    while z < 31 && id >= zoom_base(z + 1) {+        z += 1;+    }+    let mut t = id - zoom_base(z);+    let n = 1u64 << z;+    let (mut x, mut y) = (0u64, 0u64);+    let mut s = 1u64;+    while s < n {+        let rx = 1 & (t / 2);+        let ry = 1 & (t ^ rx);+        rot(s, &mut x, &mut y, rx, ry);+        x += s * rx;+        y += s * ry;+        t /= 4;+        s *= 2;+    }+    (z, x, y)+}++// --- Directory serialization --------------------------------------------------++/// Serialize a directory. Entries must be sorted ascending by `tile_id`.+pub fn serialize_directory(entries: &[Entry]) -> Vec<u8> {+    let mut w = Writer::with_capacity(entries.len() * 5);+    w.uvarint(entries.len() as u64);+    let mut last = 0u64;+    for e in entries {+        w.uvarint(e.tile_id - last);+        last = e.tile_id;+    }+    for e in entries {+        w.uvarint(e.run_length as u64);+    }+    for e in entries {+        w.uvarint(e.length as u64);+    }+    for (i, e) in entries.iter().enumerate() {+        // 0 is the "picks up exactly where the last one ended" shorthand, which is+        // the common case in a clustered archive and saves several bytes per entry.+        let contiguous = i > 0+            && e.offset == entries[i - 1].offset + entries[i - 1].length as u64;+        if contiguous {+            w.uvarint(0);+        } else {+            w.uvarint(e.offset + 1);+        }+    }+    w.into_vec()+}++/// Parse a directory body (already decompressed).+pub fn parse_directory(buf: &[u8]) -> Result<Vec<Entry>> {+    let mut r = Reader::new(buf);+    let n = r.uvarint()? as usize;+    // A directory is 5 varints per entry at minimum one byte each, so a count+    // wildly larger than the buffer is corruption, not a huge directory.+    if n > buf.len() {+        return err(format!("PMTiles directory claims {n} entries in {} bytes", buf.len()));+    }+    let mut entries = vec![+        Entry { tile_id: 0, offset: 0, length: 0, run_length: 0 };+        n+    ];+    let mut last = 0u64;+    for e in entries.iter_mut() {+        last += r.uvarint()?;+        e.tile_id = last;+    }+    for e in entries.iter_mut() {+        e.run_length = r.uvarint()? as u32;+    }+    for e in entries.iter_mut() {+        e.length = r.uvarint()? as u32;+    }+    for i in 0..n {+        let v = r.uvarint()?;+        entries[i].offset = if v == 0 {+            if i == 0 {+                return err("PMTiles directory's first entry uses the contiguous shorthand");+            }+            entries[i - 1].offset + entries[i - 1].length as u64+        } else {+            v - 1+        };+    }+    if !r.at_end() {+        return err("trailing bytes after PMTiles directory");+    }+    Ok(entries)+}++// --- Reading ------------------------------------------------------------------++/// A whole archive held in memory.+///+/// Fine for the layers we build (tens of MB). The 1.5 GB published basemap is+/// composited by streaming instead — see `tile_join`.+pub struct Archive {+    pub header: Header,+    pub metadata: Vec<u8>,+    root: Vec<Entry>,+    leaves: Vec<u8>,+    tile_data: Vec<u8>,+}++impl Archive {+    pub fn parse(buf: &[u8]) -> Result<Archive> {+        let header = Header::parse(buf)?;+        let slice = |off: u64, len: u64, what: &str| -> Result<&[u8]> {+            let (o, l) = (off as usize, len as usize);+            match o.checked_add(l).filter(|e| *e <= buf.len()) {+                Some(end) => Ok(&buf[o..end]),+                None => err(format!("PMTiles {what} runs past end of file")),+            }+        };+        let root_raw = slice(header.root_offset, header.root_length, "root directory")?;+        let root = parse_directory(&decompress(header.internal_compression, root_raw)?)?;+        let metadata = decompress(+            header.internal_compression,+            slice(header.metadata_offset, header.metadata_length, "metadata")?,+        )?;+        let leaves = slice(header.leaf_offset, header.leaf_length, "leaf directories")?.to_vec();+        let tile_data =+            slice(header.tile_data_offset, header.tile_data_length, "tile data")?.to_vec();+        Ok(Archive { header, metadata, root, leaves, tile_data })+    }++    /// Raw (still `tile_compression`-compressed) bytes for a tile, or `None`.+    pub fn tile_raw(&self, z: u8, x: u64, y: u64) -> Result<Option<&[u8]>> {+        let want = tile_id(z, x, y);+        let Some(entry) = find_entry(&self.root, want).copied() else { return Ok(None) };+        if entry.run_length > 0 {+            return self.tile_bytes(&entry).map(Some);+        }+        // A leaf pointer. The spec allows arbitrary nesting; producers emit two+        // levels, so cap the walk rather than risk looping on a corrupt file.+        let mut entry = entry;+        for _ in 0..4 {+            let leaf = self.read_leaf(&entry)?;+            let Some(e) = find_entry(&leaf, want).copied() else { return Ok(None) };+            if e.run_length > 0 {+                return self.tile_bytes(&e).map(Some);+            }+            entry = e;+        }+        err("PMTiles directory nested deeper than 4 levels")+    }++    /// Tile-data bytes an entry addresses.+    fn tile_bytes(&self, e: &Entry) -> Result<&[u8]> {+        let (o, l) = (e.offset as usize, e.length as usize);+        match o.checked_add(l).filter(|v| *v <= self.tile_data.len()) {+            Some(end) => Ok(&self.tile_data[o..end]),+            None => err("PMTiles tile entry runs past tile data"),+        }+    }++    /// Parse the leaf directory a leaf-pointer entry addresses.+    fn read_leaf(&self, e: &Entry) -> Result<Vec<Entry>> {+        let (o, l) = (e.offset as usize, e.length as usize);+        let end = match o.checked_add(l).filter(|v| *v <= self.leaves.len()) {+            Some(v) => v,+            None => return err("PMTiles leaf entry runs past leaf section"),+        };+        parse_directory(&decompress(self.header.internal_compression, &self.leaves[o..end])?)+    }++    /// Decompressed tile bytes (an MVT body), or `None` when absent.+    pub fn tile(&self, z: u8, x: u64, y: u64) -> Result<Option<Vec<u8>>> {+        match self.tile_raw(z, x, y)? {+            None => Ok(None),+            Some(raw) => Ok(Some(decompress(self.header.tile_compression, raw)?)),+        }+    }++    /// Every `(tile_id, raw bytes)` in the archive, ascending. Runs are expanded,+    /// so a run of identical ocean tiles yields one item per tile id.+    pub fn iter_tiles(&self) -> Result<Vec<(u64, &[u8])>> {+        let mut out = Vec::new();+        for e in &self.root {+            if e.run_length > 0 {+                push_run(&mut out, e, &self.tile_data)?;+            } else {+                let (o, l) = (e.offset as usize, e.length as usize);+                if o + l > self.leaves.len() {+                    return err("PMTiles leaf entry runs past leaf section");+                }+                let leaf = parse_directory(&decompress(+                    self.header.internal_compression,+                    &self.leaves[o..o + l],+                )?)?;+                for le in &leaf {+                    if le.run_length > 0 {+                        push_run(&mut out, le, &self.tile_data)?;+                    }+                }+            }+        }+        Ok(out)+    }+}++fn push_run<'a>(out: &mut Vec<(u64, &'a [u8])>, e: &Entry, data: &'a [u8]) -> Result<()> {+    let (o, l) = (e.offset as usize, e.length as usize);+    if o + l > data.len() {+        return err("PMTiles tile entry runs past tile data");+    }+    let bytes = &data[o..o + l];+    for k in 0..e.run_length as u64 {+        out.push((e.tile_id + k, bytes));+    }+    Ok(())+}++/// Find the entry covering `want`: the last entry whose `tile_id <= want`, then a+/// bounds check against its run.+fn find_entry(entries: &[Entry], want: u64) -> Option<&Entry> {+    let idx = match entries.binary_search_by(|e| e.tile_id.cmp(&want)) {+        Ok(i) => i,+        Err(0) => return None,+        Err(i) => i - 1,+    };+    let e = &entries[idx];+    if e.run_length == 0 {+        // Leaf pointers cover everything from their id to the next entry's.+        return Some(e);+    }+    if want < e.tile_id + e.run_length as u64 {+        Some(e)+    } else {+        None+    }+}++fn decompress(kind: u8, data: &[u8]) -> Result<Vec<u8>> {+    match kind {+        COMPRESSION_NONE => Ok(data.to_vec()),+        COMPRESSION_GZIP => gz::decompress(data),+        other => err(format!("unsupported PMTiles compression {other}")),+    }+}++fn compress(kind: u8, data: &[u8]) -> Result<Vec<u8>> {+    match kind {+        COMPRESSION_NONE => Ok(data.to_vec()),+        COMPRESSION_GZIP => Ok(gz::compress(data)),+        other => err(format!("unsupported PMTiles compression {other}")),+    }+}++// --- Writing ------------------------------------------------------------------++/// Accumulates tiles and serializes a whole v3 archive.+pub struct Builder {+    /// `tile_id -> already tile-compressed bytes`.+    tiles: Vec<(u64, Vec<u8>)>,+    pub metadata: Vec<u8>,+    pub min_zoom: u8,+    pub max_zoom: u8,+    pub min_lon_e7: i32,+    pub min_lat_e7: i32,+    pub max_lon_e7: i32,+    pub max_lat_e7: i32,+    pub center_zoom: u8,+    pub center_lon_e7: i32,+    pub center_lat_e7: i32,+}++impl Default for Builder {+    fn default() -> Self {+        Builder::new()+    }+}++impl Builder {+    pub fn new() -> Builder {+        Builder {+            tiles: Vec::new(),+            metadata: b"{}".to_vec(),+            min_zoom: 0,+            max_zoom: 0,+            // Whole Mercator world, as the published archive uses.+            min_lon_e7: -1_800_000_000,+            min_lat_e7: -850_511_290,+            max_lon_e7: 1_800_000_000,+            max_lat_e7: 850_511_290,+            center_zoom: 0,+            center_lon_e7: 0,+            center_lat_e7: 0,+        }+    }++    /// Add a tile from its uncompressed MVT body.+    pub fn add_tile(&mut self, z: u8, x: u64, y: u64, mvt: &[u8]) {+        self.add_tile_raw(tile_id(z, x, y), gz::compress(mvt));+    }++    /// Add a tile that is already gzipped, e.g. copied straight out of another+    /// archive without a decode/re-encode cycle.+    pub fn add_tile_raw(&mut self, tile_id: u64, compressed: Vec<u8>) {+        self.tiles.push((tile_id, compressed));+    }++    pub fn is_empty(&self) -> bool {+        self.tiles.is_empty()+    }++    pub fn len(&self) -> usize {+        self.tiles.len()+    }++    /// Serialize the archive.+    pub fn build(mut self) -> Result<Vec<u8>> {+        self.tiles.sort_by_key(|(id, _)| *id);+        self.tiles.dedup_by_key(|(id, _)| *id);++        // Deduplicate identical tile bodies: a basemap is mostly repeated ocean and+        // empty land, and this is what makes an archive of 1.5 M tiles hold ~1 M+        // distinct bodies.+        let mut blob = Vec::new();+        let mut seen: HashMap<Vec<u8>, (u64, u32)> = HashMap::new();+        let mut entries: Vec<Entry> = Vec::with_capacity(self.tiles.len());+        let mut addressed = 0u64;+        for (id, data) in &self.tiles {+            addressed += 1;+            let (offset, length) = match seen.get(data) {+                Some(&v) => v,+                None => {+                    let v = (blob.len() as u64, data.len() as u32);+                    blob.extend_from_slice(data);+                    seen.insert(data.clone(), v);+                    v+                }+            };+            // Extend the previous entry's run when this tile is the next id and+            // resolves to the same bytes.+            if let Some(prev) = entries.last_mut() {+                if prev.offset == offset+                    && prev.length == length+                    && prev.tile_id + prev.run_length as u64 == *id+                {+                    prev.run_length += 1;+                    continue;+                }+            }+            entries.push(Entry { tile_id: *id, offset, length, run_length: 1 });+        }+        let tile_contents = seen.len() as u64;+        let tile_entries = entries.len() as u64;++        let (root_body, leaf_body) = self.split_directories(&entries)?;+        let root = compress(COMPRESSION_GZIP, &root_body)?;+        let metadata = compress(COMPRESSION_GZIP, &self.metadata)?;++        let root_offset = HEADER_LEN as u64;+        let metadata_offset = root_offset + root.len() as u64;+        let leaf_offset = metadata_offset + metadata.len() as u64;+        let tile_data_offset = leaf_offset + leaf_body.len() as u64;++        let header = Header {+            root_offset,+            root_length: root.len() as u64,+            metadata_offset,+            metadata_length: metadata.len() as u64,+            leaf_offset,+            leaf_length: leaf_body.len() as u64,+            tile_data_offset,+            tile_data_length: blob.len() as u64,+            addressed_tiles: addressed,+            tile_entries,+            tile_contents,+            // Entries are written in ascending tile_id and their offsets ascend with+            // them, which is exactly what `clustered` promises a reader.+            clustered: true,+            internal_compression: COMPRESSION_GZIP,+            tile_compression: COMPRESSION_GZIP,+            tile_type: TILE_TYPE_MVT,+            min_zoom: self.min_zoom,+            max_zoom: self.max_zoom,+            min_lon_e7: self.min_lon_e7,+            min_lat_e7: self.min_lat_e7,+            max_lon_e7: self.max_lon_e7,+            max_lat_e7: self.max_lat_e7,+            center_zoom: self.center_zoom,+            center_lon_e7: self.center_lon_e7,+            center_lat_e7: self.center_lat_e7,+        };++        let mut out = Vec::with_capacity(+            HEADER_LEN + root.len() + metadata.len() + leaf_body.len() + blob.len(),+        );+        out.extend_from_slice(&header.serialize());+        out.extend_from_slice(&root);+        out.extend_from_slice(&metadata);+        out.extend_from_slice(&leaf_body);+        out.extend_from_slice(&blob);+        Ok(out)+    }++    /// Fit the entries into a root directory small enough for a one-request open,+    /// spilling into leaf directories when they do not fit.+    fn split_directories(&self, entries: &[Entry]) -> Result<(Vec<u8>, Vec<u8>)> {+        let flat = serialize_directory(entries);+        if flat.len() <= MAX_ROOT_BYTES {+            return Ok((flat, Vec::new()));+        }+        // Grow the leaf size until one entry per leaf fits in the root. Starting at+        // 4096 matches what the published archive uses.+        let mut leaf_size = 4096usize;+        for _ in 0..12 {+            let mut root: Vec<Entry> = Vec::new();+            let mut leaves: Vec<u8> = Vec::new();+            for chunk in entries.chunks(leaf_size) {+                let body = compress(COMPRESSION_GZIP, &serialize_directory(chunk))?;+                root.push(Entry {+                    tile_id: chunk[0].tile_id,+                    offset: leaves.len() as u64,+                    length: body.len() as u32,+                    run_length: 0,+                });+                leaves.extend_from_slice(&body);+            }+            let root_body = serialize_directory(&root);+            if root_body.len() <= MAX_ROOT_BYTES {+                return Ok((root_body, leaves));+            }+            leaf_size *= 2;+        }+        err("cannot fit a PMTiles root directory even with very large leaves")+    }+}++#[cfg(test)]+mod tests {+    use super::*;++    /// Real bytes 0..1479 of the published archive: the 127-byte header plus its+    /// whole gzipped root directory.+    const REAL_HEAD: &[u8] = include_bytes!("../tests/fixtures/v5ca_header_rootdir.bin");+    const REAL_TILE_MVT: &[u8] = include_bytes!("../tests/fixtures/v5ca_z11_tile.mvt");++    #[test]+    fn zoom_base_matches_the_closed_form() {+        assert_eq!(zoom_base(0), 0);+        assert_eq!(zoom_base(1), 1);+        assert_eq!(zoom_base(2), 5);+        assert_eq!(zoom_base(3), 21);+        // Sum of 4^k for k < z.+        for z in 0..16u8 {+            let want: u64 = (0..z).map(|k| 1u64 << (2 * k as u32)).sum();+            assert_eq!(zoom_base(z), want, "zoom_base({z})");+        }+    }++    #[test]+    fn tile_ids_round_trip_exhaustively_at_low_zoom() {+        // Every tile up to z6 (5461 of them), both directions.+        for z in 0..=6u8 {+            let n = 1u64 << z;+            for x in 0..n {+                for y in 0..n {+                    let id = tile_id(z, x, y);+                    assert_eq!(tile_zxy(id), (z, x, y), "z{z}/{x}/{y} -> {id}");+                }+            }+        }+    }++    #[test]+    fn tile_ids_are_contiguous_within_a_zoom() {+        // A zoom's ids must exactly fill [base(z), base(z+1)) with no gaps or+        // repeats, which is what makes run-length encoding work.+        for z in 0..=6u8 {+            let n = 1u64 << z;+            let mut ids: Vec<u64> = (0..n).flat_map(|x| (0..n).map(move |y| (x, y)))+                .map(|(x, y)| tile_id(z, x, y))+                .collect();+            ids.sort_unstable();+            let want: Vec<u64> = (zoom_base(z)..zoom_base(z + 1)).collect();+            assert_eq!(ids, want, "zoom {z} ids");+        }+    }++    #[test]+    fn the_spec_anchor_points_hold() {+        // z0 is id 0, and z1 walks its quadrants in Hilbert order.+        assert_eq!(tile_id(0, 0, 0), 0);+        assert_eq!(tile_zxy(0), (0, 0, 0));+        assert_eq!(tile_id(1, 0, 0), 1);+        assert_eq!(tile_id(1, 0, 1), 2);+        assert_eq!(tile_id(1, 1, 1), 3);+        assert_eq!(tile_id(1, 1, 0), 4);+    }++    #[test]+    fn the_real_fixture_tile_id_round_trips() {+        // The id the published archive actually stored for our fixture tile. An+        // earlier hand-computed z/x/y for this was wrong, so the assertion is on+        // the round-trip and the zoom rather than on remembered coordinates.+        let id = 2_229_854u64;+        let (z, x, y) = tile_zxy(id);+        assert_eq!(z, 11, "the fixture came from a zoom-11 entry");+        assert_eq!(tile_id(z, x, y), id, "z{z}/{x}/{y} must map back to {id}");+        assert!(x < (1 << 11) && y < (1 << 11), "coords inside the z11 grid");+    }++    #[test]+    fn a_directory_round_trips() {+        let entries = vec![+            Entry { tile_id: 0, offset: 0, length: 100, run_length: 1 },+            // Contiguous: exercises the offset-0 shorthand.+            Entry { tile_id: 1, offset: 100, length: 50, run_length: 3 },+            // A jump, so a real offset must be written.+            Entry { tile_id: 99, offset: 9000, length: 7, run_length: 1 },+            // A leaf pointer.+            Entry { tile_id: 500, offset: 12, length: 34, run_length: 0 },+        ];+        let body = serialize_directory(&entries);+        assert_eq!(parse_directory(&body).unwrap(), entries);+    }++    #[test]+    fn an_empty_directory_round_trips() {+        assert_eq!(parse_directory(&serialize_directory(&[])).unwrap(), vec![]);+    }++    #[test]+    fn a_header_round_trips() {+        let h = Header {+            root_offset: 127,+            root_length: 1352,+            metadata_offset: 1479,+            metadata_length: 67106,+            leaf_offset: 68585,+            leaf_length: 2340693,+            tile_data_offset: 2409278,+            tile_data_length: 1614828579,+            addressed_tiles: 1571621,+            tile_entries: 1324064,+            tile_contents: 1026180,+            clustered: true,+            internal_compression: COMPRESSION_GZIP,+            tile_compression: COMPRESSION_GZIP,+            tile_type: TILE_TYPE_MVT,+            min_zoom: 0,+            max_zoom: 16,+            min_lon_e7: -1_800_000_000,+            min_lat_e7: -850_511_290,+            max_lon_e7: 1_800_000_000,+            max_lat_e7: 850_511_290,+            center_zoom: 16,+            center_lon_e7: -1_224_069_210,+            center_lat_e7: 377_945_930,+        };+        let bytes = h.serialize();+        assert_eq!(bytes.len(), HEADER_LEN);+        let back = Header::parse(&bytes).unwrap();+        assert_eq!(back.root_offset, h.root_offset);+        assert_eq!(back.tile_data_length, h.tile_data_length);+        assert_eq!(back.center_lat_e7, h.center_lat_e7);+        assert_eq!(back.max_zoom, h.max_zoom);+        assert!(back.clustered);+    }++    // --- Against the real published archive --------------------------------++    #[test]+    fn the_real_header_parses_to_its_known_values() {+        let h = Header::parse(REAL_HEAD).expect("the published header");+        assert_eq!(h.root_offset, 127);+        assert_eq!(h.root_length, 1352);+        assert_eq!(h.metadata_offset, 1479);+        assert_eq!(h.leaf_offset, 68585);+        assert_eq!(h.tile_data_offset, 2409278);+        assert_eq!(h.addressed_tiles, 1571621);+        assert_eq!(h.tile_entries, 1324064);+        assert_eq!(h.tile_contents, 1026180);+        assert!(h.clustered);+        assert_eq!(h.internal_compression, COMPRESSION_GZIP);+        assert_eq!(h.tile_compression, COMPRESSION_GZIP);+        assert_eq!(h.tile_type, TILE_TYPE_MVT);+        assert_eq!((h.min_zoom, h.max_zoom), (0, 16));+        // Whole Mercator world, centred on San Francisco.+        assert_eq!(h.min_lon_e7, -1_800_000_000);+        assert_eq!(h.max_lat_e7, 850_511_290);+        assert_eq!(h.center_lon_e7, -1_224_069_210);+        assert_eq!(h.center_lat_e7, 377_945_930);+    }++    #[test]+    fn the_real_root_directory_parses_and_re_serializes() {+        let h = Header::parse(REAL_HEAD).unwrap();+        let raw = &REAL_HEAD[h.root_offset as usize..(h.root_offset + h.root_length) as usize];+        let body = gz::decompress(raw).expect("gzipped root directory");+        assert_eq!(body.len(), 2004, "known inflated size of the real root directory");++        let entries = parse_directory(&body).expect("the real root directory");+        assert_eq!(entries.len(), 324, "known entry count");+        // Every root entry in this archive is a leaf pointer.+        assert!(entries.iter().all(|e| e.run_length == 0), "all leaf pointers");+        assert_eq!(entries[0].tile_id, 0);+        assert_eq!(entries[0].offset, 0);+        assert_eq!(entries[0].length, 9222);+        assert_eq!(entries[1].tile_id, 2_230_397);++        // Byte-exact: our serializer reproduces tippecanoe's directory encoding,+        // including its use of the contiguous-offset shorthand.+        assert_eq!(serialize_directory(&entries), body, "directory re-serializes byte-exactly");+    }++    // --- Whole-archive round trip -------------------------------------------++    #[test]+    fn an_archive_round_trips_through_build_and_parse() {+        let mut b = Builder::new();+        b.max_zoom = 2;+        b.metadata = br#"{"name":"test"}"#.to_vec();+        b.add_tile(0, 0, 0, b"tile-zero");+        b.add_tile(1, 0, 0, b"tile-one");+        b.add_tile(2, 3, 1, REAL_TILE_MVT);+        let bytes = b.build().unwrap();++        let a = Archive::parse(&bytes).expect("our own archive parses");+        assert_eq!(a.metadata, br#"{"name":"test"}"#);+        assert_eq!(a.header.max_zoom, 2);+        assert_eq!(a.tile(0, 0, 0).unwrap().unwrap(), b"tile-zero");+        assert_eq!(a.tile(1, 0, 0).unwrap().unwrap(), b"tile-one");+        assert_eq!(a.tile(2, 3, 1).unwrap().unwrap(), REAL_TILE_MVT);+        // Absent tiles are None, not an error.+        assert!(a.tile(1, 1, 1).unwrap().is_none());+        assert!(a.tile(9, 0, 0).unwrap().is_none());+    }++    #[test]+    fn identical_tiles_are_stored_once_and_run_length_encoded() {+        let mut b = Builder::new();+        b.max_zoom = 4;+        // Four consecutive ids with identical bodies, the ocean-tile case.+        let base = tile_id(4, 0, 0);+        for k in 0..4 {+            b.add_tile_raw(base + k, gz::compress(b"same"));+        }+        let bytes = b.build().unwrap();+        let a = Archive::parse(&bytes).unwrap();+        assert_eq!(a.header.addressed_tiles, 4, "four addressable tiles");+        assert_eq!(a.header.tile_entries, 1, "collapsed into one run");+        assert_eq!(a.header.tile_contents, 1, "one distinct body");+        // All four still resolve.+        for k in 0..4 {+            let (z, x, y) = tile_zxy(base + k);+            assert_eq!(a.tile(z, x, y).unwrap().unwrap(), b"same", "tile {k}");+        }+    }++    #[test]+    fn a_large_archive_spills_into_leaf_directories() {+        // Enough distinct tiles that the root cannot hold them all, forcing the+        // two-level layout the real archive uses.+        let mut b = Builder::new();+        b.max_zoom = 8;+        let n = 20_000u64;+        let base = tile_id(8, 0, 0);+        for k in 0..n {+            b.add_tile_raw(base + k, gz::compress(format!("tile {k}").as_bytes()));+        }+        let bytes = b.build().unwrap();+        let a = Archive::parse(&bytes).unwrap();+        assert!(a.header.leaf_length > 0, "must have spilled into leaves");+        assert!(+            a.header.root_length as usize <= MAX_ROOT_BYTES,+            "root must stay within one request"+        );+        // Spot-check across leaf boundaries.+        for k in [0u64, 1, 4095, 4096, 4097, 9999, n - 1] {+            let (z, x, y) = tile_zxy(base + k);+            assert_eq!(+                a.tile(z, x, y).unwrap().unwrap(),+                format!("tile {k}").as_bytes(),+                "tile {k}"+            );+        }+        assert_eq!(a.iter_tiles().unwrap().len(), n as usize, "every tile enumerated");+    }++    #[test]+    fn a_truncated_archive_errors_rather_than_panicking() {+        let mut b = Builder::new();+        b.add_tile(0, 0, 0, b"x");+        let bytes = b.build().unwrap();+        assert!(Archive::parse(&bytes[..HEADER_LEN - 1]).is_err(), "short header");+        assert!(Archive::parse(&bytes[..bytes.len() / 2]).is_err(), "clipped body");+        let mut bad = bytes.clone();+        bad[0] = b'X';+        assert!(Archive::parse(&bad).is_err(), "bad magic");+        let mut bad = bytes.clone();+        bad[7] = 2;+        assert!(Archive::parse(&bad).is_err(), "wrong spec version");+    }+}
scripts/maps/tile_build/tests/fixtures/README.md
diff --git a/scripts/maps/tile_build/tests/fixtures/README.md b/scripts/maps/tile_build/tests/fixtures/README.mdindex 131e43f39a..b1e597bc31 100644--- a/scripts/maps/tile_build/tests/fixtures/README.md+++ b/scripts/maps/tile_build/tests/fixtures/README.md@@ -7,8 +7,12 @@ One real tile lifted out of the published basemap, via a ranged GET. Stored **inflated** -- the archive gzips its tiles, but that is the container's business, so the MVT tests work on the raw protobuf. -PMTiles `tile_id` 2229854, which is zoom 11. Contents, as decoded from the-published file at the time it was captured:+PMTiles ``tile_id`` 2229854, which is **z11/339/770** -- north-eastern California+(NW corner lon -120.4102, lat 40.7140). The zoom/x/y were derived with the crate's+own ``tile_zxy``, which is exhaustively round-trip tested; an earlier hand+calculation put this tile in the Arctic and was wrong.++Contents, as decoded from the published file at the time it was captured:  | layer  | features | keys | values | extent | version | |--------|----------|------|--------|--------|---------|@@ -22,4 +26,25 @@ the tile-join step depends on: our own writer only ever emits points, but the composite has to carry the base tileset's lines and polygons through untouched.  Its purpose is to pin the decoder against genuine tippecanoe output. A synthetic-round-trip only proves we agree with ourselves.+round-trip only proves we agree with ourselves.++## ``v5ca_z11_tile.mvt.gz``++The same tile, exactly as the archive stores it: gzipped. Proves the gzip reader+handles a real producer's stream and inflates to ``v5ca_z11_tile.mvt`` byte for+byte.++## ``v5ca_header_rootdir.bin``++Bytes ``0..1479`` of the same archive -- the 127-byte v3 header plus its entire+gzipped root directory (which ends exactly where ``metadata_offset`` begins).++Enough to test header parsing and directory decoding against real data without+carrying the 1.5 GB file. Note the offsets inside it address that full file, so it+cannot be opened as a standalone archive; the tests parse the header and root+directory specifically.++Known values: 324 root entries, all leaf pointers, inflating to 2004 bytes. Our+serializer reproduces those 2004 bytes exactly, which is what proves the writer+agrees with tippecanoe on the directory encoding -- including its use of the+contiguous-offset shorthand.
scripts/maps/tile_build/tests/fixtures/v5ca_header_rootdir.bin
diff --git a/scripts/maps/tile_build/tests/fixtures/v5ca_header_rootdir.bin b/scripts/maps/tile_build/tests/fixtures/v5ca_header_rootdir.binnew file mode 100644index 0000000000..f82a1756b8Binary files /dev/null and b/scripts/maps/tile_build/tests/fixtures/v5ca_header_rootdir.bin differ
scripts/maps/tile_build/tests/fixtures/v5ca_z11_tile.mvt.gz
diff --git a/scripts/maps/tile_build/tests/fixtures/v5ca_z11_tile.mvt.gz b/scripts/maps/tile_build/tests/fixtures/v5ca_z11_tile.mvt.gznew file mode 100644index 0000000000..945bbfe3e6Binary files /dev/null and b/scripts/maps/tile_build/tests/fixtures/v5ca_z11_tile.mvt.gz differ