Modern Apps git

← Modern-Apps.git

tilecodec: v9 format gates + zstd body codec

Commit
f8d24686d9590df5ab7ec5ab86285f2b21327df3
Author
vayun-mathur <[email protected]>
When
2026-10-10 03:18 UTC (1 month ago)
Parents
de4ba9d

Diff

library/tilecodec/src/main/rust/Cargo.lock
diff --git a/library/tilecodec/src/main/rust/Cargo.lock b/library/tilecodec/src/main/rust/Cargo.lockindex ee12687c3f..d106023ce2 100644--- a/library/tilecodec/src/main/rust/Cargo.lock+++ b/library/tilecodec/src/main/rust/Cargo.lock@@ -17,9 +17,32 @@ dependencies = [  "adler2", ] +[[package]]+name = "ruzstd"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7c1c839d570d835527c9a5e4db7cb2198683a988cb9d7293fc8674e6bd58fc8"+dependencies = [+ "twox-hash",+]+ [[package]] name = "tilecodec" version = "0.1.0" dependencies = [  "miniz_oxide",+ "ruzstd",+ "zstd-rs", ]++[[package]]+name = "twox-hash"+version = "2.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2"++[[package]]+name = "zstd-rs"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41514ccc30389f95bb9e6ab6d5634f17121c7b4fead6722a5fceec1c7891d78f"
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 4185aeb4d6..493a4b3970 100644--- a/library/tilecodec/src/main/rust/Cargo.toml+++ b/library/tilecodec/src/main/rust/Cargo.toml@@ -34,7 +34,7 @@ description = "PMTiles v3, Mapbox Vector Tile 2.1 and .mamaps codecs shared by t # 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 = []+write = ["dep:zstd-rs"]  [lib] name = "tilecodec"@@ -42,6 +42,14 @@ path = "src/lib.rs"  [dependencies] miniz_oxide = "0.8"+# Pure-Rust zstd decoder for v9 bodies (no C toolchain, so the+# aarch64-linux-android cdylib keeps its single-pure-Rust-dependency+# property — see the crate docs above). Decode-only here; the host-side+# encoder arrives with the writer change.+ruzstd = "0.8"+# Pure-Rust zstd encoder, host-side only (writer): v9 bodies. Optional so the+# cdylib never links it — Android reads archives, it never writes one.+zstd-rs = { version = "0.1", optional = true }  # Detach from both the repo-root Android workspace and `tile_build`'s. [workspace]
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 283d267cd7..de54b8c11b 100644--- a/library/tilecodec/src/main/rust/src/lib.rs+++ b/library/tilecodec/src/main/rust/src/lib.rs@@ -37,3 +37,8 @@ pub mod mvt; pub mod pmtiles; pub mod proto; pub mod stream;++/// Blocked zstd sections ([`blocked`]): random-access compression for graph+/// tables. Read side always linked; the writer ([`blocked::write_blocked`])+/// is behind the `write` feature like the tile writer.+pub mod blocked;
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.rsindex a0e6bfc279..bbf2527383 100644--- a/library/tilecodec/src/main/rust/src/mamaps/header.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/header.rs@@ -23,7 +23,8 @@ mod types; mod tests;  pub use consts::{-    COMPRESSION_DEFLATE, COMPRESSION_NONE, FLAG_BODIES_COMPRESSED, FLAG_LEAF_LEN_64,-    FLAG_RINGS_VALIDATED, FLAG_RUN_LENGTH_PRESENT, FORMAT_VERSION, HEADER_LEN, MAGIC, MAX_ZOOM,+    COMPRESSION_DEFLATE, COMPRESSION_NONE, COMPRESSION_ZSTD, FLAG_BODIES_COMPRESSED,+    FLAG_LEAF_LEN_64, FLAG_RINGS_VALIDATED, FLAG_RUN_LENGTH_PRESENT, FORMAT_VERSION,+    FORMAT_VERSION_V9, FORMAT_VERSION_V10, HEADER_LEN, MAGIC, MAX_ZOOM, }; pub use types::Header;
library/tilecodec/src/main/rust/src/mamaps/header/consts.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/header/consts.rs b/library/tilecodec/src/main/rust/src/mamaps/header/consts.rsindex 498ce8a21b..2591168707 100644--- a/library/tilecodec/src/main/rust/src/mamaps/header/consts.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/header/consts.rs@@ -65,6 +65,22 @@ pub const MAGIC: &[u8; 7] = b"MAMAPS\0"; /// The reader speaks v8 only: any other version byte is refused on open. pub const FORMAT_VERSION: u8 = 8; +/// The v9 format version: zstd bodies, compressed leaves, packed sidecars.+///+/// Bumped for the structural-savings rebuild. A v9 archive is refused by a v8+/// reader (clean rejection, not a wrong map); a v9 reader still refuses+/// anything it does not speak. See the v8 history above for what forces a bump.+pub const FORMAT_VERSION_V9: u8 = 9;++/// The v10 format version: narrowed body records.+///+/// v10 bodies drop dead bytes from feature records (per-layer classes),+/// shrink part entries 12 B to 4 B, and store side tables bitset+sparse. The+/// header/index framing is unchanged from v9; only body payloads differ, gated+/// by the per-body version byte. A v10 body in a v8 archive is refused at the+/// body, not the header — but builders ship v10 bodies under v9+ headers.+pub const FORMAT_VERSION_V10: u8 = 10;+ pub const HEADER_LEN: usize = 128;  /// Bodies are compressed frames; clear means the body is stored raw.@@ -95,6 +111,13 @@ pub const COMPRESSION_NONE: u8 = 0; /// 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;+/// zstd, one independent frame per body (v9 only).+///+/// Same framing as DEFLATE (raw frame behind the uncompressed 16-byte body+/// header), different codec. Encoder and decoder are pure Rust (`zstd-rs` /+/// `ruzstd`) so the aarch64-linux-android cdylib keeps its no-C-toolchain+/// property — see the crate docs in `Cargo.toml`.+pub const COMPRESSION_ZSTD: u8 = 2;  /// The deepest zoom a `tile_id_lo` can span inside one leaf. See [`crate::mamaps::index`]. pub const MAX_ZOOM: u8 = 22;
library/tilecodec/src/main/rust/src/mamaps/header/parse.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/header/parse.rs b/library/tilecodec/src/main/rust/src/mamaps/header/parse.rsindex 414d70bc6f..182bbbb68b 100644--- a/library/tilecodec/src/main/rust/src/mamaps/header/parse.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/header/parse.rs@@ -7,8 +7,8 @@ use crate::proto::{err, Result};  use super::consts::{-    COMPRESSION_DEFLATE, COMPRESSION_NONE, FLAG_LEAF_LEN_64, FORMAT_VERSION, HEADER_LEN,-    KNOWN_FLAGS, MAGIC, MAX_ZOOM,+    COMPRESSION_DEFLATE, COMPRESSION_NONE, COMPRESSION_ZSTD, FLAG_LEAF_LEN_64, FORMAT_VERSION,+    FORMAT_VERSION_V9, HEADER_LEN, KNOWN_FLAGS, MAGIC, MAX_ZOOM, }; use super::types::Header; @@ -32,9 +32,9 @@ impl Header {             return err("not a .mamaps archive (bad magic)");         }         let version = buf[7];-        if version != FORMAT_VERSION {+        if version != FORMAT_VERSION && version != FORMAT_VERSION_V9 {             return err(format!(-                "unsupported .mamaps format version {version} (this reader speaks v{FORMAT_VERSION})",+                "unsupported .mamaps format version {version} (this reader speaks v{FORMAT_VERSION} and v{FORMAT_VERSION_V9})",             ));         }         let u16_at = |o: usize| u16::from_le_bytes([buf[o], buf[o + 1]]);@@ -132,7 +132,10 @@ impl Header {     /// 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.     pub(super) fn check(&self) -> Result<()> {-        if !matches!(self.compression, COMPRESSION_NONE | COMPRESSION_DEFLATE) {+        if !matches!(+            self.compression,+            COMPRESSION_NONE | COMPRESSION_DEFLATE | COMPRESSION_ZSTD+        ) {             return err(format!("unknown .mamaps compression {}", self.compression));         }         if self.compressed() != (self.compression != COMPRESSION_NONE) {
library/tilecodec/src/main/rust/src/mamaps/header/tests.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/header/tests.rs b/library/tilecodec/src/main/rust/src/mamaps/header/tests.rsindex 2388e8c430..800594ff7b 100644--- a/library/tilecodec/src/main/rust/src/mamaps/header/tests.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/header/tests.rs@@ -65,8 +65,8 @@ fn a_truncated_or_foreign_header_is_refused() {     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 version past v8");+    wrong_version[7] = FORMAT_VERSION_V9 + 1;+    assert!(Header::parse(&wrong_version).is_err(), "a version past v9");     let mut wrong_len = bytes.clone();     wrong_len[8..10].copy_from_slice(&160u16.to_le_bytes());     assert!(Header::parse(&wrong_len).is_err(), "a v8 version declaring 160");@@ -119,6 +119,28 @@ fn an_offset_length_pair_cannot_overflow_into_looking_valid() {     assert!(Header::parse(&header.serialize()).is_err(), "the end wraps"); } +/// v9 parses wherever v8 does: same 128 bytes, new version byte only.+/// A v9 reader must accept both; anything else is refused.+#[test]+fn a_v9_header_parses_and_anything_past_v9_is_refused() {+    let mut bytes = plausible().serialize();+    bytes[7] = FORMAT_VERSION_V9;+    assert!(Header::parse(&bytes).is_ok(), "v9 must parse");+    for v in [0u8, 1, 7, 10, 255] {+        let mut bad = bytes.clone();+        bad[7] = v;+        assert!(Header::parse(&bad).is_err(), "version {v} must be refused");+    }+}++/// zstd is a known compression: the header carries it, the flag agrees.+#[test]+fn a_zstd_header_parses() {+    let mut header = plausible();+    header.compression = COMPRESSION_ZSTD;+    assert!(Header::parse(&header.serialize()).is_ok());+}+ /// Planet scale: leaf index is ~268M bodies ×16 B ≈4.29 GB > u32::MAX, /// overflowing the old 4 GiB leaf_len field by 1257 B in the failed run. /// Extended encoding uses FLAG_LEAF_LEN_64 and the formerly-reserved
library/tilecodec/src/main/rust/src/mamaps/read/helpers.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/read/helpers.rs b/library/tilecodec/src/main/rust/src/mamaps/read/helpers.rsindex c792730cca..1dc49bdfaa 100644--- a/library/tilecodec/src/main/rust/src/mamaps/read/helpers.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/read/helpers.rs@@ -1,8 +1,11 @@ use crate::mamaps::body::Body; use crate::mamaps::dict::Dictionary;-use crate::mamaps::header::{COMPRESSION_DEFLATE, COMPRESSION_NONE, Header, HEADER_LEN};+use crate::mamaps::header::{+    COMPRESSION_DEFLATE, COMPRESSION_NONE, COMPRESSION_ZSTD, Header, HEADER_LEN,+}; use crate::mamaps::index::{self, RootEntry}; use crate::proto::{Error, Result, err};+use std::io::Read as _;  /// Inflate one body frame, allocating exactly once. ///@@ -40,6 +43,39 @@ pub fn decompress(compression: u8, stored: &[u8]) -> Result<Vec<u8>> {             }             Ok(out)         }+        COMPRESSION_ZSTD => {+            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];+            let header_len = crate::mamaps::body::BODY_HEADER_LEN;+            out[..header_len].copy_from_slice(&stored[..header_len]);+            // Same framing as DEFLATE (raw frame behind the uncompressed+            // header), different codec. `ruzstd` is decode-only pure Rust.+            let mut decoder = ruzstd::decoding::StreamingDecoder::new(&stored[header_len..])+                .map_err(|e| Error(format!("a .mamaps zstd body will not decode: {e:?}")))?;+            let mut at = header_len;+            loop {+                if at >= raw_len {+                    break;+                }+                let n = decoder+                    .read(&mut out[at..])+                    .map_err(|e| Error(format!("a .mamaps zstd body will not decode: {e:?}")))?;+                if n == 0 {+                    break;+                }+                at += n;+            }+            if at != raw_len {+                return err(format!(+                    "a .mamaps zstd body decoded to {} bytes, not the {} it declares",+                    at, raw_len,+                ));+            }+            Ok(out)+        }         other => err(format!("unknown .mamaps compression {other}")),     } }
library/tilecodec/src/main/rust/src/mamaps/tests_extra.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/tests_extra.rs b/library/tilecodec/src/main/rust/src/mamaps/tests_extra.rsindex d7eb5dcfb1..011a34e550 100644--- a/library/tilecodec/src/main/rust/src/mamaps/tests_extra.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/tests_extra.rs@@ -201,6 +201,24 @@ fn an_archive_whose_dictionary_is_not_this_schema_is_refused_on_open() {     assert!(failure.0.contains("disagrees with this build's schema"), "{}", failure.0); } +/// A zstd body round-trips through the reader: same framing as DEFLATE (raw+/// frame behind the uncompressed 16-byte header), decoded by `ruzstd`.+#[test]+fn a_zstd_body_decodes_to_the_bytes_it_was_encoded_from() {+    use crate::mamaps::body::serialize;+    use crate::mamaps::read::decompress;+    use crate::mamaps::write::{compress_body, compress_body_zstd};+    let raw = serialize(&body_for(7)).expect("serialize");+    let stored = compress_body_zstd(&raw);+    assert_eq!(&stored[..16], &raw[..16], "header stays outside the frame");+    let back = decompress(crate::mamaps::header::COMPRESSION_ZSTD, &stored).expect("decode");+    assert_eq!(back, raw);+    // And the DEFLATE path is untouched by the new arm.+    let d_stored = compress_body(&raw);+    let d_back = decompress(crate::mamaps::header::COMPRESSION_DEFLATE, &d_stored).expect("inflate");+    assert_eq!(d_back, raw);+}+ /// Planet per-leaf data-span overflow: a leaf whose entries' max(offset)- /// min(offset) would exceed u32::MAX (planet: 4294968552 = u32::MAX+1257) /// must be split, otherwise LeafEntry.offset_delta (u32) overflows.
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.rsindex 3036b8a310..f95db94b05 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write.rs@@ -59,6 +59,8 @@ pub mod writer_extra; mod tests;  pub use codec::{compress_body, compress_body_with, hash64};+#[cfg(feature = "write")]+pub use codec::compress_body_zstd; pub use options::Options; pub use writer::StreamWriter; pub(crate) use writer::Pending;
library/tilecodec/src/main/rust/src/mamaps/write/codec.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/write/codec.rs b/library/tilecodec/src/main/rust/src/mamaps/write/codec.rsindex ad596dcfd9..5d931d2365 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/codec.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/codec.rs@@ -36,6 +36,30 @@ pub fn compress_body_with(deflate: &mut crate::gz::Compressor, encoded: &[u8]) -     out } +/// zstd over everything but the body header (v9 only).+///+/// Same framing as [`compress_body`] — 16-byte header ahead of one independent+/// frame — different codec. Host-side only (`write` feature): the device reads+/// v9 bodies with `ruzstd` and never encodes. Level 19 is zstd's archive+/// default (bytes over build seconds, same trade DEFLATE-9 makes).+/// Deterministic for fixed input + config, which is what keeps builds+/// byte-identical.+#[cfg(feature = "write")]+pub fn compress_body_zstd(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]);+    let cfg = zstd_rs::CompressionConfig {+        level: 19,+        ..zstd_rs::CompressionConfig::DEFAULT+    };+    let mut enc =+        zstd_rs::Compressor::new(cfg).expect("zstd compressor with a valid level");+    enc.compress(&encoded[header_len..], None, &mut out)+        .expect("zstd encode of an in-memory body");+    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. ///