Modern Apps git

← Modern-Apps.git

maps: add tile_lines and tile_polygons with a deterministic drop policy

Commit
089c4b249d4bb2d2e0daed0b1b85667be470e16d
Author
vayun-mathur <[email protected]>
When
2026-08-21 06:22 UTC (3 months ago)
Parents
c0d681e

Diff

scripts/maps/README.md
diff --git a/scripts/maps/README.md b/scripts/maps/README.mdindex 07365b0435..2fa4d6c884 100644--- a/scripts/maps/README.md+++ b/scripts/maps/README.md@@ -178,7 +178,7 @@ mutually consistent (same POI set, same coordinates). See | `build_transit_stops_layer.sh` | GTFS dirs → `gtfs_ingest` `transit_stops` → geojsonseq → `tile_build` `tile_points` → `transit_stops.pmtiles`. **No tippecanoe, no osmium** | | `build_transit_stops_layer.ps1` | **Windows** entry point for the same layer (cargo-only) | | `gtfs_ingest/` | Rust GTFS crate (detached): `gtfs_ingest` (the on-device `.transit` pack) and `transit_stops` (the basemap stop layer). TRX2 on-disk format documented in `src/index.rs` |-| `tile_build/` | Rust MVT + PMTiles v3 crate (detached), **replacing tippecanoe and tile-join**. Bins: `tile_points` (tile a point geojsonseq), `tile_join` (merge archives), `pmtiles_dump` (canonical text dump, for the differential harness). Library: `geom` (web-mercator projection, tile ranges, quantisation), `clip` (Liang-Barsky for lines, Sutherland-Hodgman for polygons), `simplify` (Douglas-Peucker in integer tile coordinates), `mvt` (line and polygon encoders beside the opaque passthrough that keeps `tile_join` lossless). Container layout documented in `src/pmtiles.rs`, the pipeline order in `src/geom.rs` |+| `tile_build/` | Rust MVT + PMTiles v3 crate (detached), **replacing tippecanoe and tile-join**. Bins: `tile_points` / `tile_lines` / `tile_polygons` (one per geometry kind), `tile_join` (merge archives), `pmtiles_dump` (canonical text dump, for the differential harness). Library: `geojson` (the shared GeoJSONSeq reader), `geom` (web-mercator projection, tile ranges, quantisation), `clip` (Liang-Barsky for lines, Sutherland-Hodgman for polygons), `simplify` (Douglas-Peucker in integer tile coordinates), `pyramid` (the tile pyramid driver and the drop policy), `mvt` (line and polygon encoders beside the opaque passthrough that keeps `tile_join` lossless). Container layout documented in `src/pmtiles.rs`, the pipeline order in `src/geom.rs`, the drop policy in `src/pyramid.rs` | | `publish_r2.sh` | Upload built artifacts to Cloudflare R2 (creds from env vars only) | | `normalize_safety.py` | OSM tags → `safety` layer schema (pure stdlib, unit-tested). **Superseded** by `osm_ingest/src/safety.rs`; kept as the contract of record and as `--engine legacy` for the differential harness | | `normalize_maxspeed.py` | OSM maxspeed ways → `maxspeed` layer schema (pure stdlib, unit-tested) |@@ -215,23 +215,39 @@ which change on a different clock and from a different source.  ### 3. Output is not byte-identical to tippecanoe, by design -`--drop-densest-as-needed` is a lossy per-tile heuristic, and-`--extend-zooms-if-still-dropping` can push an archive *past* its own-`--maximum-zoom`. Our tilers implement a deterministic, documented drop policy-and a fixed max zoom instead. Consequences:--* Per-tile feature counts differ. `test/diff_pmtiles.py --max-feature-delta`-  is the explicit budget for that; the flag exists so the divergence has a number-  rather than being unbounded.+`--drop-densest-as-needed` is a lossy per-tile heuristic whose result depends on+the order tippecanoe happened to visit features. Our tilers use a deterministic+policy instead, documented in `tile_build/src/pyramid.rs`:++* Features in a tile are put in a **stable importance order** — largest bounding+  box first, ties broken by input index — and the largest prefix that fits the+  gzipped byte budget (500 KB by default, `--max-tile-bytes`) is kept, found by+  binary search. A prefix, so the kept set is always the top-k, never a scattered+  subset.+* If even one feature does not fit, that one is kept anyway and the tile is+  **reported as over budget**. An empty tile is a hole in the map; an oversized one+  is merely slow.+* Every run prints a per-zoom table: tiles, placements, kept, dropped, largest tile.++Consequences:++* Per-tile feature counts differ from tippecanoe's. `test/diff_pmtiles.py+  --max-feature-delta` is the explicit budget for that; the flag exists so the+  divergence has a number rather than being unbounded. * Tests assert **our own invariants** (ring closure, winding order,-  Douglas-Peucker monotonicity, PMTiles round-trip), never equality with+  Douglas-Peucker monotonicity, PMTiles round trip), never equality with   tippecanoe. * An MVT re-encode rebuilds each layer's key/value dictionaries in first-use   order, so even an untouched tile can come back a few bytes different. Compare   the decoded model, which is what the spec defines.-* `--detect-shared-borders` is not reproduced. Adjacent admin polygons are-  simplified independently, so at low zoom a shared border can show a hairline-  gap or overlap. Noted rather than papered over.+* **`--extend-zooms-if-still-dropping` is deliberately not reproduced.** It can+  push an archive *past* its own `--maximum-zoom`, so the advertised zoom range+  stops being a fact about the contents. Here `--maxzoom` is exactly the deepest+  zoom present.+* **`--detect-shared-borders` is not implemented.** Adjacent admin polygons are+  simplified independently, so two countries sharing a border can end up with+  slightly different vertex sets along it — visible at low zoom as a hairline gap+  or overlap. Reproducing it needs a shared topology pass across features.  ### 4. World transit is a large step up in cost 
scripts/maps/tile_build/Cargo.toml
diff --git a/scripts/maps/tile_build/Cargo.toml b/scripts/maps/tile_build/Cargo.tomlindex b0ec17188d..7a3a994aa4 100644--- a/scripts/maps/tile_build/Cargo.toml+++ b/scripts/maps/tile_build/Cargo.toml@@ -29,6 +29,12 @@ path = "src/lib.rs" name = "tile_points" path = "src/bin/tile_points.rs" [[bin]]+name = "tile_lines"+path = "src/bin/tile_lines.rs"+[[bin]]+name = "tile_polygons"+path = "src/bin/tile_polygons.rs"+[[bin]] name = "tile_join" path = "src/bin/tile_join.rs" [[bin]]
scripts/maps/tile_build/src/bin/tile_lines.rs
diff --git a/scripts/maps/tile_build/src/bin/tile_lines.rs b/scripts/maps/tile_build/src/bin/tile_lines.rsnew file mode 100644index 0000000000..bb2b3520d8--- /dev/null+++ b/scripts/maps/tile_build/src/bin/tile_lines.rs@@ -0,0 +1,20 @@+//! `tile_lines` — tile a geojsonseq line file into a single-layer PMTiles archive.+//! The `tippecanoe` replacement for line layers (`maxspeed`, `transit_lines`).+//!+//! Usage:+//!   tile_lines --geojson IN.geojsonseq --out OUT.pmtiles --layer NAME+//!              [--minzoom N] [--maxzoom N] [--simplification F]+//!              [--max-tile-bytes N] [--extent N]+//!+//! Input is one GeoJSON `Feature` per line with `LineString` or `MultiLineString`+//! geometry; anything else is counted and skipped. See `osm_ingest::extract` for+//! the producer and `tile_build::pyramid` for the drop policy, which is+//! deliberately *not* tippecanoe's `--drop-densest-as-needed`.++use std::process::ExitCode;+use tile_build::pyramid::{cli_main, Accept};++fn main() -> ExitCode {+    let argv: Vec<String> = std::env::args().skip(1).collect();+    cli_main("tile_lines", Accept::Lines, &argv)+}
scripts/maps/tile_build/src/bin/tile_points.rs
diff --git a/scripts/maps/tile_build/src/bin/tile_points.rs b/scripts/maps/tile_build/src/bin/tile_points.rsindex 589e7f735b..f8d83c8c98 100644--- a/scripts/maps/tile_build/src/bin/tile_points.rs+++ b/scripts/maps/tile_build/src/bin/tile_points.rs@@ -6,17 +6,24 @@ //!               [--minzoom N] [--maxzoom N] //! //! Input is one GeoJSON `Feature` per line with `Point` geometry, exactly what-//! `gtfs_ingest`'s `transit_stops` binary and `osm_ingest`'s `poi_extract` emit.-//! Only `Point` features are accepted; anything else is counted and skipped, since-//! this tool deliberately has no clipper.+//! `gtfs_ingest`'s `transit_stops` binary and `osm_ingest`'s `poi_extract` and+//! `osm_extract` emit. Only `Point` features are accepted; anything else is counted+//! and skipped.+//!+//! Unlike `tile_lines` and `tile_polygons` this has no per-tile byte budget: a+//! point layer's size is bounded by the number of pins the operator chose to bake,+//! and thinning it silently would change what the app can find rather than only how+//! it looks. It is also the path the published archives were built with, so it+//! stays as it is.  use std::process::ExitCode;-use tile_build::mvt::Value;+use tile_build::geojson;+use tile_build::geom::Geometry; use tile_build::tiling::{build_point_archive, Point};  fn main() -> ExitCode {     let args: Vec<String> = std::env::args().collect();-    let mut geojson = None;+    let mut geojson_path = None;     let mut out = None;     let mut layer = None;     let mut minzoom = 11u8;@@ -27,7 +34,7 @@ fn main() -> ExitCode {         let take = |i: usize| args.get(i + 1).cloned();         match args[i].as_str() {             "--geojson" => {-                geojson = take(i);+                geojson_path = take(i);                 i += 2;             }             "--out" => {@@ -58,7 +65,7 @@ fn main() -> ExitCode {         }     } -    let (Some(geojson), Some(out), Some(layer)) = (geojson, out, layer) else {+    let (Some(geojson_path), Some(out), Some(layer)) = (geojson_path, out, layer) else {         eprintln!("tile_points: --geojson, --out and --layer are all required");         usage();         return ExitCode::from(2);@@ -68,10 +75,10 @@ fn main() -> ExitCode {         return ExitCode::from(2);     } -    let text = match std::fs::read_to_string(&geojson) {+    let text = match std::fs::read_to_string(&geojson_path) {         Ok(t) => t,         Err(e) => {-            eprintln!("tile_points: cannot read {geojson}: {e}");+            eprintln!("tile_points: cannot read {geojson_path}: {e}");             return ExitCode::FAILURE;         }     };@@ -83,8 +90,8 @@ fn main() -> ExitCode {         if line.is_empty() {             continue;         }-        match parse_point_feature(line) {-            Some(p) => points.push(p),+        match parse_point(line) {+            Some(p) => points.extend(p),             None => {                 skipped += 1;                 if skipped <= 5 {@@ -97,7 +104,7 @@ fn main() -> ExitCode {         eprintln!("tile_points: ... and {} more skipped line(s)", skipped - 5);     }     if points.is_empty() {-        eprintln!("tile_points: no point features in {geojson}");+        eprintln!("tile_points: no point features in {geojson_path}");         return ExitCode::FAILURE;     } @@ -125,143 +132,39 @@ fn usage() {     eprintln!("                   [--minzoom N] [--maxzoom N]"); } -/// Minimal GeoJSON `Feature`/`Point` reader for the one-line-per-feature shape our-/// own emitters produce. Deliberately not a general GeoJSON parser: it needs no-/// serde dependency, which is what keeps this crate resolving offline.-fn parse_point_feature(line: &str) -> Option<Point> {-    let coords = extract_after(line, "\"coordinates\":[")?;-    let close = coords.find(']')?;-    let mut nums = coords[..close].split(',');-    let lon: f64 = nums.next()?.trim().parse().ok()?;-    let lat: f64 = nums.next()?.trim().parse().ok()?;-    if !line.contains("\"Point\"") {+/// One line's points, or `None` when the line is not point geometry.+///+/// A `MultiPoint` becomes several points sharing one property set, which is what+/// a point layer means by it.+fn parse_point(line: &str) -> Option<Vec<Point>> {+    let f = geojson::parse_feature(line)?;+    let Geometry::Points(coords) = f.geometry else {+        return None;+    };+    if coords.is_empty() {         return None;     }--    let mut props = Vec::new();-    if let Some(rest) = extract_after(line, "\"properties\":{") {-        let end = rest.rfind('}').unwrap_or(rest.len());-        props = parse_props(&rest[..end]);-    }-    Some(Point { lon, lat, props })-}--fn extract_after<'a>(hay: &'a str, needle: &str) -> Option<&'a str> {-    hay.find(needle).map(|i| &hay[i + needle.len()..])-}--/// Parse a flat JSON object body into properties. Strings and numbers only, which-/// is all our emitters write.-fn parse_props(body: &str) -> Vec<(String, Value)> {-    let mut out = Vec::new();-    let b = body.as_bytes();-    let mut i = 0usize;-    while i < b.len() {-        // Key.-        while i < b.len() && b[i] != b'"' {-            i += 1;-        }-        if i >= b.len() {-            break;-        }-        i += 1;-        let ks = i;-        while i < b.len() && b[i] != b'"' {-            if b[i] == b'\\' {-                i += 1;-            }-            i += 1;-        }-        if i >= b.len() {-            break;-        }-        let key = unescape(&body[ks..i]);-        i += 1;-        while i < b.len() && b[i] != b':' {-            i += 1;-        }-        i += 1;-        while i < b.len() && (b[i] as char).is_whitespace() {-            i += 1;-        }-        if i >= b.len() {-            break;-        }-        // Value: string or number.-        if b[i] == b'"' {-            i += 1;-            let vs = i;-            while i < b.len() && b[i] != b'"' {-                if b[i] == b'\\' {-                    i += 1;-                }-                i += 1;-            }-            if i > b.len() {-                break;-            }-            out.push((key, Value::String(unescape(&body[vs..i.min(body.len())]))));-            i += 1;-        } else {-            let vs = i;-            while i < b.len() && b[i] != b',' && b[i] != b'}' {-                i += 1;-            }-            let raw = body[vs..i].trim();-            if let Ok(u) = raw.parse::<u64>() {-                out.push((key, Value::Uint(u)));-            } else if let Ok(f) = raw.parse::<f64>() {-                out.push((key, Value::Double(f)));-            } else if raw == "true" || raw == "false" {-                out.push((key, Value::Bool(raw == "true")));-            }-        }-        while i < b.len() && b[i] != b',' {-            i += 1;-        }-        i += 1;-    }-    out-}--fn unescape(s: &str) -> String {-    if !s.contains('\\') {-        return s.to_string();-    }-    let mut out = String::with_capacity(s.len());-    let mut it = s.chars();-    while let Some(c) = it.next() {-        if c != '\\' {-            out.push(c);-            continue;-        }-        match it.next() {-            Some('n') => out.push('\n'),-            Some('r') => out.push('\r'),-            Some('t') => out.push('\t'),-            Some('u') => {-                let hex: String = it.by_ref().take(4).collect();-                if let Some(ch) =-                    u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32)-                {-                    out.push(ch);-                }-            }-            Some(other) => out.push(other),-            None => break,-        }-    }-    out+    Some(+        coords+            .into_iter()+            .map(|(lon, lat)| Point { lon, lat, props: f.props.clone() })+            .collect(),+    ) }  #[cfg(test)] mod tests {     use super::*;+    use tile_build::mvt::Value;++    fn one(line: &str) -> Option<Point> {+        parse_point(line).map(|mut v| v.remove(0))+    }      #[test]     fn parses_what_transit_stops_emits() {         let line = r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[-122.3968000,37.7929000]},"properties":{"name":"Embarcadero","motis_id":"us-ca-SF-bayarea_901201","route_type":1}}"#;-        let p = parse_point_feature(line).expect("a point feature");+        let p = one(line).expect("a point feature");         assert!((p.lon - -122.3968).abs() < 1e-9);         assert!((p.lat - 37.7929).abs() < 1e-9);         assert_eq!(@@ -277,7 +180,7 @@ mod tests {     #[test]     fn parses_a_feature_with_no_motis_id() {         let line = r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[-1.5,2.5]},"properties":{"name":"Ferry Building","route_type":0}}"#;-        let p = parse_point_feature(line).unwrap();+        let p = one(line).unwrap();         assert_eq!(p.props.len(), 2);         assert!(p.props.iter().all(|(k, _)| k != "motis_id"));     }@@ -285,20 +188,38 @@ mod tests {     #[test]     fn handles_escapes_in_names() {         let line = r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[0,0]},"properties":{"name":"A\"B\\C","route_type":3}}"#;-        let p = parse_point_feature(line).unwrap();+        let p = one(line).unwrap();         assert_eq!(p.props[0].1, Value::String("A\"B\\C".into()));     } +    #[test]+    fn parses_what_osm_extract_emits_for_the_safety_layer() {+        let line = r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[-122.4194000,37.7749000]},"properties":{"kind":"speed_camera","direction":"forward","osm_id":"node/1001"}}"#;+        let p = one(line).unwrap();+        assert_eq!(p.props[0].1, Value::String("speed_camera".into()));+        assert_eq!(p.props[2].1, Value::String("node/1001".into()));+    }++    #[test]+    fn a_multipoint_becomes_several_points_sharing_one_property_set() {+        let line = r#"{"type":"Feature","geometry":{"type":"MultiPoint","coordinates":[[0,0],[1,1]]},"properties":{"name":"Pair"}}"#;+        let pts = parse_point(line).unwrap();+        assert_eq!(pts.len(), 2);+        assert_eq!(pts[0].props, pts[1].props);+    }+     #[test]     fn rejects_non_point_geometry() {         let line = r#"{"type":"Feature","geometry":{"type":"LineString","coordinates":[[0,0],[1,1]]},"properties":{}}"#;-        assert!(parse_point_feature(line).is_none(), "no clipper, so lines are refused");+        assert!(one(line).is_none(), "a point layer takes points");+        let line = r#"{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[0,0],[1,0],[1,1],[0,0]]]},"properties":{}}"#;+        assert!(one(line).is_none());     }      #[test]     fn rejects_junk() {-        assert!(parse_point_feature("").is_none());-        assert!(parse_point_feature("not json").is_none());-        assert!(parse_point_feature(r#"{"type":"Feature"}"#).is_none());+        assert!(one("").is_none());+        assert!(one("not json").is_none());+        assert!(one(r#"{"type":"Feature"}"#).is_none());     } }
scripts/maps/tile_build/src/bin/tile_polygons.rs
diff --git a/scripts/maps/tile_build/src/bin/tile_polygons.rs b/scripts/maps/tile_build/src/bin/tile_polygons.rsnew file mode 100644index 0000000000..569af3adbe--- /dev/null+++ b/scripts/maps/tile_build/src/bin/tile_polygons.rs@@ -0,0 +1,25 @@+//! `tile_polygons` — tile a geojsonseq polygon file into a single-layer PMTiles+//! archive. The `tippecanoe` replacement for area layers (`admin_*`).+//!+//! Usage:+//!   tile_polygons --geojson IN.geojsonseq --out OUT.pmtiles --layer NAME+//!                 [--minzoom N] [--maxzoom N] [--simplification F]+//!                 [--max-tile-bytes N] [--extent N]+//!+//! Input is one GeoJSON `Feature` per line with `Polygon` or `MultiPolygon`+//! geometry; anything else is counted and skipped. Ring winding order is derived+//! from the signed area rather than trusted, so an input wound either way encodes+//! correctly.+//!+//! Two things tippecanoe does for admin layers that this does not:+//! `--detect-shared-borders` (so a shared border can show a hairline seam at low+//! zoom) and `--extend-zooms-if-still-dropping`. Both are documented in+//! `tile_build::pyramid`.++use std::process::ExitCode;+use tile_build::pyramid::{cli_main, Accept};++fn main() -> ExitCode {+    let argv: Vec<String> = std::env::args().skip(1).collect();+    cli_main("tile_polygons", Accept::Polygons, &argv)+}
scripts/maps/tile_build/src/geojson.rs
diff --git a/scripts/maps/tile_build/src/geojson.rs b/scripts/maps/tile_build/src/geojson.rsnew file mode 100644index 0000000000..be67aca27c--- /dev/null+++ b/scripts/maps/tile_build/src/geojson.rs@@ -0,0 +1,516 @@+//! Reading the GeoJSONSeq the extractors emit.+//!+//! One `Feature` per line, with any of the six geometry types. Deliberately **not**+//! a general GeoJSON parser and deliberately not serde: this crate's only+//! dependency is `miniz_oxide`, which is what lets it resolve and build offline,+//! and adding a JSON stack for a format we also write ourselves would throw that+//! away.+//!+//! What that costs, stated plainly: nested objects inside `properties` are+//! ignored, and so is any geometry the six types do not cover+//! (`GeometryCollection`). Both are things our own writers never produce, and both+//! are counted and reported rather than silently skipped.+//!+//! Key order is *not* assumed. The geometry object is located and its extent+//! found by brace counting, then `type` and `coordinates` are looked up inside it,+//! so `{"coordinates":...,"type":...}` reads the same as the other way round.++use crate::geom::{Geometry, Pt};+use crate::mvt::Value;++/// One parsed feature: geometry in lon/lat, plus its flat properties.+#[derive(Debug, Clone, PartialEq)]+pub struct Feature {+    pub geometry: Geometry,+    pub props: Vec<(String, Value)>,+}++/// Parse one line. `None` when the line is not a feature we can use -- malformed,+/// or a geometry type this reader does not cover.+pub fn parse_feature(line: &str) -> Option<Feature> {+    // Work on the object's body, so "top level" means depth 0 for both this call+    // and the ones on the nested objects below.+    let body = strip_outer_braces(line)?;+    let geometry = find_object(body, "\"geometry\"")?;+    let type_name = string_value(geometry, "\"type\"")?;+    let coords_at = find_key(geometry, "\"coordinates\"")?;+    let (coords, _) = parse_coords(&geometry[coords_at..])?;++    let geometry = match type_name.as_str() {+        "Point" => Geometry::Points(vec![coords.as_point()?]),+        "MultiPoint" => Geometry::Points(coords.as_line()?),+        "LineString" => Geometry::Lines(vec![coords.as_line()?]),+        "MultiLineString" => Geometry::Lines(coords.as_lines()?),+        "Polygon" => Geometry::Polygons(vec![coords.as_lines()?]),+        "MultiPolygon" => Geometry::Polygons(coords.as_polygons()?),+        _ => return None,+    };++    let props = match find_object(body, "\"properties\"") {+        Some(p) => parse_props(p),+        None => Vec::new(),+    };+    Some(Feature { geometry, props })+}++/// The contents of one enclosing `{...}`.+fn strip_outer_braces(s: &str) -> Option<&str> {+    let s = s.trim();+    s.strip_prefix('{')?.strip_suffix('}')+}++/// The body of the object at `key`, without its braces. `hay` is an object *body*,+/// so its own keys sit at depth 0.+///+/// Brace counting, ignoring braces inside strings, so a `properties` value that+/// happens to contain `{` in a name does not truncate the object.+fn find_object<'a>(hay: &'a str, key: &str) -> Option<&'a str> {+    let at = find_key(hay, key)?;+    let b = hay.as_bytes();+    let mut i = at;+    while i < b.len() && b[i] != b'{' {+        // A non-object value for this key: not something we can read.+        if b[i] == b'"' || b[i] == b'[' {+            return None;+        }+        i += 1;+    }+    if i >= b.len() {+        return None;+    }+    let start = i + 1;+    let mut depth = 0usize;+    let mut in_str = false;+    while i < b.len() {+        match b[i] {+            b'\\' if in_str => i += 1,+            b'"' => in_str = !in_str,+            b'{' if !in_str => depth += 1,+            b'}' if !in_str => {+                depth -= 1;+                if depth == 0 {+                    return Some(&hay[start..i]);+                }+            }+            _ => {}+        }+        i += 1;+    }+    None+}++/// Byte offset just past `key":` at the top nesting level of `hay`.+fn find_key(hay: &str, key: &str) -> Option<usize> {+    let b = hay.as_bytes();+    let k = key.as_bytes();+    let mut i = 0usize;+    let mut depth = 0i32;+    let mut in_str = false;+    while i < b.len() {+        match b[i] {+            b'\\' if in_str => {+                i += 2;+                continue;+            }+            b'"' if !in_str && depth == 0 && b[i..].starts_with(k) => {+                let mut j = i + k.len();+                while j < b.len() && (b[j] == b' ' || b[j] == b':') {+                    if b[j] == b':' {+                        return Some(j + 1);+                    }+                    j += 1;+                }+                i = j;+                continue;+            }+            b'"' => in_str = !in_str,+            b'{' | b'[' if !in_str => depth += 1,+            b'}' | b']' if !in_str => depth -= 1,+            _ => {}+        }+        i += 1;+    }+    None+}++fn string_value(hay: &str, key: &str) -> Option<String> {+    let at = find_key(hay, key)?;+    let rest = hay[at..].trim_start();+    let rest = rest.strip_prefix('"')?;+    let end = rest.find('"')?;+    Some(rest[..end].to_string())+}++/// A JSON value that is either a number or a list, which is all a `coordinates`+/// member can be at any depth.+#[derive(Debug, PartialEq)]+enum Coords {+    Num(f64),+    List(Vec<Coords>),+}++impl Coords {+    fn as_point(&self) -> Option<Pt> {+        match self {+            Coords::List(v) if v.len() >= 2 => match (&v[0], &v[1]) {+                // Extra ordinates (elevation, measure) are ignored, not rejected:+                // GeoJSON permits them and they carry nothing a tile can show.+                (Coords::Num(x), Coords::Num(y)) => Some((*x, *y)),+                _ => None,+            },+            _ => None,+        }+    }++    fn as_line(&self) -> Option<Vec<Pt>> {+        match self {+            Coords::List(v) => v.iter().map(Coords::as_point).collect(),+            _ => None,+        }+    }++    fn as_lines(&self) -> Option<Vec<Vec<Pt>>> {+        match self {+            Coords::List(v) => v.iter().map(Coords::as_line).collect(),+            _ => None,+        }+    }++    fn as_polygons(&self) -> Option<Vec<Vec<Vec<Pt>>>> {+        match self {+            Coords::List(v) => v.iter().map(Coords::as_lines).collect(),+            _ => None,+        }+    }+}++/// Parse a number-or-list value, returning it and the bytes consumed.+fn parse_coords(s: &str) -> Option<(Coords, usize)> {+    let b = s.as_bytes();+    let mut i = 0usize;+    while i < b.len() && b[i].is_ascii_whitespace() {+        i += 1;+    }+    if i >= b.len() {+        return None;+    }+    if b[i] == b'[' {+        i += 1;+        let mut items = Vec::new();+        loop {+            while i < b.len() && (b[i].is_ascii_whitespace() || b[i] == b',') {+                i += 1;+            }+            if i >= b.len() {+                return None;+            }+            if b[i] == b']' {+                return Some((Coords::List(items), i + 1));+            }+            let (v, used) = parse_coords(&s[i..])?;+            items.push(v);+            i += used;+        }+    }+    // A number: take the longest run of characters a JSON number can use.+    let start = i;+    while i < b.len() && matches!(b[i], b'0'..=b'9' | b'-' | b'+' | b'.' | b'e' | b'E') {+        i += 1;+    }+    if i == start {+        return None;+    }+    Some((Coords::Num(s[start..i].parse().ok()?), i))+}++/// Parse a flat JSON object body into properties. Strings and numbers only, which+/// is all our emitters write; a nested object or array value is skipped.+pub fn parse_props(body: &str) -> Vec<(String, Value)> {+    let mut out = Vec::new();+    let b = body.as_bytes();+    let mut i = 0usize;+    while i < b.len() {+        // Key.+        while i < b.len() && b[i] != b'"' {+            i += 1;+        }+        if i >= b.len() {+            break;+        }+        i += 1;+        let ks = i;+        while i < b.len() && b[i] != b'"' {+            if b[i] == b'\\' {+                i += 1;+            }+            i += 1;+        }+        if i >= b.len() {+            break;+        }+        let key = unescape(&body[ks..i]);+        i += 1;+        while i < b.len() && b[i] != b':' {+            i += 1;+        }+        i += 1;+        while i < b.len() && b[i].is_ascii_whitespace() {+            i += 1;+        }+        if i >= b.len() {+            break;+        }+        match b[i] {+            b'"' => {+                i += 1;+                let vs = i;+                while i < b.len() && b[i] != b'"' {+                    if b[i] == b'\\' {+                        i += 1;+                    }+                    i += 1;+                }+                out.push((key, Value::String(unescape(&body[vs..i.min(body.len())]))));+                i += 1;+            }+            open @ (b'{' | b'[') => {+                // Skip the whole nested value. Reporting it is the caller's job;+                // guessing a scalar for it would be worse than omitting it.+                let close = if open == b'{' { b'}' } else { b']' };+                let mut depth = 0usize;+                let mut in_str = false;+                while i < b.len() {+                    match b[i] {+                        b'\\' if in_str => i += 1,+                        b'"' => in_str = !in_str,+                        c if c == open && !in_str => depth += 1,+                        c if c == close && !in_str => {+                            depth -= 1;+                            if depth == 0 {+                                i += 1;+                                break;+                            }+                        }+                        _ => {}+                    }+                    i += 1;+                }+            }+            _ => {+                let vs = i;+                while i < b.len() && b[i] != b',' && b[i] != b'}' {+                    i += 1;+                }+                let raw = body[vs..i].trim();+                // u64 before f64 so an integer property stays an integer on the+                // wire, which is what tippecanoe emitted and what the styles read.+                if let Ok(u) = raw.parse::<u64>() {+                    out.push((key, Value::Uint(u)));+                } else if let Ok(f) = raw.parse::<f64>() {+                    out.push((key, Value::Double(f)));+                } else if raw == "true" || raw == "false" {+                    out.push((key, Value::Bool(raw == "true")));+                }+            }+        }+        while i < b.len() && b[i] != b',' {+            i += 1;+        }+        i += 1;+    }+    out+}++pub fn unescape(s: &str) -> String {+    if !s.contains('\\') {+        return s.to_string();+    }+    let mut out = String::with_capacity(s.len());+    let mut it = s.chars();+    while let Some(c) = it.next() {+        if c != '\\' {+            out.push(c);+            continue;+        }+        match it.next() {+            Some('n') => out.push('\n'),+            Some('r') => out.push('\r'),+            Some('t') => out.push('\t'),+            Some('u') => {+                let hex: String = it.by_ref().take(4).collect();+                if let Some(ch) = u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32) {+                    out.push(ch);+                }+            }+            Some(other) => out.push(other),+            None => break,+        }+    }+    out+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn reads_what_osm_extract_emits_for_a_point() {+        let line = r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[-122.4194000,37.7749000]},"properties":{"kind":"speed_camera","osm_id":"node/1001"}}"#;+        let f = parse_feature(line).unwrap();+        assert_eq!(f.geometry, Geometry::Points(vec![(-122.4194, 37.7749)]));+        assert_eq!(+            f.props,+            vec![+                ("kind".to_string(), Value::String("speed_camera".into())),+                ("osm_id".to_string(), Value::String("node/1001".into())),+            ]+        );+    }++    #[test]+    fn reads_a_linestring_and_a_multilinestring() {+        let line = r#"{"type":"Feature","geometry":{"type":"LineString","coordinates":[[-122.42,37.77],[-122.41,37.78]]},"properties":{"maxspeed":"25 mph"}}"#;+        let f = parse_feature(line).unwrap();+        assert_eq!(+            f.geometry,+            Geometry::Lines(vec![vec![(-122.42, 37.77), (-122.41, 37.78)]])+        );++        let line = r#"{"type":"Feature","geometry":{"type":"MultiLineString","coordinates":[[[0,0],[1,1]],[[2,2],[3,3]]]},"properties":{}}"#;+        let f = parse_feature(line).unwrap();+        assert_eq!(+            f.geometry,+            Geometry::Lines(vec![+                vec![(0.0, 0.0), (1.0, 1.0)],+                vec![(2.0, 2.0), (3.0, 3.0)]+            ])+        );+    }++    #[test]+    fn reads_a_polygon_with_a_hole_and_a_multipolygon() {+        let line = r#"{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[0,0],[4,0],[4,4],[0,4],[0,0]],[[1,1],[2,1],[2,2],[1,1]]]},"properties":{"name":"Oakland"}}"#;+        let f = parse_feature(line).unwrap();+        let Geometry::Polygons(polys) = f.geometry else { panic!() };+        assert_eq!(polys.len(), 1);+        assert_eq!(polys[0].len(), 2, "exterior plus its hole");+        assert_eq!(polys[0][0].len(), 5);++        let line = r#"{"type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[[[[0,0],[1,0],[1,1],[0,0]]],[[[5,5],[6,5],[6,6],[5,5]]]]},"properties":{}}"#;+        let Geometry::Polygons(polys) = parse_feature(line).unwrap().geometry else { panic!() };+        assert_eq!(polys.len(), 2);+        assert_eq!(polys[0][0].len(), 4);+    }++    #[test]+    fn reads_a_multipoint() {+        let line = r#"{"type":"Feature","geometry":{"type":"MultiPoint","coordinates":[[0,0],[1,1]]},"properties":{}}"#;+        assert_eq!(+            parse_feature(line).unwrap().geometry,+            Geometry::Points(vec![(0.0, 0.0), (1.0, 1.0)])+        );+    }++    #[test]+    fn key_order_inside_the_geometry_does_not_matter() {+        let a = r#"{"type":"Feature","geometry":{"type":"LineString","coordinates":[[0,0],[1,1]]},"properties":{}}"#;+        let b = r#"{"type":"Feature","geometry":{"coordinates":[[0,0],[1,1]],"type":"LineString"},"properties":{}}"#;+        assert_eq!(parse_feature(a), parse_feature(b));+    }++    #[test]+    fn properties_before_geometry_still_reads() {+        let line = r#"{"type":"Feature","properties":{"name":"X"},"geometry":{"type":"Point","coordinates":[1,2]}}"#;+        let f = parse_feature(line).unwrap();+        assert_eq!(f.geometry, Geometry::Points(vec![(1.0, 2.0)]));+        assert_eq!(f.props, vec![("name".to_string(), Value::String("X".into()))]);+    }++    #[test]+    fn numeric_and_boolean_properties_keep_their_types() {+        let line = r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[0,0]},"properties":{"type":12,"score":1.5,"neg":-3,"ok":true}}"#;+        let f = parse_feature(line).unwrap();+        assert_eq!(+            f.props,+            vec![+                ("type".to_string(), Value::Uint(12)),+                ("score".to_string(), Value::Double(1.5)),+                ("neg".to_string(), Value::Double(-3.0)),+                ("ok".to_string(), Value::Bool(true)),+            ]+        );+    }++    #[test]+    fn escapes_and_awkward_names_survive() {+        let line = r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[0,0]},"properties":{"name":"A\"B\\C","other":"{not an object}"}}"#;+        let f = parse_feature(line).unwrap();+        assert_eq!(f.props[0].1, Value::String("A\"B\\C".into()));+        // A brace inside a string must not truncate the properties object.+        assert_eq!(f.props[1].1, Value::String("{not an object}".into()));+    }++    #[test]+    fn a_nested_property_value_is_skipped_not_guessed_at() {+        let line = r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[0,0]},"properties":{"a":1,"nested":{"x":1},"b":2}}"#;+        let f = parse_feature(line).unwrap();+        let keys: Vec<&str> = f.props.iter().map(|(k, _)| k.as_str()).collect();+        assert_eq!(keys, vec!["a", "b"]);+    }++    #[test]+    fn extra_ordinates_are_ignored() {+        // GeoJSON allows a third (elevation) ordinate. A tile has nowhere to put it.+        let line = r#"{"type":"Feature","geometry":{"type":"LineString","coordinates":[[1,2,300],[3,4,500]]},"properties":{}}"#;+        assert_eq!(+            parse_feature(line).unwrap().geometry,+            Geometry::Lines(vec![vec![(1.0, 2.0), (3.0, 4.0)]])+        );+    }++    #[test]+    fn scientific_notation_and_signs_parse() {+        let line = r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[-1.22e2,+3.7e1]},"properties":{}}"#;+        assert_eq!(+            parse_feature(line).unwrap().geometry,+            Geometry::Points(vec![(-122.0, 37.0)])+        );+    }++    #[test]+    fn a_feature_with_no_properties_member_reads_as_empty() {+        let line = r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[0,0]}}"#;+        assert_eq!(parse_feature(line).unwrap().props, vec![]);+    }++    #[test]+    fn unusable_lines_are_rejected_rather_than_guessed_at() {+        for bad in [+            "",+            "not json",+            r#"{"type":"Feature"}"#,+            // No coordinates.+            r#"{"type":"Feature","geometry":{"type":"Point"}}"#,+            // A geometry type this reader does not cover.+            r#"{"type":"Feature","geometry":{"type":"GeometryCollection","coordinates":[]}}"#,+            // Point with one ordinate.+            r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[1]}}"#,+            // Wrong nesting for the declared type.+            r#"{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[0,0],[1,1]]}}"#,+            // Truncated array.+            r#"{"type":"Feature","geometry":{"type":"LineString","coordinates":[[0,0],[1,"#,+        ] {+            assert!(parse_feature(bad).is_none(), "{bad:?} should not parse");+        }+    }++    #[test]+    fn a_top_level_type_key_is_not_mistaken_for_the_geometrys() {+        // "type" appears at the top level too, and inside properties. Only the one+        // inside the geometry object may decide the geometry.+        let line = r#"{"type":"Feature","properties":{"type":99},"geometry":{"type":"LineString","coordinates":[[0,0],[1,1]]}}"#;+        let f = parse_feature(line).unwrap();+        assert!(matches!(f.geometry, Geometry::Lines(_)));+        assert_eq!(f.props, vec![("type".to_string(), Value::Uint(99))]);+    }+}
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 a07c9b390a..83b931ae4d 100644--- a/scripts/maps/tile_build/src/lib.rs+++ b/scripts/maps/tile_build/src/lib.rs@@ -16,19 +16,24 @@ //!     for both its directories and its tiles. //!   * [`pmtiles`] — the v3 container, read and write, including Hilbert tile ids //!     and the root/leaf directory split.+//!   * [`geojson`] — the GeoJSONSeq reader the tilers share. Hand-rolled, not+//!     serde: `miniz_oxide` being the only dependency is what lets this crate+//!     build offline. //!   * [`geom`] — projection, bounds, tile ranges and quantisation: lon/lat in, //!     integer tile coordinates out. //!   * [`clip`] — Liang-Barsky for lines, Sutherland-Hodgman for polygons, against //!     a tile's buffered rect. //!   * [`simplify`] — Douglas-Peucker in integer tile coordinates.+//!   * [`pyramid`] — the tile pyramid driver and the drop policy. //!   * [`tiling`] — bucket points into tiles, and merge tilesets. //! //! [`geom`], [`clip`] and [`simplify`] compose in one fixed order; [`geom`]'s module //! docs give the pipeline. //!-//! Three binaries sit on top: `tile_points` (the `tippecanoe` replacement for point-//! layers), `tile_join` (the `tile-join` replacement) and `pmtiles_dump` (a-//! canonical text dump, for the differential harness).+//! Five binaries sit on top: `tile_points`, `tile_lines` and `tile_polygons` (the+//! `tippecanoe` replacements, one per geometry kind), `tile_join` (the `tile-join`+//! replacement) and `pmtiles_dump` (a canonical text dump, for the differential+//! harness). //! //! Verified against the published `v5-ca.pmtiles` during development: its header, //! gzipped root directory and gzipped leaf directories all decode with byte-exact@@ -40,13 +45,16 @@ //! `--extend-zooms-if-still-dropping` can push an archive past its own maximum //! zoom; we implement a deterministic policy and a fixed max zoom instead. Tests //! assert our own invariants — ring closure, winding order, Douglas-Peucker-//! monotonicity, a PMTiles round trip — never equality with tippecanoe.+//! monotonicity, a PMTiles round trip — never equality with tippecanoe. See+//! [`pyramid`] for the policy and its consequences.  pub mod clip;+pub mod geojson; pub mod geom; pub mod gz; pub mod mvt; pub mod pmtiles; pub mod proto;+pub mod pyramid; pub mod simplify; pub mod tiling;
scripts/maps/tile_build/src/pyramid.rs
diff --git a/scripts/maps/tile_build/src/pyramid.rs b/scripts/maps/tile_build/src/pyramid.rsnew file mode 100644index 0000000000..1814b5f874--- /dev/null+++ b/scripts/maps/tile_build/src/pyramid.rs@@ -0,0 +1,847 @@+//! The tile pyramid driver, and the drop policy.+//!+//! Turns a list of lon/lat features into a PMTiles archive:+//!+//! ```text+//! per zoom, per feature: bounds -> tile range+//! per tile:              clip -> to_tile -> simplify -> encode -> drop policy+//!                        -> gzip -> pmtiles::Builder+//! ```+//!+//! # The drop policy+//!+//! tippecanoe keeps a tile under its size limit with `--drop-densest-as-needed`, a+//! heuristic that removes whichever features are locally densest and whose result+//! depends on the order it happened to visit them. We do not reproduce it. Instead:+//!+//! 1. Features in a tile are put in a **stable importance order**: largest bounding+//!    box first, ties broken by the feature's index in the input. Size is the best+//!    cheap proxy for "matters at this zoom" -- at z6 a state boundary should+//!    survive and a suburban street should not -- and the index makes it total, so+//!    two runs over the same input always drop the same features.+//! 2. The largest prefix of that order which fits the gzipped byte budget is kept,+//!    found by binary search. A prefix, so the kept set is always the top-k most+//!    important, never a scattered subset.+//! 3. If even one feature does not fit, that one feature is kept anyway and the+//!    tile is reported as over budget. An empty tile is a hole in the map; an+//!    oversized one is a slow tile.+//!+//! Consequences worth being explicit about:+//!+//! * **Per-tile feature counts will not match tippecanoe's.** That is the point of+//!   `test/diff_pmtiles.py --max-feature-delta`: the divergence is bounded and+//!   measured rather than unknown.+//! * **`--extend-zooms-if-still-dropping` is deliberately not reproduced.** It can+//!   push an archive past its own `--maximum-zoom`, so an archive's advertised zoom+//!   range stops being a fact about its contents. Here `--maxzoom` is exactly the+//!   deepest zoom present.+//! * **`--detect-shared-borders` is not implemented.** Adjacent admin polygons are+//!   simplified independently, so two countries sharing a border can end up with+//!   slightly different vertex sets along it. At low zoom that shows as a hairline+//!   gap or a hairline overlap. Reproducing it needs a shared topology pass across+//!   features, which is a project of its own.++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::pmtiles::{self, Builder};+use crate::proto::{err, Result};+use crate::simplify;++/// tippecanoe's default maximum gzipped tile size, and what the published+/// archives were built against.+pub const DEFAULT_MAX_TILE_BYTES: usize = 500_000;++/// One feature to tile: geometry in lon/lat, plus its properties.+#[derive(Debug, Clone)]+pub struct Feature {+    pub geometry: Geometry,+    pub props: Vec<(String, Value)>,+}++pub struct Options {+    pub layer: String,+    pub min_zoom: u8,+    pub max_zoom: u8,+    pub extent: u32,+    /// Simplification tolerance multiplier; 1.0 is the default policy.+    pub simplification: f64,+    pub max_tile_bytes: usize,+}++impl Options {+    pub fn new(layer: impl Into<String>, min_zoom: u8, max_zoom: u8) -> Options {+        Options {+            layer: layer.into(),+            min_zoom,+            max_zoom,+            extent: DEFAULT_EXTENT,+            simplification: 1.0,+            max_tile_bytes: DEFAULT_MAX_TILE_BYTES,+        }+    }+}++/// What one zoom cost, for the per-zoom report the drop policy owes the operator.+#[derive(Debug, Default, Clone, PartialEq)]+pub struct ZoomStats {+    pub zoom: u8,+    pub tiles: usize,+    /// Feature instances placed into tiles before the drop policy ran. A feature+    /// spanning four tiles counts four times, which is what the budget sees.+    pub placed: usize,+    pub kept: usize,+    pub dropped: usize,+    /// Tiles that could not be brought under budget even at one feature.+    pub over_budget: usize,+    pub largest_tile_bytes: usize,+}++/// Build the archive, and a per-zoom report.+pub fn build_archive(features: &[Feature], opts: &Options) -> Result<(Vec<u8>, Vec<ZoomStats>)> {+    if opts.min_zoom > opts.max_zoom {+        return err("minzoom is above maxzoom");+    }+    if opts.extent == 0 {+        return err("extent 0");+    }++    let geom_type = dominant_geom_type(features);+    let buffer = geom::buffer_for(opts.extent);+    let mut builder = Builder::new();+    builder.min_zoom = opts.min_zoom;+    builder.max_zoom = opts.max_zoom;+    builder.center_zoom = opts.min_zoom;+    builder.metadata = metadata(&opts.layer, opts.min_zoom, opts.max_zoom).into_bytes();+    if let Some(b) = lonlat_bounds(features) {+        builder.min_lon_e7 = e7(b.min_x);+        builder.min_lat_e7 = e7(b.min_y);+        builder.max_lon_e7 = e7(b.max_x);+        builder.max_lat_e7 = e7(b.max_y);+        builder.center_lon_e7 = e7((b.min_x + b.max_x) / 2.0);+        builder.center_lat_e7 = e7((b.min_y + b.max_y) / 2.0);+    }++    let mut report = Vec::new();+    for z in opts.min_zoom..=opts.max_zoom {+        let mut stats = ZoomStats { zoom: z, ..Default::default() };+        let tolerance = simplify::tolerance_for(z, opts.max_zoom, opts.simplification);++        // Project once per zoom, not once per tile: a coastline can cross thousands+        // of tiles and the projection is the expensive part.+        let projected: Vec<Option<Geometry>> = features+            .iter()+            .map(|f| Some(geom::project_geometry(&f.geometry, z, opts.extent)))+            .collect();++        // tile -> the features that reach it, in input order.+        let mut by_tile: std::collections::HashMap<(u64, u64), Vec<usize>> =+            std::collections::HashMap::new();+        for (i, p) in projected.iter().enumerate() {+            let Some(p) = p else { continue };+            let Some(b) = geom::bounds(p) else { continue };+            let Some(range) = geom::tile_range(&b, z, opts.extent, buffer) else {+                continue;+            };+            for (tx, ty) in range.iter() {+                by_tile.entry((tx, ty)).or_default().push(i);+            }+        }++        let mut tiles: Vec<(u64, u64)> = by_tile.keys().copied().collect();+        tiles.sort_unstable();+        for (tx, ty) in tiles {+            let indices = &by_tile[&(tx, ty)];+            let rect = geom::tile_rect(tx, ty, opts.extent, buffer);++            // Clip, move into the tile, simplify. Anything that vanishes here never+            // reached the tile in the first place, so it is not a "drop".+            let mut candidates: Vec<(usize, IntGeometry)> = Vec::with_capacity(indices.len());+            for &i in indices {+                let p = projected[i].as_ref().expect("filtered above");+                let clipped = clip_geometry(p, &rect);+                let local = geom::to_tile(&clipped, tx, ty, opts.extent);+                let simplified = simplify::simplify(&local, tolerance);+                if simplified.is_empty() {+                    continue;+                }+                candidates.push((i, simplified));+            }+            if candidates.is_empty() {+                continue;+            }+            stats.placed += candidates.len();++            // The stable importance order: largest first, index breaking ties.+            candidates.sort_by(|a, b| {+                extent_of(&b.1)+                    .cmp(&extent_of(&a.1))+                    .then_with(|| a.0.cmp(&b.0))+            });++            let (body, kept, over) = fit_tile(&candidates, features, &opts.layer, geom_type, opts)?;+            stats.kept += kept;+            stats.dropped += candidates.len() - kept;+            if over {+                stats.over_budget += 1;+            }+            stats.largest_tile_bytes = stats.largest_tile_bytes.max(body.len());+            stats.tiles += 1;+            builder.add_tile_raw(pmtiles::tile_id(z, tx, ty), body);+        }+        report.push(stats);+    }++    Ok((builder.build()?, report))+}++/// Encode the largest prefix of `candidates` that fits the byte budget.+///+/// Binary search on the prefix length: `O(log n)` gzip calls per tile rather than+/// one per dropped feature, and the answer does not depend on the search order.+/// Returns the gzipped body, how many features it holds, and whether it is still+/// over budget -- which happens when even a single feature does not fit, and is the+/// one case worth telling the operator about.+fn fit_tile(+    candidates: &[(usize, IntGeometry)],+    features: &[Feature],+    layer_name: &str,+    geom_type: GeomType,+    opts: &Options,+) -> Result<(Vec<u8>, usize, bool)> {+    let encode = |n: usize| -> Vec<u8> {+        let mut layer = Layer::new(layer_name);+        layer.extent = opts.extent;+        for (i, g) in &candidates[..n] {+            let geometry = match g {+                IntGeometry::Points(p) => mvt::encode_points(p),+                IntGeometry::Lines(l) => mvt::encode_lines(l),+                IntGeometry::Polygons(p) => mvt::encode_polygons(p),+            };+            if geometry.is_empty() {+                continue;+            }+            layer.features.push(MvtFeature {+                id: None,+                geom_type,+                geometry,+                props: features[*i].props.clone(),+            });+        }+        crate::gz::compress(&Tile { layers: vec![layer] }.encode())+    };++    let all = encode(candidates.len());+    if all.len() <= opts.max_tile_bytes {+        return Ok((all, candidates.len(), false));+    }++    // Largest n in 1..len with encode(n) within budget. `lo` is always known to+    // fit or to be the floor of 1; `hi` is known not to.+    let mut lo = 1usize;+    let mut hi = candidates.len();+    let mut best = encode(1);+    while lo < hi {+        let mid = lo + (hi - lo).div_ceil(2);+        let body = encode(mid);+        if body.len() <= opts.max_tile_bytes {+            best = body;+            lo = mid;+        } else {+            hi = mid - 1;+        }+    }+    // One feature that does not fit is kept anyway: an empty tile is a hole in the+    // map, an oversized one is merely slow.+    let over = best.len() > opts.max_tile_bytes;+    Ok((best, lo, over))+}++/// A cheap importance proxy: the geometry's span in tile units, as a single+/// number. Bigger means more of the tile is affected by keeping it.+fn extent_of(g: &IntGeometry) -> i64 {+    let mut min = (i32::MAX, i32::MAX);+    let mut max = (i32::MIN, i32::MIN);+    let mut seen = false;+    let mut add = |(x, y): (i32, i32)| {+        seen = true;+        min = (min.0.min(x), min.1.min(y));+        max = (max.0.max(x), max.1.max(y));+    };+    match g {+        IntGeometry::Points(p) => p.iter().for_each(|p| add(*p)),+        IntGeometry::Lines(l) => l.iter().flatten().for_each(|p| add(*p)),+        IntGeometry::Polygons(p) => p.iter().flatten().flatten().for_each(|p| add(*p)),+    }+    if !seen {+        return 0;+    }+    (max.0 as i64 - min.0 as i64) + (max.1 as i64 - min.1 as i64)+}++/// The MVT geometry type for the layer.+///+/// MVT tags each feature individually, but a layer is styled as one thing, so a+/// mixed layer is a mistake somewhere upstream. Taking the first feature's type+/// and applying it throughout makes that mistake visible as wrong rendering rather+/// than hiding it as a silently split layer.+fn dominant_geom_type(features: &[Feature]) -> GeomType {+    match features.first().map(|f| &f.geometry) {+        Some(Geometry::Points(_)) => GeomType::Point,+        Some(Geometry::Lines(_)) => GeomType::LineString,+        Some(Geometry::Polygons(_)) => GeomType::Polygon,+        None => GeomType::Unknown,+    }+}++fn lonlat_bounds(features: &[Feature]) -> Option<geom::Rect> {+    let mut acc: Option<geom::Rect> = None;+    for f in features {+        if let Some(b) = geom::bounds(&f.geometry) {+            acc = Some(match acc {+                None => b,+                Some(a) => geom::Rect {+                    min_x: a.min_x.min(b.min_x),+                    min_y: a.min_y.min(b.min_y),+                    max_x: a.max_x.max(b.max_x),+                    max_y: a.max_y.max(b.max_y),+                },+            });+        }+    }+    acc+}++fn e7(deg: f64) -> i32 {+    (deg * 1e7).round().clamp(i32::MIN as f64, i32::MAX as f64) as i32+}++/// The `json` metadata blob a PMTiles archive carries. MapLibre does not need it to+/// render a styled layer, but `pmtiles show` and friends read it, so emitting a+/// truthful `vector_layers` list keeps the archive introspectable.+fn metadata(layer_name: &str, min_zoom: u8, max_zoom: u8) -> String {+    format!(+        "{{\"vector_layers\":[{{\"id\":\"{layer_name}\",\"minzoom\":{min_zoom},\+         \"maxzoom\":{max_zoom}}}]}}"+    )+}++/// Print the per-zoom report the drop policy owes the operator.+pub fn print_report(report: &[ZoomStats], out: &mut impl std::io::Write) -> std::io::Result<()> {+    writeln!(out, "  zoom  tiles   placed     kept  dropped  largest")?;+    for s in report {+        writeln!(+            out,+            "  z{:<4} {:>6} {:>8} {:>8} {:>8} {:>8}{}",+            s.zoom,+            s.tiles,+            s.placed,+            s.kept,+            s.dropped,+            s.largest_tile_bytes,+            if s.over_budget > 0 {+                format!("  ({} tile(s) over budget)", s.over_budget)+            } else {+                String::new()+            }+        )?;+    }+    Ok(())+}++// --- the shared CLI -------------------------------------------------------++/// Which geometry a binary will tile. A layer is styled as one thing, so mixing+/// kinds in one archive is a mistake upstream; each binary accepts exactly one and+/// counts what it turns away.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Accept {+    Lines,+    Polygons,+}++impl Accept {+    fn matches(self, g: &Geometry) -> bool {+        matches!(+            (self, g),+            (Accept::Lines, Geometry::Lines(_)) | (Accept::Polygons, Geometry::Polygons(_))+        )+    }++    fn describe(self) -> &'static str {+        match self {+            Accept::Lines => "LineString or MultiLineString",+            Accept::Polygons => "Polygon or MultiPolygon",+        }+    }+}++/// `tile_lines` and `tile_polygons` are the same program with a different+/// [`Accept`], so they share one implementation and differ only in the name they+/// print.+pub fn cli_main(name: &str, accept: Accept, argv: &[String]) -> std::process::ExitCode {+    use std::process::ExitCode;++    let usage = || {+        eprintln!("usage: {name} --geojson IN.geojsonseq --out OUT.pmtiles --layer NAME");+        eprintln!("                  [--minzoom N] [--maxzoom N] [--simplification F]");+        eprintln!("                  [--max-tile-bytes N] [--extent N]");+    };++    let mut geojson = None;+    let mut out = None;+    let mut layer = None;+    let mut min_zoom = 11u8;+    let mut max_zoom = 14u8;+    let mut simplification = 1.0f64;+    let mut max_tile_bytes = DEFAULT_MAX_TILE_BYTES;+    let mut extent = DEFAULT_EXTENT;++    let mut i = 0;+    while i < argv.len() {+        let value = || argv.get(i + 1).cloned();+        match argv[i].as_str() {+            "--geojson" => {+                geojson = value();+                i += 2;+            }+            "--out" => {+                out = value();+                i += 2;+            }+            "--layer" => {+                layer = value();+                i += 2;+            }+            // A bad numeric value is fatal rather than falling back to the default:+            // silently tiling z11-14 when the caller asked for z0-8 produces an+            // archive that looks fine and is wrong.+            flag @ ("--minzoom" | "--maxzoom" | "--simplification" | "--max-tile-bytes"+            | "--extent") => {+                let Some(raw) = value() else {+                    eprintln!("{name}: {flag} needs a value");+                    return ExitCode::from(2);+                };+                let ok = match flag {+                    "--minzoom" => raw.parse().map(|v| min_zoom = v).is_ok(),+                    "--maxzoom" => raw.parse().map(|v| max_zoom = v).is_ok(),+                    "--simplification" => raw.parse().map(|v| simplification = v).is_ok(),+                    "--max-tile-bytes" => raw.parse().map(|v| max_tile_bytes = v).is_ok(),+                    _ => raw.parse().map(|v| extent = v).is_ok(),+                };+                if !ok {+                    eprintln!("{name}: {flag} wants a number, got '{raw}'");+                    return ExitCode::from(2);+                }+                i += 2;+            }+            "-h" | "--help" => {+                usage();+                return ExitCode::SUCCESS;+            }+            other => {+                eprintln!("{name}: unexpected argument '{other}'");+                usage();+                return ExitCode::from(2);+            }+        }+    }++    let (Some(geojson), Some(out), Some(layer)) = (geojson, out, layer) else {+        eprintln!("{name}: --geojson, --out and --layer are all required");+        usage();+        return ExitCode::from(2);+    };+    if min_zoom > max_zoom {+        eprintln!("{name}: --minzoom {min_zoom} is above --maxzoom {max_zoom}");+        return ExitCode::from(2);+    }++    let text = match std::fs::read_to_string(&geojson) {+        Ok(t) => t,+        Err(e) => {+            eprintln!("{name}: cannot read {geojson}: {e}");+            return ExitCode::FAILURE;+        }+    };++    let mut features = Vec::new();+    let mut skipped = 0usize;+    for (n, line) in text.lines().enumerate() {+        let line = line.trim();+        if line.is_empty() {+            continue;+        }+        match crate::geojson::parse_feature(line) {+            Some(f) if accept.matches(&f.geometry) => features.push(Feature {+                geometry: f.geometry,+                props: f.props,+            }),+            _ => {+                skipped += 1;+                if skipped <= 5 {+                    eprintln!(+                        "{name}: skipping line {} (not a {})",+                        n + 1,+                        accept.describe()+                    );+                }+            }+        }+    }+    if skipped > 5 {+        eprintln!("{name}: ... and {} more skipped line(s)", skipped - 5);+    }+    if features.is_empty() {+        eprintln!("{name}: no {} features in {geojson}", accept.describe());+        return ExitCode::FAILURE;+    }++    let opts = Options {+        layer: layer.clone(),+        min_zoom,+        max_zoom,+        extent,+        simplification,+        max_tile_bytes,+    };+    let (bytes, report) = match build_archive(&features, &opts) {+        Ok(v) => v,+        Err(e) => {+            eprintln!("{name}: {e}");+            return ExitCode::FAILURE;+        }+    };+    if let Err(e) = std::fs::write(&out, &bytes) {+        eprintln!("{name}: cannot write {out}: {e}");+        return ExitCode::FAILURE;+    }++    eprintln!(+        "{name}: wrote {out} ({:.1} MiB): {} feature(s), layer '{layer}', z{min_zoom}-{max_zoom}",+        bytes.len() as f64 / (1024.0 * 1024.0),+        features.len(),+    );+    let _ = print_report(&report, &mut std::io::stderr());+    let dropped: usize = report.iter().map(|s| s.dropped).sum();+    if dropped > 0 {+        eprintln!(+            "{name}: {dropped} feature placement(s) dropped by the {max_tile_bytes}-byte \+             per-tile budget"+        );+    }+    ExitCode::SUCCESS+}++#[cfg(test)]+mod tests {+    use super::*;+    use crate::pmtiles::Archive;++    fn line(coords: &[(f64, f64)], props: Vec<(&str, Value)>) -> Feature {+        Feature {+            geometry: Geometry::Lines(vec![coords.to_vec()]),+            props: props.into_iter().map(|(k, v)| (k.to_string(), v)).collect(),+        }+    }++    fn square(min_lon: f64, min_lat: f64, size: f64, name: &str) -> Feature {+        Feature {+            geometry: Geometry::Polygons(vec![vec![vec![+                (min_lon, min_lat),+                (min_lon + size, min_lat),+                (min_lon + size, min_lat + size),+                (min_lon, min_lat + size),+                (min_lon, min_lat),+            ]]]),+            props: vec![("name".to_string(), Value::String(name.into()))],+        }+    }++    fn tile_at(archive: &Archive, z: u8, lon: f64, lat: f64) -> Option<Tile> {+        let (fx, fy) = geom::project(lon, lat, z);+        archive+            .tile(z, fx.floor() as u64, fy.floor() as u64)+            .unwrap()+            .map(|b| Tile::decode(&b).unwrap())+    }++    #[test]+    fn a_line_archive_round_trips_through_the_reader() {+        let features = vec![line(+            &[(-122.42, 37.77), (-122.40, 37.79), (-122.38, 37.78)],+            vec![("maxspeed", Value::String("25 mph".into()))],+        )];+        let (bytes, report) = build_archive(&features, &Options::new("maxspeed", 10, 12)).unwrap();+        let a = Archive::parse(&bytes).unwrap();+        assert_eq!((a.header.min_zoom, a.header.max_zoom), (10, 12));+        assert!(String::from_utf8_lossy(&a.metadata).contains("maxspeed"));+        assert_eq!(report.len(), 3);++        for z in 10..=12u8 {+            let tile = tile_at(&a, z, -122.42, 37.77).unwrap_or_else(|| panic!("a tile at z{z}"));+            let l = tile.layer("maxspeed").unwrap();+            assert_eq!(l.features.len(), 1, "z{z}");+            assert_eq!(l.features[0].geom_type, GeomType::LineString);+            assert_eq!(+                l.features[0].get("maxspeed"),+                Some(&Value::String("25 mph".into()))+            );+            // And the geometry decodes as a line.+            assert!(mvt::decode_lines(&l.features[0].geometry).is_some());+        }+    }++    #[test]+    fn a_polygon_archive_keeps_its_winding_and_its_hole() {+        let with_hole = Feature {+            geometry: Geometry::Polygons(vec![vec![+                vec![(-122.5, 37.7), (-122.3, 37.7), (-122.3, 37.9), (-122.5, 37.9), (-122.5, 37.7)],+                vec![(-122.45, 37.75), (-122.35, 37.75), (-122.35, 37.85), (-122.45, 37.85), (-122.45, 37.75)],+            ]]),+            props: vec![("name".to_string(), Value::String("Oakland".into()))],+        };+        let (bytes, _) = build_archive(&[with_hole], &Options::new("admin_city", 9, 10)).unwrap();+        let a = Archive::parse(&bytes).unwrap();+        let tile = tile_at(&a, 10, -122.4, 37.8).expect("a tile");+        let f = &tile.layer("admin_city").unwrap().features[0];+        assert_eq!(f.geom_type, GeomType::Polygon);+        let rings = mvt::decode_polygons(&f.geometry).expect("polygon geometry");+        assert_eq!(rings.len(), 1);+        assert_eq!(rings[0].len(), 2, "exterior plus its hole: {rings:?}");+        assert!(mvt::signed_area(&rings[0][0]) > 0, "exterior positive");+        assert!(mvt::signed_area(&rings[0][1]) < 0, "interior negative");+    }++    #[test]+    fn a_feature_spanning_several_tiles_appears_in_each_of_them() {+        // A line across most of California at z6 lands in more than one tile.+        let features = vec![line(&[(-124.0, 40.0), (-116.0, 33.0)], vec![])];+        let (bytes, report) = build_archive(&features, &Options::new("l", 6, 6)).unwrap();+        let a = Archive::parse(&bytes).unwrap();+        assert!(report[0].tiles > 1, "{:?}", report[0]);+        assert!(a.header.addressed_tiles > 1);+        // Every tile it reaches actually carries geometry.+        for (_, raw) in a.iter_tiles().unwrap() {+            let tile = Tile::decode(&crate::gz::decompress(raw).unwrap()).unwrap();+            let l = tile.layer("l").unwrap();+            assert_eq!(l.features.len(), 1);+            assert!(!l.features[0].geometry.is_empty());+        }+    }++    #[test]+    fn tiles_a_feature_does_not_reach_are_not_created() {+        let features = vec![line(&[(-122.42, 37.77), (-122.41, 37.78)], vec![])];+        let (bytes, _) = build_archive(&features, &Options::new("l", 12, 12)).unwrap();+        let a = Archive::parse(&bytes).unwrap();+        // A small line at z12 covers a handful of tiles, not the whole grid.+        assert!(a.header.addressed_tiles < 10, "{}", a.header.addressed_tiles);+        assert!(tile_at(&a, 12, -74.0, 40.7).is_none(), "nothing in New York");+    }++    #[test]+    fn two_runs_are_byte_identical() {+        let features = vec![+            line(&[(-122.42, 37.77), (-122.40, 37.79)], vec![("a", Value::Uint(1))]),+            square(-122.5, 37.7, 0.1, "A"),+        ];+        let opts = Options::new("l", 10, 12);+        let (a, ra) = build_archive(&features, &opts).unwrap();+        let (b, rb) = build_archive(&features, &opts).unwrap();+        assert_eq!(a, b, "determinism is a regression surface here");+        assert_eq!(ra, rb);+    }++    // --- the drop policy ---------------------------------------------------++    #[test]+    fn nothing_is_dropped_when_the_tile_fits() {+        let features: Vec<Feature> = (0..50)+            .map(|i| {+                let d = i as f64 * 0.0001;+                line(&[(-122.42 + d, 37.77), (-122.41 + d, 37.78)], vec![])+            })+            .collect();+        let (_, report) = build_archive(&features, &Options::new("l", 12, 12)).unwrap();+        assert_eq!(report[0].dropped, 0, "{:?}", report[0]);+        assert_eq!(report[0].over_budget, 0);+        assert!(report[0].kept >= 50);+    }++    #[test]+    fn a_tight_budget_drops_the_least_important_features_first() {+        // One long line and many short ones in the same tile, with a budget only a+        // few features wide. Importance is bbox span, so the long one must survive.+        let mut features = vec![line(+            &[(-122.45, 37.75), (-122.35, 37.85)],+            vec![("id", Value::String("long".into()))],+        )];+        for i in 0..200 {+            let d = i as f64 * 0.00005;+            features.push(line(+                &[(-122.40 + d, 37.80), (-122.3999 + d, 37.8001)],+                vec![("id", Value::String(format!("short{i}")))],+            ));+        }+        let mut opts = Options::new("l", 11, 11);+        opts.max_tile_bytes = 400;+        let (bytes, report) = build_archive(&features, &opts).unwrap();+        assert!(report[0].dropped > 0, "the budget must have bitten: {:?}", report[0]);++        let a = Archive::parse(&bytes).unwrap();+        let tile = tile_at(&a, 11, -122.40, 37.80).expect("a tile");+        let ids: Vec<String> = tile+            .layer("l")+            .unwrap()+            .features+            .iter()+            .filter_map(|f| match f.get("id") {+                Some(Value::String(s)) => Some(s.clone()),+                _ => None,+            })+            .collect();+        assert!(ids.contains(&"long".to_string()), "the long line survives: {ids:?}");+    }++    #[test]+    fn a_dropping_tile_stays_within_its_budget() {+        let features: Vec<Feature> = (0..400)+            .map(|i| {+                let d = i as f64 * 0.00002;+                line(+                    &[(-122.40 + d, 37.80), (-122.399 + d, 37.801)],+                    vec![("name", Value::String(format!("street number {i}")))],+                )+            })+            .collect();+        let mut opts = Options::new("l", 11, 11);+        opts.max_tile_bytes = 600;+        let (bytes, report) = build_archive(&features, &opts).unwrap();+        assert!(report[0].dropped > 0);+        assert!(+            report[0].largest_tile_bytes <= 600,+            "largest tile {} exceeds the 600-byte budget",+            report[0].largest_tile_bytes+        );+        // The archive still reads, which is the thing a bad drop breaks.+        let a = Archive::parse(&bytes).unwrap();+        for (_, raw) in a.iter_tiles().unwrap() {+            assert!(Tile::decode(&crate::gz::decompress(raw).unwrap()).is_ok());+        }+    }++    #[test]+    fn one_feature_too_big_for_the_budget_is_kept_and_reported() {+        // An empty tile is a hole in the map; an oversized one is merely slow.+        let long: Vec<(f64, f64)> = (0..4000)+            .map(|i| (-122.42 + (i % 97) as f64 * 0.0001, 37.77 + (i % 89) as f64 * 0.0001))+            .collect();+        let features = vec![line(&long, vec![("name", Value::String("wiggly".into()))])];+        let mut opts = Options::new("l", 14, 14);+        opts.max_tile_bytes = 50;+        let (bytes, report) = build_archive(&features, &opts).unwrap();+        assert!(report[0].over_budget > 0, "{:?}", report[0]);+        assert!(report[0].kept > 0, "the tile must not be empty");+        let a = Archive::parse(&bytes).unwrap();+        assert!(a.header.addressed_tiles > 0);+    }++    #[test]+    fn the_drop_policy_is_deterministic_under_a_tight_budget() {+        let features: Vec<Feature> = (0..300)+            .map(|i| {+                let d = i as f64 * 0.00003;+                line(+                    &[(-122.40 + d, 37.80), (-122.3995 + d, 37.8005)],+                    vec![("name", Value::String(format!("f{i}")))],+                )+            })+            .collect();+        let mut opts = Options::new("l", 11, 11);+        opts.max_tile_bytes = 700;+        let (a, ra) = build_archive(&features, &opts).unwrap();+        let (b, rb) = build_archive(&features, &opts).unwrap();+        assert_eq!(a, b);+        assert_eq!(ra, rb);+        assert!(ra[0].dropped > 0, "the test is only meaningful if it dropped");+    }++    #[test]+    fn simplification_thins_the_shallow_zooms_and_spares_the_deepest() {+        // A wiggly line: at maxzoom the tolerance is zero, so every vertex the clip+        // left must still be there; below it, fewer.+        let coords: Vec<(f64, f64)> = (0..300)+            .map(|i| (-122.45 + i as f64 * 0.0002, 37.80 + (i % 2) as f64 * 0.00005))+            .collect();+        let (bytes, _) = build_archive(&[line(&coords, vec![])], &Options::new("l", 8, 12)).unwrap();+        let a = Archive::parse(&bytes).unwrap();+        let vertices_at = |z: u8| -> usize {+            let mut n = 0;+            for (id, raw) in a.iter_tiles().unwrap() {+                if pmtiles::tile_zxy(id).0 != z {+                    continue;+                }+                let tile = Tile::decode(&crate::gz::decompress(raw).unwrap()).unwrap();+                for f in &tile.layer("l").unwrap().features {+                    n += mvt::decode_lines(&f.geometry)+                        .map(|ls| ls.iter().map(|l| l.len()).sum::<usize>())+                        .unwrap_or(0);+                }+            }+            n+        };+        let deep = vertices_at(12);+        let shallow = vertices_at(8);+        assert!(deep > 0 && shallow > 0);+        assert!(+            shallow < deep,+            "z8 kept {shallow} vertices and z12 kept {deep}; simplification did nothing"+        );+    }++    #[test]+    fn features_that_clip_away_entirely_are_not_counted_as_drops() {+        // Two features far apart: each tile sees one of them, and the other's+        // absence is a clip, not a budget decision.+        let features = vec![+            line(&[(-122.42, 37.77), (-122.41, 37.78)], vec![]),+            line(&[(-74.01, 40.71), (-74.00, 40.72)], vec![]),+        ];+        let (_, report) = build_archive(&features, &Options::new("l", 12, 12)).unwrap();+        assert_eq!(report[0].dropped, 0, "{:?}", report[0]);+        assert_eq!(report[0].kept, report[0].placed);+    }++    #[test]+    fn an_empty_input_produces_an_empty_but_valid_archive() {+        let (bytes, report) = build_archive(&[], &Options::new("l", 10, 12)).unwrap();+        let a = Archive::parse(&bytes).unwrap();+        assert_eq!(a.header.addressed_tiles, 0);+        assert!(report.iter().all(|s| s.tiles == 0));+    }++    #[test]+    fn bad_options_are_refused() {+        let features = vec![line(&[(0.0, 0.0), (1.0, 1.0)], vec![])];+        let mut opts = Options::new("l", 12, 10);+        assert!(build_archive(&features, &opts).is_err(), "minzoom above maxzoom");+        opts = Options::new("l", 10, 12);+        opts.extent = 0;+        assert!(build_archive(&features, &opts).is_err(), "extent 0");+    }++    #[test]+    fn the_report_prints_one_row_per_zoom() {+        let (_, report) = build_archive(+            &[line(&[(-122.42, 37.77), (-122.41, 37.78)], vec![])],+            &Options::new("l", 10, 11),+        )+        .unwrap();+        let mut out = Vec::new();+        print_report(&report, &mut out).unwrap();+        let text = String::from_utf8(out).unwrap();+        assert!(text.contains("z10"), "{text}");+        assert!(text.contains("z11"), "{text}");+    }+}