Modern Apps git

← Modern-Apps.git

maps: encode tiles from borrowed props, dropping a clone per candidate

Commit
2ad084191ac5be794237390e675f679a40dbccf7
Author
vayun-mathur <[email protected]>
When
2026-08-26 04:22 UTC (3 months ago)
Parents
b548e31

Diff

scripts/maps/tile_build/src/mvt.rs
diff --git a/scripts/maps/tile_build/src/mvt.rs b/scripts/maps/tile_build/src/mvt.rsindex e4be5c9ea9..87883d63aa 100644--- a/scripts/maps/tile_build/src/mvt.rs+++ b/scripts/maps/tile_build/src/mvt.rs@@ -161,6 +161,25 @@ impl Feature {     } } +/// One feature as the encoder actually needs it: nothing owned.+///+/// The producers already own their geometry and properties somewhere — the pyramid in a+/// candidate list, the point tiler in its input slice — and copying both into a+/// [`Feature`] just to encode it made the per-candidate `props` clone the largest+/// allocation in the tiler: measured at ~35% of single-threaded tile encode time, since+/// every property key and string value is a separate heap copy per tile a feature+/// touches.+///+/// [`encode_layer_from`] is the single implementation; [`Tile::encode`] feeds it views of+/// its owned features, so the two paths cannot drift apart and produce different bytes.+pub struct FeatureRef<'a> {+    pub id: Option<u64>,+    pub geom_type: GeomType,+    /// Raw MVT command integers, re-emitted verbatim. See the module docs.+    pub geometry: &'a [u32],+    pub props: &'a [(String, Value)],+}+ #[derive(Debug, Clone)] pub struct Layer {     pub name: String,@@ -289,7 +308,33 @@ fn decode_feature(buf: &[u8], keys: &[String], values: &[Value]) -> Result<Featu }  fn encode_layer(layer: &Layer, out: &mut Writer) {-    out.string_field(1, &layer.name);+    encode_layer_from(+        &layer.name,+        layer.extent,+        layer.version,+        layer.features.iter().map(|f| FeatureRef {+            id: f.id,+            geom_type: f.geom_type,+            geometry: &f.geometry,+            props: &f.props,+        }),+        out,+    );+}++/// Encode a single layer body from borrowed features.+///+/// The one implementation of the layer encoder: [`encode_layer`] is a thin view over+/// owned [`Feature`]s, and the tilers pass their own data straight in. See+/// [`FeatureRef`].+pub fn encode_layer_from<'a>(+    name: &str,+    extent: u32,+    version: u32,+    features: impl IntoIterator<Item = FeatureRef<'a>>,+    out: &mut Writer,+) {+    out.string_field(1, name);      // Dictionaries are rebuilt from the decoded properties, interning on first use.     let mut keys: Vec<&str> = Vec::new();@@ -300,14 +345,14 @@ fn encode_layer(layer: &Layer, out: &mut Writer) {     let mut feat_buf = Writer::new();     let mut tag_buf = Writer::new();     let mut geom_buf = Writer::new();-    for f in &layer.features {+    for f in features {         feat_buf.clear();         if let Some(id) = f.id {             feat_buf.varint_field(1, id);         }          tag_buf.clear();-        for (k, v) in &f.props {+        for (k, v) in f.props {             let ki = *key_idx.entry(k.as_str()).or_insert_with(|| {                 keys.push(k.as_str());                 (keys.len() - 1) as u32@@ -329,7 +374,7 @@ fn encode_layer(layer: &Layer, out: &mut Writer) {         }         if !f.geometry.is_empty() {             geom_buf.clear();-            for &g in &f.geometry {+            for &g in f.geometry {                 geom_buf.uvarint(g as u64);             }             feat_buf.bytes_field(4, geom_buf.as_slice());@@ -347,8 +392,24 @@ fn encode_layer(layer: &Layer, out: &mut Writer) {         out.message(4, &val_buf);     } -    out.varint_field(5, layer.extent as u64);-    out.varint_field(15, layer.version as u64);+    out.varint_field(5, extent as u64);+    out.varint_field(15, version as u64);+}++/// Encode a whole one-layer tile body from borrowed features.+///+/// Byte-for-byte what `Tile { layers: vec![one] }.encode()` produces — the layer+/// wrapper is field 3 either way — which is what the tilers rely on.+pub fn encode_tile_from<'a>(+    name: &str,+    extent: u32,+    features: impl IntoIterator<Item = FeatureRef<'a>>,+) -> Vec<u8> {+    let mut layer_buf = Writer::new();+    encode_layer_from(name, extent, DEFAULT_VERSION, features, &mut layer_buf);+    let mut out = Writer::new();+    out.message(3, &layer_buf);+    out.into_vec() }  // --- Geometry command integers ------------------------------------------------
scripts/maps/tile_build/src/pyramid.rs
diff --git a/scripts/maps/tile_build/src/pyramid.rs b/scripts/maps/tile_build/src/pyramid.rsindex c729c3c62e..951e745024 100644--- a/scripts/maps/tile_build/src/pyramid.rs+++ b/scripts/maps/tile_build/src/pyramid.rs@@ -43,7 +43,7 @@  use crate::clip::clip_geometry; use crate::geom::{self, Geometry, IntGeometry};-use crate::mvt::{self, Feature as MvtFeature, GeomType, Layer, Tile, Value, DEFAULT_EXTENT};+use crate::mvt::{self, FeatureRef as MvtFeature, GeomType, Value, DEFAULT_EXTENT}; use crate::par; use crate::pmtiles::{self, Builder}; use crate::progress::Progress;@@ -407,10 +407,14 @@ fn fit_tile(     opts: &Options,     gz: &mut crate::gz::Compressor, ) -> Result<(Vec<u8>, usize, bool)> {+    // Reused across the binary search's calls, so an over-budget tile does not+    // reallocate its geometry list once per probe.+    let mut geoms: Vec<Vec<u32>> = Vec::new();+    let mut kept_at: Vec<usize> = Vec::new();     let mut encode = |n: usize| -> Vec<u8> {-        let mut layer = Layer::new(layer_name);-        layer.extent = opts.extent;-        for c in &candidates[..n] {+        geoms.clear();+        kept_at.clear();+        for (at, c) in candidates[..n].iter().enumerate() {             let geometry = match c.geom {                 IntGeometry::Points(p) => mvt::encode_points(p),                 IntGeometry::Lines(l) => mvt::encode_lines(l),@@ -419,14 +423,22 @@ fn fit_tile(             if geometry.is_empty() {                 continue;             }-            layer.features.push(MvtFeature {+            geoms.push(geometry);+            kept_at.push(at);+        }+        // Properties are BORROWED here. Cloning them per candidate per tile was ~35%+        // of this function's cost, and a feature reaching many tiles paid it once per+        // tile. See `mvt::FeatureRef`.+        let refs = kept_at+            .iter()+            .zip(geoms.iter())+            .map(|(&at, geometry)| MvtFeature {                 id: None,                 geom_type,                 geometry,-                props: c.props.to_vec(),+                props: candidates[at].props,             });-        }-        gz.compress(&Tile { layers: vec![layer] }.encode())+        gz.compress(&mvt::encode_tile_from(layer_name, opts.extent, refs))     };      let all = encode(candidates.len());@@ -1454,6 +1466,7 @@ fn report_and_exit( #[cfg(test)] mod tests {     use super::*;+    use crate::mvt::Tile;     use crate::pmtiles::Archive;      fn line(coords: &[(f64, f64)], props: Vec<(&str, Value)>) -> Feature {
scripts/maps/tile_build/src/tiling.rs
diff --git a/scripts/maps/tile_build/src/tiling.rs b/scripts/maps/tile_build/src/tiling.rsindex dd1d6efa75..daaac54b07 100644--- a/scripts/maps/tile_build/src/tiling.rs+++ b/scripts/maps/tile_build/src/tiling.rs@@ -8,7 +8,7 @@ //! which is what makes a composite lossless.  use crate::geom::project;-use crate::mvt::{self, Feature, GeomType, Layer, Tile, Value, DEFAULT_EXTENT};+use crate::mvt::{self, GeomType, Tile, Value, DEFAULT_EXTENT}; use crate::par; use crate::pmtiles::{self, Archive, ArchiveFile, Builder}; use crate::progress::Progress;@@ -72,18 +72,25 @@ pub fn tile_points(             .map(|((tx, ty), pts)| {                 // Deterministic feature order, so a rebuild is byte-identical.                 pts.sort_by_key(|&(x, y, i)| (x, y, i));-                let mut layer = Layer::new(layer_name);-                layer.extent = extent;-                for &(x, y, i) in pts.iter() {-                    layer.features.push(Feature {-                        id: None,-                        geom_type: GeomType::Point,-                        geometry: mvt::encode_points(&[(x, y)]),-                        props: points[i].props.clone(),-                    });-                }-                let tile = Tile { layers: vec![layer] };-                (pmtiles::tile_id(z, *tx, *ty), tile.encode())+                // Geometry first, so the borrowed views below have something to point+                // at; properties are never copied. See `mvt::FeatureRef`.+                let geoms: Vec<Vec<u32>> = pts+                    .iter()+                    .map(|&(x, y, _)| mvt::encode_points(&[(x, y)]))+                    .collect();+                let body = mvt::encode_tile_from(+                    layer_name,+                    extent,+                    pts.iter().zip(geoms.iter()).map(|(&(_, _, i), geometry)| {+                        mvt::FeatureRef {+                            id: None,+                            geom_type: GeomType::Point,+                            geometry,+                            props: &points[i].props,+                        }+                    }),+                );+                (pmtiles::tile_id(z, *tx, *ty), body)             })             .collect()     });@@ -772,6 +779,7 @@ pub fn merge_tiles(bodies: &[Vec<u8>]) -> Result<Vec<u8>> { #[cfg(test)] mod tests {     use super::*;+    use crate::mvt::{Feature, Layer};      const REAL_TILE: &[u8] = include_bytes!("../tests/fixtures/v5ca_z11_tile.mvt");