Skip to main content

geolith_tiles_builder/layers/
boundaries.rs

1//! Boundaries layer — country and administrative boundaries.
2//!
3//! Processes features from multiple data sources:
4//! - **`NaturalEarth`** (z0-5): Admin boundary lines from `ne_10m_admin_*`
5//! - **OSM** (z6+): Admin boundaries from relations with India bbox fix
6//! - **`IndiaBoundary`**: Official Survey of India `GeoJSON` boundaries
7//! - **Overture**: `divisions/division_boundary` features
8
9use std::sync::Arc;
10
11use geo::{BooleanOps, BoundingRect, Buffer, Intersects};
12
13use crate::layers::{Layer, mark_foreign, take_owner};
14use crate::source::input::{DataSource, InputFeature};
15use crate::tile::feature::PropValue;
16
17use super::buildings::ProcessedFeature;
18
19/// How far the mask reaches past the Survey of India line, in degrees
20/// (about 550 m at the equator), so a source's own copy of the same border
21/// goes too and only the Survey of India line is drawn there.
22const MASK_MARGIN_DEG: f64 = 0.005;
23
24/// How far inside the Survey of India line a region or county line must
25/// lie to count as inside India, in degrees (about 2 km): a line along the
26/// border itself is a neighbour's own border and stays.
27const INNER_MARGIN_DEG: f64 = 0.02;
28
29/// How far a claim-marked line is kept away from India, in degrees: nothing of
30/// it is drawn inside the land, and nothing within this distance outside the
31/// edge, so a claim line that weaves along the border leaves no dashes
32/// hugging it.
33const CLAIM_MARGIN_DEG: f64 = 0.02;
34
35/// The land inside the Survey of India outline (`--india-boundary`).
36///
37/// India is always the Survey of India map. Overture and Natural Earth draw
38/// the Line of Control, and the lines around Aksai Chin, as country lines
39/// (often without `is_disputed`), and OSM tags them `boundary=disputed`.
40/// [`IndiaMask::clip`] removes every country line inside this land, so only
41/// the Survey of India line marks India's border.
42#[derive(Debug)]
43pub struct IndiaMask {
44    land: geo::MultiPolygon<f64>,
45    /// The land shrunk by [`INNER_MARGIN_DEG`].
46    inner: geo::MultiPolygon<f64>,
47    /// The land grown by [`CLAIM_MARGIN_DEG`]: where no claim-marked line is
48    /// drawn.
49    claim_land: geo::MultiPolygon<f64>,
50    bounds: geo::Rect<f64>,
51    claim_bounds: geo::Rect<f64>,
52}
53
54impl IndiaMask {
55    /// Build the mask from the `--india-boundary` features: every closed ring
56    /// (or polygon exterior) is one piece of land. `None` when there is no
57    /// closed ring.
58    pub fn from_features(features: &[InputFeature]) -> Option<Self> {
59        let pieces: Vec<geo::Polygon<f64>> = features
60            .iter()
61            .flat_map(|f| closed_rings(&f.geometry))
62            .map(|ring| geo::Polygon::new(ring, vec![]))
63            .collect();
64        if pieces.is_empty() {
65            return None;
66        }
67        let pieces = geo::MultiPolygon::new(pieces);
68        let land = pieces.buffer(MASK_MARGIN_DEG);
69        let inner = pieces.buffer(-INNER_MARGIN_DEG);
70        let claim_land = pieces.buffer(CLAIM_MARGIN_DEG);
71        let bounds = land.bounding_rect()?;
72        let claim_bounds = claim_land.bounding_rect()?;
73        Some(Self {
74            land,
75            inner,
76            claim_land,
77            bounds,
78            claim_bounds,
79        })
80    }
81
82    /// The Survey of India map inside India's land, in five rules.
83    /// A boundary line of any kind carrying a claim (`disputed`,
84    /// `disputed_by`, `claimed_by`) keeps only its part outside the land grown
85    /// by [`CLAIM_MARGIN_DEG`]: no claim line is drawn inside India or hugging
86    /// its edge from outside. Other `kind=country` lines keep only their part
87    /// outside the mask. A region, county or locality line marked foreign by
88    /// its source keeps only its part outside the land shrunk by
89    /// [`INNER_MARGIN_DEG`]: inside India only the lines between Indian
90    /// divisions are drawn, and they carry no claim. A places label marked
91    /// foreign (a division of another country, or a claim name) inside the
92    /// land is dropped. Every other feature passes unchanged. The private
93    /// owner mark is removed from all.
94    pub fn clip(&self, feature: ProcessedFeature) -> Option<ProcessedFeature> {
95        let (feature, foreign) = take_owner(feature);
96        match feature.layer {
97            Layer::Places => self.clip_label(feature, foreign),
98            Layer::Boundaries if carries_claim(&feature) => self.clip_claim_line(feature),
99            Layer::Boundaries if is_country(&feature) => self.clip_country_line(feature),
100            Layer::Boundaries => self.clip_admin_line(feature, foreign),
101            _ => Some(feature),
102        }
103    }
104
105    /// A foreign admin label whose point is on the land is dropped.
106    fn clip_label(&self, feature: ProcessedFeature, foreign: bool) -> Option<ProcessedFeature> {
107        use geo::Contains;
108        if !foreign {
109            return Some(feature);
110        }
111        match feature.geometry.as_ref() {
112            geo::Geometry::Point(point)
113                if self.bounds.contains(point) && self.land.contains(point) =>
114            {
115                None
116            }
117            _ => Some(feature),
118        }
119    }
120
121    /// The part of a `kind=country` line outside the mask.
122    fn clip_country_line(&self, feature: ProcessedFeature) -> Option<ProcessedFeature> {
123        let lines = match feature.geometry.as_ref() {
124            geo::Geometry::LineString(line) => geo::MultiLineString::new(vec![line.clone()]),
125            geo::Geometry::MultiLineString(lines) => lines.clone(),
126            _ => return Some(feature),
127        };
128        match lines.bounding_rect() {
129            Some(rect) if rect.intersects(&self.bounds) => {}
130            _ => return Some(feature),
131        }
132        let outside = self.land.clip(&lines, true);
133        if outside.0.is_empty() {
134            return None;
135        }
136        Some(ProcessedFeature {
137            geometry: Arc::new(geo::Geometry::MultiLineString(outside)),
138            ..feature
139        })
140    }
141
142    /// The part of a claim-carrying line (any kind) outside the land grown by
143    /// [`CLAIM_MARGIN_DEG`].
144    fn clip_claim_line(&self, feature: ProcessedFeature) -> Option<ProcessedFeature> {
145        let lines = match feature.geometry.as_ref() {
146            geo::Geometry::LineString(line) => geo::MultiLineString::new(vec![line.clone()]),
147            geo::Geometry::MultiLineString(lines) => lines.clone(),
148            _ => return Some(feature),
149        };
150        match lines.bounding_rect() {
151            Some(rect) if rect.intersects(&self.claim_bounds) => {}
152            _ => return Some(feature),
153        }
154        let outside = self.claim_land.clip(&lines, true);
155        if outside.0.is_empty() {
156            return None;
157        }
158        Some(ProcessedFeature {
159            geometry: Arc::new(geo::Geometry::MultiLineString(outside)),
160            ..feature
161        })
162    }
163
164    /// The part of a foreign region, county or locality line outside the
165    /// shrunk land.
166    fn clip_admin_line(
167        &self,
168        feature: ProcessedFeature,
169        foreign: bool,
170    ) -> Option<ProcessedFeature> {
171        if !foreign {
172            return Some(feature);
173        }
174        let lines = match feature.geometry.as_ref() {
175            geo::Geometry::LineString(line) => geo::MultiLineString::new(vec![line.clone()]),
176            geo::Geometry::MultiLineString(lines) => lines.clone(),
177            _ => return Some(feature),
178        };
179        match lines.bounding_rect() {
180            Some(rect) if rect.intersects(&self.bounds) => {}
181            _ => return Some(feature),
182        }
183        let outside = self.inner.clip(&lines, true);
184        if outside.0.is_empty() {
185            return None;
186        }
187        Some(ProcessedFeature {
188            geometry: Arc::new(geo::Geometry::MultiLineString(outside)),
189            ..feature
190        })
191    }
192}
193
194/// Whether a boundaries feature says its line is claimed or controlled by
195/// someone: `disputed`, `disputed_by` or `claimed_by`.
196fn carries_claim(feature: &ProcessedFeature) -> bool {
197    feature.properties.iter().any(|(k, v)| {
198        matches!(k.as_str(), "disputed_by" | "claimed_by")
199            || (k == "disputed" && *v == PropValue::Bool(true))
200    })
201}
202
203/// The closed rings of a line or polygon geometry.
204fn closed_rings(geometry: &geo::Geometry<f64>) -> Vec<geo::LineString<f64>> {
205    let is_ring = |line: &&geo::LineString<f64>| line.is_closed() && line.0.len() >= 4;
206    match geometry {
207        geo::Geometry::LineString(line) => [line].into_iter().filter(is_ring).cloned().collect(),
208        geo::Geometry::MultiLineString(lines) => lines.0.iter().filter(is_ring).cloned().collect(),
209        geo::Geometry::Polygon(polygon) => vec![polygon.exterior().clone()],
210        geo::Geometry::MultiPolygon(polygons) => {
211            polygons.0.iter().map(|p| p.exterior().clone()).collect()
212        }
213        _ => Vec::new(),
214    }
215}
216
217/// Whether a boundaries feature is a `kind=country` line.
218fn is_country(feature: &ProcessedFeature) -> bool {
219    feature
220        .properties
221        .iter()
222        .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
223}
224
225/// India bounding box \[`min_lon`, `min_lat`, `max_lon`, `max_lat`\].
226///
227/// OSM `admin_level=2` boundaries within this bbox are suppressed
228/// and replaced by the official India boundary `GeoJSON`.
229const INDIA_BBOX: [f64; 4] = [68.0, 6.5, 97.5, 37.2];
230
231/// Process a feature into a boundaries layer feature.
232///
233/// Routes to the appropriate handler based on data source.
234pub fn process(feature: &InputFeature) -> Option<ProcessedFeature> {
235    match &feature.source {
236        DataSource::Overture { .. } => process_overture(feature),
237        DataSource::NaturalEarth { .. } => process_ne(feature),
238        DataSource::Osm { .. } => process_osm(feature),
239        DataSource::IndiaBoundary => process_india(feature),
240        _ => None,
241    }
242}
243
244/// Process Overture `divisions/division_boundary` features.
245///
246/// The kind comes from `subtype`, not `admin_level`. Overture's
247/// `admin_level` is a relative depth (country and region boundaries are
248/// both 1, counties are 2), so reading it on the OSM scale drew counties as
249/// national borders and dropped every country and region boundary.
250/// `kind_detail` carries the OSM-equivalent level because the protomaps
251/// style draws `kind_detail <= 2` as a national border.
252fn process_overture(feature: &InputFeature) -> Option<ProcessedFeature> {
253    let (kind, admin_level, min_zoom) = overture_subtype_to_kind(feature.get_str("subtype")?)?;
254
255    let disputed = matches!(
256        feature.properties.get("is_disputed"),
257        Some(PropValue::Bool(true))
258    );
259
260    let sort_rank = if disputed { 288 } else { 289 };
261
262    let mut properties = Vec::with_capacity(4);
263    properties.push(("kind".into(), PropValue::Str(kind.into())));
264    properties.push(("kind_detail".into(), PropValue::I64(admin_level)));
265
266    if disputed {
267        properties.push(("disputed".into(), PropValue::Bool(true)));
268    }
269    if feature
270        .get_str("country")
271        .is_some_and(|c| !c.eq_ignore_ascii_case("IN"))
272    {
273        mark_foreign(&mut properties);
274    }
275
276    Some(ProcessedFeature {
277        id: feature.id,
278        geometry: feature.geometry.clone(),
279        layer: Layer::Boundaries,
280        min_zoom,
281        max_zoom: 15,
282        sort_rank,
283        properties,
284    })
285}
286
287/// Process Natural Earth admin boundary lines (z0-5).
288///
289/// Maps NE `featurecla` attribute to kind and disputed status.
290fn process_ne(feature: &InputFeature) -> Option<ProcessedFeature> {
291    let source_layer = feature.ne_source_layer()?;
292
293    let is_boundary_layer = source_layer.starts_with("ne_10m_admin_0_boundary")
294        || source_layer.starts_with("ne_10m_admin_1");
295
296    if !is_boundary_layer {
297        return None;
298    }
299
300    let featurecla = feature.get_str("featurecla").unwrap_or("");
301
302    let (kind, admin_level, disputed) = match featurecla {
303        "International boundary (verify)" => ("country", 2i64, false),
304        "Disputed (please verify)" => ("country", 2, true),
305        "Line of control (please verify)" => ("country", 2, true),
306        "Indefinite (please verify)" => ("country", 2, true),
307        "Lease limit" => ("country", 2, true),
308        "Overlay limit" => ("country", 2, true),
309        "Admin-1 boundary" => ("region", 4, false),
310        "Admin-1 statistical boundary" => ("region", 4, false),
311        "Admin-1 region boundary" => ("region", 4, false),
312        "Unrecognized" => ("country", 2, true),
313        _ if featurecla.contains("disputed") || featurecla.contains("Disputed") => {
314            ("country", 2, true)
315        }
316        _ if featurecla.contains("Admin-1") => ("region", 4, false),
317        _ => ("country", 2, false),
318    };
319
320    let sort_rank = if disputed { 288 } else { 289 };
321
322    let mut properties = Vec::with_capacity(4);
323    properties.push(("kind".into(), PropValue::Str(kind.into())));
324    properties.push(("kind_detail".into(), PropValue::I64(admin_level)));
325
326    if disputed {
327        properties.push(("disputed".into(), PropValue::Bool(true)));
328    }
329    // An admin-1 line of another country: `adm0_a3` is the country the
330    // Natural Earth line belongs to.
331    if kind == "region"
332        && feature
333            .get_str("adm0_a3")
334            .is_some_and(|c| !c.eq_ignore_ascii_case("IND"))
335    {
336        mark_foreign(&mut properties);
337    }
338
339    // Respect NE data's per-feature min_zoom (Planetiler reads this field too).
340    // NE features have different min_zoom values (0–5) controlling when each
341    // boundary line first appears. Without this, ALL boundaries show at z0.
342    let ne_min_zoom = feature
343        .get_f64("min_zoom")
344        .map(|v| (v as u8).min(5))
345        .or_else(|| feature.get_i64("min_zoom").map(|v| (v as u8).min(5)))
346        .unwrap_or(0);
347
348    Some(ProcessedFeature {
349        id: feature.id,
350        geometry: feature.geometry.clone(),
351        layer: Layer::Boundaries,
352        min_zoom: ne_min_zoom,
353        max_zoom: 5,
354        sort_rank,
355        properties,
356    })
357}
358
359/// Process OSM admin boundary features (z6+).
360///
361/// Uses `admin_level` from parent relations. Suppresses `admin_level=2`
362/// boundaries within the India bbox (replaced by official `GeoJSON`).
363fn process_osm(feature: &InputFeature) -> Option<ProcessedFeature> {
364    if !feature.can_be_line() {
365        return None;
366    }
367
368    let relations = feature.osm_relations();
369    if relations.is_empty() {
370        // Fall back to tags on the way itself
371        if feature.has_tag("boundary", "administrative") || feature.has_tag("boundary", "disputed")
372        {
373            let admin_level = feature
374                .get_str("admin_level")
375                .and_then(|v| v.parse::<i64>().ok())
376                .unwrap_or(2);
377
378            let disputed = feature.has_tag("boundary", "disputed")
379                || feature.get_str("disputed").is_some_and(|v| v == "yes")
380                || feature
381                    .get_str("boundary")
382                    .is_some_and(|v| v == "disputed" || v == "claim");
383
384            if admin_level == 2 && is_within_india_bbox(feature) && !disputed {
385                return None;
386            }
387
388            let (kind, min_zoom) = admin_level_to_kind(admin_level)?;
389            let sort_rank = if disputed { 288 } else { 289 };
390
391            let mut properties = Vec::with_capacity(4);
392            properties.push(("kind".into(), PropValue::Str(kind.into())));
393            properties.push(("kind_detail".into(), PropValue::I64(admin_level)));
394            if disputed {
395                properties.push(("disputed".into(), PropValue::Bool(true)));
396            }
397            push_claim_tags(feature, &mut properties);
398
399            return Some(ProcessedFeature {
400                id: feature.id,
401                geometry: feature.geometry.clone(),
402                layer: Layer::Boundaries,
403                min_zoom,
404                max_zoom: 15,
405                sort_rank,
406                properties,
407            });
408        }
409        return None;
410    }
411
412    // Use the highest-priority (lowest admin_level) relation
413    let best_relation = relations
414        .iter()
415        .filter(|r| {
416            r.tags.get("type").is_some_and(|t| t == "boundary")
417                || r.tags
418                    .get("boundary")
419                    .is_some_and(|b| b == "administrative" || b == "disputed")
420        })
421        .min_by_key(|r| r.admin_level.unwrap_or(99));
422
423    let rel = best_relation?;
424    let admin_level = i64::from(rel.admin_level.unwrap_or(2));
425
426    let disputed = rel.disputed
427        || rel
428            .tags
429            .get("boundary")
430            .is_some_and(|v| v == "disputed" || v == "claim")
431        || rel.tags.get("disputed").is_some_and(|v| v == "yes");
432
433    // India fix: skip admin_level=2 within India bbox
434    if admin_level == 2 && is_within_india_bbox(feature) && !disputed {
435        return None;
436    }
437
438    let (kind, min_zoom) = admin_level_to_kind(admin_level)?;
439    let sort_rank = if disputed { 288 } else { 289 };
440
441    let mut properties = Vec::with_capacity(5);
442    properties.push(("kind".into(), PropValue::Str(kind.into())));
443    properties.push(("kind_detail".into(), PropValue::I64(admin_level)));
444
445    if disputed {
446        properties.push(("disputed".into(), PropValue::Bool(true)));
447    }
448
449    push_claim_tags(feature, &mut properties);
450    // A line that is a member of an admin relation of another country.
451    if relations
452        .iter()
453        .filter_map(|r| relation_country(&r.tags))
454        .any(|code| code != "IN")
455    {
456        mark_foreign(&mut properties);
457    }
458
459    Some(ProcessedFeature {
460        id: feature.id,
461        geometry: feature.geometry.clone(),
462        layer: Layer::Boundaries,
463        min_zoom,
464        max_zoom: 15,
465        sort_rank,
466        properties,
467    })
468}
469
470/// Copy the claim tags of an OSM way (`disputed_by`, `claimed_by`) into the
471/// feature properties, so [`carries_claim`] sees them.
472fn push_claim_tags(feature: &InputFeature, properties: &mut Vec<(String, PropValue)>) {
473    for key in ["disputed_by", "claimed_by"] {
474        if let Some(value) = feature.get_str(key) {
475            properties.push((key.into(), PropValue::Str(value.to_string())));
476        }
477    }
478}
479
480/// The ISO 3166-1 code of the country an OSM admin relation belongs to: its
481/// `ISO3166-1` tags, else the country part of `ISO3166-2` (`PK-GB`).
482fn relation_country(tags: &std::collections::HashMap<String, String>) -> Option<String> {
483    let code = ["ISO3166-1:alpha2", "ISO3166-1"]
484        .iter()
485        .find_map(|key| tags.get(*key))
486        .or_else(|| tags.get("ISO3166-2"))?;
487    let country = code.split(['-', ';']).next()?.trim().to_ascii_uppercase();
488    (country.len() == 2).then_some(country)
489}
490
491/// Process India boundary `GeoJSON` features (z0+). From z0, because
492/// [`IndiaMask`] removes the Natural Earth country lines inside India at
493/// z0–z5 too.
494fn process_india(feature: &InputFeature) -> Option<ProcessedFeature> {
495    let kind = feature.get_str("kind").unwrap_or("country");
496    let kind_detail = feature.get_i64("kind_detail").unwrap_or(2);
497
498    let mut properties = Vec::with_capacity(3);
499    properties.push(("kind".into(), PropValue::Str(kind.to_string())));
500    properties.push(("kind_detail".into(), PropValue::I64(kind_detail)));
501
502    if let Some(name) = feature.get_str("name") {
503        properties.push(("name".into(), PropValue::Str(name.to_string())));
504    }
505
506    Some(ProcessedFeature {
507        id: feature.id,
508        geometry: feature.geometry.clone(),
509        layer: Layer::Boundaries,
510        min_zoom: 0,
511        max_zoom: 15,
512        sort_rank: 289,
513        properties,
514    })
515}
516
517/// Map an Overture division `subtype` to (kind, OSM-equivalent `admin_level`, `min_zoom`).
518///
519/// Levels match [`admin_level_to_kind`]: country 2, region 4, county 6,
520/// locality 8. Subtypes finer than locality are dropped, as OSM levels
521/// above 8 are.
522fn overture_subtype_to_kind(subtype: &str) -> Option<(&'static str, i64, u8)> {
523    match subtype {
524        "country" | "dependency" => Some(("country", 2, 6)),
525        "macroregion" | "region" => Some(("region", 4, 6)),
526        "macrocounty" | "county" => Some(("county", 6, 8)),
527        "localadmin" | "locality" | "borough" => Some(("locality", 8, 10)),
528        _ => None,
529    }
530}
531
532/// Map `admin_level` integer to (kind, `min_zoom`).
533///
534/// Returns `None` for `admin_level` > 8, matching Planetiler which drops
535/// these entirely.
536const fn admin_level_to_kind(admin_level: i64) -> Option<(&'static str, u8)> {
537    match admin_level {
538        2 => Some(("country", 6)),
539        3 | 4 => Some(("region", 6)),
540        5 | 6 => Some(("county", 8)),
541        7 | 8 => Some(("locality", 10)),
542        _ => None,
543    }
544}
545
546/// Check if a feature's bbox or geometry centroid is within the India bbox.
547fn is_within_india_bbox(feature: &InputFeature) -> bool {
548    if let Some(bbox) = feature.bbox {
549        let cx = (bbox[0] + bbox[2]) / 2.0;
550        let cy = (bbox[1] + bbox[3]) / 2.0;
551        return (INDIA_BBOX[0]..=INDIA_BBOX[2]).contains(&cx)
552            && (INDIA_BBOX[1]..=INDIA_BBOX[3]).contains(&cy);
553    }
554
555    // Fall back to checking first coordinate of geometry
556    match feature.geometry.as_ref() {
557        geo::Geometry::LineString(ls) => {
558            if let Some(coord) = ls.0.first() {
559                return coord.x >= INDIA_BBOX[0]
560                    && coord.x <= INDIA_BBOX[2]
561                    && coord.y >= INDIA_BBOX[1]
562                    && coord.y <= INDIA_BBOX[3];
563            }
564        }
565        geo::Geometry::Point(pt) => {
566            return pt.x() >= INDIA_BBOX[0]
567                && pt.x() <= INDIA_BBOX[2]
568                && pt.y() >= INDIA_BBOX[1]
569                && pt.y() <= INDIA_BBOX[3];
570        }
571        _ => {}
572    }
573    false
574}
575
576#[cfg(test)]
577mod tests {
578    use super::*;
579    use crate::source::input::{DataSource, OsmElementType, RelationInfo};
580    use std::collections::HashMap;
581    use std::sync::Arc;
582
583    fn props_map(props: &[(&str, PropValue)]) -> HashMap<String, PropValue> {
584        let mut m = HashMap::new();
585        for (k, v) in props {
586            m.insert(k.to_string(), v.clone());
587        }
588        m
589    }
590
591    fn line_geom() -> Arc<geo::Geometry<f64>> {
592        Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
593            (0.0, 0.0),
594            (1.0, 1.0),
595        ])))
596    }
597
598    fn make_feature(props: &[(&str, PropValue)]) -> InputFeature {
599        InputFeature {
600            id: 1,
601            geometry: line_geom(),
602            properties: props_map(props),
603            bbox: None,
604            source: DataSource::Overture {
605                theme: String::new(),
606                otype: String::new(),
607            },
608        }
609    }
610
611    fn make_ne_feature(layer: &str, props: &[(&str, PropValue)]) -> InputFeature {
612        InputFeature {
613            id: 1,
614            geometry: line_geom(),
615            properties: props_map(props),
616            bbox: None,
617            source: DataSource::NaturalEarth {
618                source_layer: layer.to_string(),
619            },
620        }
621    }
622
623    fn make_osm_way(props: &[(&str, PropValue)], relations: Vec<RelationInfo>) -> InputFeature {
624        InputFeature {
625            id: 1,
626            geometry: line_geom(),
627            properties: props_map(props),
628            bbox: None,
629            source: DataSource::Osm {
630                element_type: OsmElementType::Way,
631                relations,
632            },
633        }
634    }
635
636    fn make_india_feature(props: &[(&str, PropValue)]) -> InputFeature {
637        InputFeature {
638            id: 1,
639            geometry: line_geom(),
640            properties: props_map(props),
641            bbox: None,
642            source: DataSource::IndiaBoundary,
643        }
644    }
645
646    fn rel_with(admin_level: Option<i32>, disputed: bool, tags: &[(&str, &str)]) -> RelationInfo {
647        let mut t = HashMap::new();
648        for (k, v) in tags {
649            t.insert(k.to_string(), v.to_string());
650        }
651        RelationInfo {
652            id: 1,
653            admin_level,
654            disputed,
655            role: String::new(),
656            tags: t,
657        }
658    }
659
660    // ─── dispatch (process) ────────────────────────────────────────────
661
662    #[test]
663    fn dispatch_unsupported_source_returns_none() {
664        let feat = InputFeature {
665            id: 1,
666            geometry: line_geom(),
667            properties: HashMap::new(),
668            bbox: None,
669            source: DataSource::LandPolygons,
670        };
671        assert!(process(&feat).is_none());
672
673        let feat2 = InputFeature {
674            source: DataSource::WaterPolygons,
675            ..feat
676        };
677        assert!(process(&feat2).is_none());
678    }
679
680    // ─── process_overture ──────────────────────────────────────────────
681
682    fn kind_of(result: &ProcessedFeature) -> Option<&PropValue> {
683        result
684            .properties
685            .iter()
686            .find(|(k, _)| k == "kind")
687            .map(|(_, v)| v)
688    }
689
690    fn detail_of(result: &ProcessedFeature) -> Option<&PropValue> {
691        result
692            .properties
693            .iter()
694            .find(|(k, _)| k == "kind_detail")
695            .map(|(_, v)| v)
696    }
697
698    /// Values observed in the 2026-08-19.0 release: a US county boundary
699    /// carries `admin_level = 2`. It must still be a county, not a country.
700    #[test]
701    fn overture_county_with_relative_admin_level_2_is_not_a_country() {
702        let feat = make_feature(&[
703            ("subtype", PropValue::Str("county".into())),
704            ("admin_level", PropValue::I64(2)),
705        ]);
706        let result = process(&feat).unwrap();
707        assert_eq!(kind_of(&result), Some(&PropValue::Str("county".into())));
708        assert_eq!(detail_of(&result), Some(&PropValue::I64(6)));
709        assert_eq!(result.min_zoom, 8);
710    }
711
712    /// Country and region boundaries carry `admin_level = 1` in Overture.
713    /// On the OSM scale that level was dropped; both must now survive.
714    #[test]
715    fn overture_country_with_relative_admin_level_1_is_kept() {
716        let feat = make_feature(&[
717            ("subtype", PropValue::Str("country".into())),
718            ("admin_level", PropValue::I64(1)),
719        ]);
720        let result = process(&feat).unwrap();
721        assert_eq!(result.layer, Layer::Boundaries);
722        assert_eq!(kind_of(&result), Some(&PropValue::Str("country".into())));
723        assert_eq!(detail_of(&result), Some(&PropValue::I64(2)));
724        assert_eq!(result.min_zoom, 6);
725        assert_eq!(result.sort_rank, 289);
726    }
727
728    #[test]
729    fn overture_region_with_relative_admin_level_1_is_kept() {
730        let feat = make_feature(&[
731            ("subtype", PropValue::Str("region".into())),
732            ("admin_level", PropValue::I64(1)),
733        ]);
734        let result = process(&feat).unwrap();
735        assert_eq!(kind_of(&result), Some(&PropValue::Str("region".into())));
736        assert_eq!(detail_of(&result), Some(&PropValue::I64(4)));
737    }
738
739    #[test]
740    fn overture_subtype_levels_follow_the_osm_scale() {
741        let cases = [
742            ("dependency", "country", 2, 6),
743            ("macroregion", "region", 4, 6),
744            ("macrocounty", "county", 6, 8),
745            ("localadmin", "locality", 8, 10),
746            ("locality", "locality", 8, 10),
747            ("borough", "locality", 8, 10),
748        ];
749        for (subtype, kind, level, zoom) in cases {
750            let feat = make_feature(&[("subtype", PropValue::Str(subtype.into()))]);
751            let result = process(&feat).unwrap();
752            assert_eq!(
753                kind_of(&result),
754                Some(&PropValue::Str(kind.into())),
755                "{subtype}"
756            );
757            assert_eq!(
758                detail_of(&result),
759                Some(&PropValue::I64(level)),
760                "{subtype}"
761            );
762            assert_eq!(result.min_zoom, zoom, "{subtype}");
763        }
764    }
765
766    #[test]
767    fn overture_neighborhood_boundaries_are_dropped() {
768        for subtype in ["macrohood", "neighborhood", "microhood"] {
769            let feat = make_feature(&[("subtype", PropValue::Str(subtype.into()))]);
770            assert!(process(&feat).is_none(), "{subtype}");
771        }
772    }
773
774    #[test]
775    fn overture_boundary_without_subtype_is_dropped() {
776        let feat = make_feature(&[("admin_level", PropValue::I64(2))]);
777        assert!(process(&feat).is_none());
778    }
779
780    /// `is_disputed` is a boolean column in the Overture schema.
781    #[test]
782    fn overture_disputed_boolean_lowers_sort_rank() {
783        let feat = make_feature(&[
784            ("subtype", PropValue::Str("country".into())),
785            ("is_disputed", PropValue::Bool(true)),
786        ]);
787        let result = process(&feat).unwrap();
788        assert_eq!(result.sort_rank, 288);
789        assert!(
790            result
791                .properties
792                .iter()
793                .any(|(k, v)| k == "disputed" && *v == PropValue::Bool(true))
794        );
795    }
796
797    #[test]
798    fn overture_undisputed_boolean_keeps_default_sort_rank() {
799        let feat = make_feature(&[
800            ("subtype", PropValue::Str("country".into())),
801            ("is_disputed", PropValue::Bool(false)),
802        ]);
803        let result = process(&feat).unwrap();
804        assert_eq!(result.sort_rank, 289);
805        assert!(!result.properties.iter().any(|(k, _)| k == "disputed"));
806    }
807    // ─── process_ne ────────────────────────────────────────────────────
808
809    #[test]
810    fn ne_non_boundary_layer_returns_none() {
811        let feat = make_ne_feature("ne_10m_lakes", &[]);
812        assert!(process(&feat).is_none());
813    }
814
815    /// Every Natural Earth `featurecla` value, with the kind, admin level and
816    /// disputed flag the NE boundary attributes document for it, and the
817    /// protomaps sort rank (288 disputed, 289 otherwise). Unknown
818    /// values fall back on their "Disputed" or "Admin-1" keyword.
819    #[test]
820    fn ne_featurecla_values_map_to_kind_level_and_disputed() {
821        let cases = [
822            ("Disputed (please verify)", "country", 2, true, 288),
823            ("Line of control (please verify)", "country", 2, true, 288),
824            ("Indefinite (please verify)", "country", 2, true, 288),
825            ("Lease limit", "country", 2, true, 288),
826            ("Overlay limit", "country", 2, true, 288),
827            ("Unrecognized", "country", 2, true, 288),
828            ("Some weird disputed thing", "country", 2, true, 288),
829            ("Something Disputed weird", "country", 2, true, 288),
830            ("Admin-1 boundary", "region", 4, false, 289),
831            ("Admin-1 statistical boundary", "region", 4, false, 289),
832            ("Admin-1 region boundary", "region", 4, false, 289),
833            ("Custom Admin-1 thing", "region", 4, false, 289),
834        ];
835        for (featurecla, kind, level, disputed, rank) in cases {
836            let feat = make_ne_feature(
837                "ne_10m_admin_0_boundary_lines_land",
838                &[("featurecla", PropValue::Str(featurecla.into()))],
839            );
840            let result = process(&feat).expect(featurecla);
841            let prop = |key: &str| {
842                result
843                    .properties
844                    .iter()
845                    .find(|(k, _)| k == key)
846                    .map(|(_, v)| v.clone())
847            };
848            assert_eq!(
849                prop("kind"),
850                Some(PropValue::Str(kind.into())),
851                "{featurecla}"
852            );
853            assert_eq!(
854                prop("kind_detail"),
855                Some(PropValue::I64(level)),
856                "{featurecla}"
857            );
858            assert_eq!(
859                prop("disputed"),
860                disputed.then_some(PropValue::Bool(true)),
861                "{featurecla}"
862            );
863            assert_eq!(result.sort_rank, rank, "{featurecla}");
864        }
865    }
866
867    #[test]
868    fn ne_admin_0_international_boundary() {
869        let feat = make_ne_feature(
870            "ne_10m_admin_0_boundary_lines_land",
871            &[(
872                "featurecla",
873                PropValue::Str("International boundary (verify)".into()),
874            )],
875        );
876        let result = process(&feat).unwrap();
877        assert_eq!(result.layer, Layer::Boundaries);
878        assert_eq!(result.max_zoom, 5);
879        assert_eq!(result.sort_rank, 289);
880        assert!(
881            result
882                .properties
883                .iter()
884                .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
885        );
886    }
887
888    #[test]
889    fn ne_unknown_default_country() {
890        let feat = make_ne_feature(
891            "ne_10m_admin_0_boundary_lines_land",
892            &[("featurecla", PropValue::Str("Mystery line".into()))],
893        );
894        let result = process(&feat).unwrap();
895        assert!(
896            result
897                .properties
898                .iter()
899                .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
900        );
901        assert_eq!(result.sort_rank, 289);
902    }
903
904    #[test]
905    fn ne_missing_featurecla_default_country() {
906        let feat = make_ne_feature("ne_10m_admin_0_boundary_lines_land", &[]);
907        let result = process(&feat).unwrap();
908        assert!(
909            result
910                .properties
911                .iter()
912                .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
913        );
914    }
915
916    #[test]
917    fn ne_min_zoom_from_f64_clamped() {
918        let feat = make_ne_feature(
919            "ne_10m_admin_0_boundary_lines_land",
920            &[
921                ("featurecla", PropValue::Str("Mystery".into())),
922                ("min_zoom", PropValue::F64(8.0)),
923            ],
924        );
925        let result = process(&feat).unwrap();
926        assert_eq!(result.min_zoom, 5);
927    }
928
929    #[test]
930    fn ne_min_zoom_from_f64_within_range() {
931        let feat = make_ne_feature(
932            "ne_10m_admin_0_boundary_lines_land",
933            &[
934                ("featurecla", PropValue::Str("Mystery".into())),
935                ("min_zoom", PropValue::F64(3.0)),
936            ],
937        );
938        let result = process(&feat).unwrap();
939        assert_eq!(result.min_zoom, 3);
940    }
941
942    #[test]
943    fn ne_min_zoom_from_i64() {
944        let feat = make_ne_feature(
945            "ne_10m_admin_0_boundary_lines_land",
946            &[
947                ("featurecla", PropValue::Str("Mystery".into())),
948                ("min_zoom", PropValue::I64(2)),
949            ],
950        );
951        let result = process(&feat).unwrap();
952        assert_eq!(result.min_zoom, 2);
953    }
954
955    #[test]
956    fn ne_min_zoom_default_zero() {
957        let feat = make_ne_feature(
958            "ne_10m_admin_0_boundary_lines_land",
959            &[("featurecla", PropValue::Str("Mystery".into()))],
960        );
961        let result = process(&feat).unwrap();
962        assert_eq!(result.min_zoom, 0);
963    }
964
965    // ─── process_osm ───────────────────────────────────────────────────
966
967    #[test]
968    fn osm_non_line_returns_none() {
969        let feat = InputFeature {
970            id: 1,
971            geometry: Arc::new(geo::Geometry::Point(geo::Point::new(0.0, 0.0))),
972            properties: HashMap::new(),
973            bbox: None,
974            source: DataSource::Osm {
975                element_type: OsmElementType::Way,
976                relations: vec![],
977            },
978        };
979        assert!(process(&feat).is_none());
980    }
981
982    #[test]
983    fn osm_no_relations_no_tag_returns_none() {
984        let feat = make_osm_way(&[], vec![]);
985        assert!(process(&feat).is_none());
986    }
987
988    #[test]
989    fn osm_no_relations_with_admin_tag() {
990        let feat = make_osm_way(
991            &[
992                ("boundary", PropValue::Str("administrative".into())),
993                ("admin_level", PropValue::Str("4".into())),
994            ],
995            vec![],
996        );
997        let result = process(&feat).unwrap();
998        assert_eq!(result.min_zoom, 6);
999        assert!(
1000            result
1001                .properties
1002                .iter()
1003                .any(|(k, v)| k == "kind" && *v == PropValue::Str("region".into()))
1004        );
1005    }
1006
1007    /// A way with no relation and no usable `admin_level` is treated as a
1008    /// country border.
1009    #[test]
1010    fn osm_no_relations_missing_or_unparseable_admin_level_is_a_country() {
1011        let missing = vec![("boundary", PropValue::Str("administrative".into()))];
1012        let mut unparseable = missing.clone();
1013        unparseable.push(("admin_level", PropValue::Str("not-a-number".into())));
1014        for tags in [missing, unparseable] {
1015            let result = process(&make_osm_way(&tags, vec![])).expect("a boundary");
1016            assert_eq!(
1017                kind_of(&result),
1018                Some(&PropValue::Str("country".into())),
1019                "{tags:?}"
1020            );
1021        }
1022    }
1023
1024    #[test]
1025    fn osm_no_relations_dropped_admin_level_returns_none() {
1026        let feat = make_osm_way(
1027            &[
1028                ("boundary", PropValue::Str("administrative".into())),
1029                ("admin_level", PropValue::Str("9".into())),
1030            ],
1031            vec![],
1032        );
1033        assert!(process(&feat).is_none());
1034    }
1035
1036    #[test]
1037    fn osm_no_relations_boundary_disputed_tag() {
1038        let feat = make_osm_way(&[("boundary", PropValue::Str("disputed".into()))], vec![]);
1039        let result = process(&feat).unwrap();
1040        assert_eq!(result.sort_rank, 288);
1041        assert!(
1042            result
1043                .properties
1044                .iter()
1045                .any(|(k, v)| k == "disputed" && *v == PropValue::Bool(true))
1046        );
1047    }
1048
1049    #[test]
1050    fn osm_no_relations_disputed_yes_tag() {
1051        let feat = make_osm_way(
1052            &[
1053                ("boundary", PropValue::Str("administrative".into())),
1054                ("admin_level", PropValue::Str("2".into())),
1055                ("disputed", PropValue::Str("yes".into())),
1056            ],
1057            vec![],
1058        );
1059        let result = process(&feat).unwrap();
1060        assert_eq!(result.sort_rank, 288);
1061    }
1062
1063    #[test]
1064    fn osm_no_relations_boundary_claim() {
1065        let feat = make_osm_way(
1066            &[
1067                ("boundary", PropValue::Str("claim".into())),
1068                ("admin_level", PropValue::Str("2".into())),
1069            ],
1070            vec![],
1071        );
1072        // boundary=claim doesn't trigger has_tag("boundary","administrative") nor "disputed"
1073        // so it falls into the empty-relations + no-tag branch → None
1074        assert!(process(&feat).is_none());
1075    }
1076
1077    #[test]
1078    fn osm_no_relations_india_level_2_suppressed() {
1079        let mut feat = make_osm_way(
1080            &[
1081                ("boundary", PropValue::Str("administrative".into())),
1082                ("admin_level", PropValue::Str("2".into())),
1083            ],
1084            vec![],
1085        );
1086        feat.bbox = Some([78.0, 20.0, 80.0, 22.0]); // inside India
1087        assert!(process(&feat).is_none());
1088    }
1089
1090    #[test]
1091    fn osm_no_relations_india_level_2_disputed_kept() {
1092        let mut feat = make_osm_way(
1093            &[
1094                ("boundary", PropValue::Str("disputed".into())),
1095                ("admin_level", PropValue::Str("2".into())),
1096            ],
1097            vec![],
1098        );
1099        feat.bbox = Some([78.0, 20.0, 80.0, 22.0]);
1100        let result = process(&feat).unwrap();
1101        assert_eq!(result.sort_rank, 288);
1102    }
1103
1104    #[test]
1105    fn osm_no_relations_india_level_4_kept() {
1106        let mut feat = make_osm_way(
1107            &[
1108                ("boundary", PropValue::Str("administrative".into())),
1109                ("admin_level", PropValue::Str("4".into())),
1110            ],
1111            vec![],
1112        );
1113        feat.bbox = Some([78.0, 20.0, 80.0, 22.0]);
1114        assert!(process(&feat).is_some());
1115    }
1116
1117    #[test]
1118    fn osm_relations_picks_lowest_admin_level() {
1119        let feat = make_osm_way(
1120            &[],
1121            vec![
1122                rel_with(Some(6), false, &[("type", "boundary")]),
1123                rel_with(Some(2), false, &[("type", "boundary")]),
1124                rel_with(Some(4), false, &[("type", "boundary")]),
1125            ],
1126        );
1127        let result = process(&feat).unwrap();
1128        assert!(
1129            result
1130                .properties
1131                .iter()
1132                .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
1133        );
1134    }
1135
1136    #[test]
1137    fn osm_relations_filter_boundary_administrative() {
1138        let feat = make_osm_way(
1139            &[],
1140            vec![rel_with(Some(4), false, &[("boundary", "administrative")])],
1141        );
1142        let result = process(&feat).unwrap();
1143        assert!(
1144            result
1145                .properties
1146                .iter()
1147                .any(|(k, v)| k == "kind" && *v == PropValue::Str("region".into()))
1148        );
1149    }
1150
1151    #[test]
1152    fn osm_relations_filter_boundary_disputed() {
1153        let feat = make_osm_way(
1154            &[],
1155            vec![rel_with(Some(2), false, &[("boundary", "disputed")])],
1156        );
1157        let result = process(&feat).unwrap();
1158        assert_eq!(result.sort_rank, 288);
1159    }
1160
1161    #[test]
1162    fn osm_relations_no_match_returns_none() {
1163        let feat = make_osm_way(
1164            &[],
1165            vec![rel_with(Some(2), false, &[("type", "multipolygon")])],
1166        );
1167        assert!(process(&feat).is_none());
1168    }
1169
1170    #[test]
1171    fn osm_relations_admin_level_default_when_missing() {
1172        let feat = make_osm_way(&[], vec![rel_with(None, false, &[("type", "boundary")])]);
1173        let result = process(&feat).unwrap();
1174        assert!(
1175            result
1176                .properties
1177                .iter()
1178                .any(|(k, v)| k == "kind_detail" && *v == PropValue::I64(2))
1179        );
1180    }
1181
1182    #[test]
1183    fn osm_relations_dropped_admin_level_returns_none() {
1184        let feat = make_osm_way(&[], vec![rel_with(Some(9), false, &[("type", "boundary")])]);
1185        assert!(process(&feat).is_none());
1186    }
1187
1188    /// Each of the three ways OSM marks a relation as disputed gives the
1189    /// disputed sort rank (288).
1190    #[test]
1191    fn osm_relations_disputed_by_flag_claim_or_disputed_tag() {
1192        let relations = [
1193            rel_with(Some(2), true, &[("type", "boundary")]),
1194            rel_with(
1195                Some(2),
1196                false,
1197                &[("type", "boundary"), ("boundary", "claim")],
1198            ),
1199            rel_with(Some(2), false, &[("type", "boundary"), ("disputed", "yes")]),
1200        ];
1201        for rel in relations {
1202            let tags = format!("{:?}", rel.tags);
1203            let result = process(&make_osm_way(&[], vec![rel])).expect("a boundary");
1204            assert_eq!(result.sort_rank, 288, "{tags}");
1205        }
1206    }
1207
1208    #[test]
1209    fn osm_relations_india_level_2_suppressed() {
1210        let mut feat = make_osm_way(&[], vec![rel_with(Some(2), false, &[("type", "boundary")])]);
1211        feat.bbox = Some([78.0, 20.0, 80.0, 22.0]);
1212        assert!(process(&feat).is_none());
1213    }
1214
1215    #[test]
1216    fn osm_relations_india_level_2_disputed_kept() {
1217        let mut feat = make_osm_way(&[], vec![rel_with(Some(2), true, &[("type", "boundary")])]);
1218        feat.bbox = Some([78.0, 20.0, 80.0, 22.0]);
1219        let result = process(&feat).unwrap();
1220        assert_eq!(result.sort_rank, 288);
1221    }
1222
1223    #[test]
1224    fn osm_relations_disputed_by_property_added() {
1225        let feat = make_osm_way(
1226            &[("disputed_by", PropValue::Str("CountryX".into()))],
1227            vec![rel_with(Some(2), true, &[("type", "boundary")])],
1228        );
1229        let result = process(&feat).unwrap();
1230        assert!(
1231            result
1232                .properties
1233                .iter()
1234                .any(|(k, v)| k == "disputed_by" && *v == PropValue::Str("CountryX".into()))
1235        );
1236    }
1237
1238    #[test]
1239    fn osm_relations_claimed_by_property_added() {
1240        let feat = make_osm_way(
1241            &[("claimed_by", PropValue::Str("CountryY".into()))],
1242            vec![rel_with(Some(2), true, &[("type", "boundary")])],
1243        );
1244        let result = process(&feat).unwrap();
1245        assert!(
1246            result
1247                .properties
1248                .iter()
1249                .any(|(k, v)| k == "claimed_by" && *v == PropValue::Str("CountryY".into()))
1250        );
1251    }
1252
1253    // ─── process_india ─────────────────────────────────────────────────
1254
1255    /// A 10° × 10° square of "India" (0..10, 0..10) as one closed ring,
1256    /// the shape `--india-boundary` uses.
1257    fn square_mask() -> IndiaMask {
1258        let ring = geo::LineString::from(vec![
1259            (0.0, 0.0),
1260            (10.0, 0.0),
1261            (10.0, 10.0),
1262            (0.0, 10.0),
1263            (0.0, 0.0),
1264        ]);
1265        let feat = InputFeature {
1266            geometry: Arc::new(geo::Geometry::MultiLineString(geo::MultiLineString::new(
1267                vec![ring],
1268            ))),
1269            ..make_india_feature(&[])
1270        };
1271        IndiaMask::from_features(&[feat]).unwrap()
1272    }
1273
1274    fn country_line(coords: Vec<(f64, f64)>, disputed: bool) -> ProcessedFeature {
1275        let mut props = vec![("subtype", PropValue::Str("country".into()))];
1276        if disputed {
1277            props.push(("is_disputed", PropValue::Bool(true)));
1278        }
1279        let mut feat = make_feature(&props);
1280        feat.geometry = Arc::new(geo::Geometry::LineString(geo::LineString::from(coords)));
1281        process(&feat).unwrap()
1282    }
1283
1284    fn total_length(feature: &ProcessedFeature) -> f64 {
1285        use geo::{Euclidean, Length};
1286        match feature.geometry.as_ref() {
1287            geo::Geometry::MultiLineString(m) => Euclidean.length(m),
1288            geo::Geometry::LineString(l) => Euclidean.length(l),
1289            other => panic!("unexpected geometry {other:?}"),
1290        }
1291    }
1292
1293    /// A line from x=-5 to x=15 at y=5 crosses the square: only the parts
1294    /// outside the square plus the margin stay, 5 - margin on each side.
1295    #[test]
1296    fn india_mask_keeps_only_the_country_line_outside_india() {
1297        let line = country_line(vec![(-5.0, 5.0), (15.0, 5.0)], false);
1298        let clipped = square_mask().clip(line).unwrap();
1299        let expected = 2.0 * (5.0 - MASK_MARGIN_DEG);
1300        assert!((total_length(&clipped) - expected).abs() < 1e-6);
1301    }
1302
1303    /// The Line of Control case: a country line (disputed or not) wholly
1304    /// inside India is dropped.
1305    #[test]
1306    fn india_mask_drops_country_lines_inside_india() {
1307        let mask = square_mask();
1308        for disputed in [false, true] {
1309            let line = country_line(vec![(2.0, 2.0), (8.0, 8.0)], disputed);
1310            assert!(mask.clip(line).is_none(), "disputed={disputed}");
1311        }
1312    }
1313
1314    /// A source's own copy of India's border, 100 m off the Survey of India
1315    /// line, goes too.
1316    #[test]
1317    fn india_mask_drops_a_copy_of_the_border_inside_the_margin() {
1318        let line = country_line(vec![(-0.001, 2.0), (-0.001, 8.0)], false);
1319        assert!(square_mask().clip(line).is_none());
1320    }
1321
1322    #[test]
1323    fn india_mask_leaves_regions_and_far_lines_alone() {
1324        let mask = square_mask();
1325        let mut region = make_feature(&[("subtype", PropValue::Str("region".into()))]);
1326        region.geometry = Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
1327            (2.0, 2.0),
1328            (8.0, 8.0),
1329        ])));
1330        let region = process(&region).unwrap();
1331        let kept = mask.clip(region.clone()).unwrap();
1332        assert!(Arc::ptr_eq(&kept.geometry, &region.geometry));
1333
1334        let far = country_line(vec![(40.0, 40.0), (50.0, 50.0)], false);
1335        let kept = mask.clip(far.clone()).unwrap();
1336        assert!(Arc::ptr_eq(&kept.geometry, &far.geometry));
1337    }
1338
1339    #[test]
1340    fn india_mask_needs_a_closed_ring() {
1341        assert!(IndiaMask::from_features(&[make_india_feature(&[])]).is_none());
1342    }
1343
1344    #[test]
1345    fn india_default_kind_and_detail() {
1346        let feat = make_india_feature(&[]);
1347        let result = process(&feat).unwrap();
1348        assert_eq!(result.layer, Layer::Boundaries);
1349        // From z0: the mask also removes Natural Earth lines at z0-z5.
1350        assert_eq!(result.min_zoom, 0);
1351        assert_eq!(result.max_zoom, 15);
1352        assert_eq!(result.sort_rank, 289);
1353        assert!(
1354            result
1355                .properties
1356                .iter()
1357                .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
1358        );
1359        assert!(
1360            result
1361                .properties
1362                .iter()
1363                .any(|(k, v)| k == "kind_detail" && *v == PropValue::I64(2))
1364        );
1365    }
1366
1367    #[test]
1368    fn india_custom_kind_and_detail() {
1369        let feat = make_india_feature(&[
1370            ("kind", PropValue::Str("region".into())),
1371            ("kind_detail", PropValue::I64(4)),
1372        ]);
1373        let result = process(&feat).unwrap();
1374        assert!(
1375            result
1376                .properties
1377                .iter()
1378                .any(|(k, v)| k == "kind" && *v == PropValue::Str("region".into()))
1379        );
1380        assert!(
1381            result
1382                .properties
1383                .iter()
1384                .any(|(k, v)| k == "kind_detail" && *v == PropValue::I64(4))
1385        );
1386    }
1387
1388    #[test]
1389    fn india_with_name_property() {
1390        let feat = make_india_feature(&[("name", PropValue::Str("India".into()))]);
1391        let result = process(&feat).unwrap();
1392        assert!(
1393            result
1394                .properties
1395                .iter()
1396                .any(|(k, v)| k == "name" && *v == PropValue::Str("India".into()))
1397        );
1398    }
1399
1400    // ─── admin_level_to_kind direct ────────────────────────────────────
1401
1402    #[test]
1403    fn admin_level_to_kind_all_branches() {
1404        assert_eq!(admin_level_to_kind(2), Some(("country", 6)));
1405        assert_eq!(admin_level_to_kind(3), Some(("region", 6)));
1406        assert_eq!(admin_level_to_kind(4), Some(("region", 6)));
1407        assert_eq!(admin_level_to_kind(5), Some(("county", 8)));
1408        assert_eq!(admin_level_to_kind(6), Some(("county", 8)));
1409        assert_eq!(admin_level_to_kind(7), Some(("locality", 10)));
1410        assert_eq!(admin_level_to_kind(8), Some(("locality", 10)));
1411        assert_eq!(admin_level_to_kind(0), None);
1412        assert_eq!(admin_level_to_kind(1), None);
1413        assert_eq!(admin_level_to_kind(9), None);
1414        assert_eq!(admin_level_to_kind(100), None);
1415        assert_eq!(admin_level_to_kind(-1), None);
1416    }
1417
1418    // ─── is_within_india_bbox ──────────────────────────────────────────
1419
1420    #[test]
1421    fn india_bbox_centroid_inside() {
1422        let feat = InputFeature {
1423            id: 1,
1424            geometry: line_geom(),
1425            properties: HashMap::new(),
1426            bbox: Some([77.0, 20.0, 79.0, 22.0]),
1427            source: DataSource::IndiaBoundary,
1428        };
1429        assert!(is_within_india_bbox(&feat));
1430    }
1431
1432    #[test]
1433    fn india_bbox_centroid_outside() {
1434        let feat = InputFeature {
1435            id: 1,
1436            geometry: line_geom(),
1437            properties: HashMap::new(),
1438            bbox: Some([0.0, 0.0, 1.0, 1.0]),
1439            source: DataSource::IndiaBoundary,
1440        };
1441        assert!(!is_within_india_bbox(&feat));
1442    }
1443
1444    #[test]
1445    fn india_bbox_fallback_linestring_inside() {
1446        let feat = InputFeature {
1447            id: 1,
1448            geometry: Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
1449                (78.0, 20.0),
1450                (79.0, 22.0),
1451            ]))),
1452            properties: HashMap::new(),
1453            bbox: None,
1454            source: DataSource::IndiaBoundary,
1455        };
1456        assert!(is_within_india_bbox(&feat));
1457    }
1458
1459    #[test]
1460    fn india_bbox_fallback_linestring_outside() {
1461        let feat = InputFeature {
1462            id: 1,
1463            geometry: Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
1464                (0.0, 0.0),
1465                (1.0, 1.0),
1466            ]))),
1467            properties: HashMap::new(),
1468            bbox: None,
1469            source: DataSource::IndiaBoundary,
1470        };
1471        assert!(!is_within_india_bbox(&feat));
1472    }
1473
1474    #[test]
1475    fn india_bbox_fallback_empty_linestring() {
1476        let feat = InputFeature {
1477            id: 1,
1478            geometry: Arc::new(geo::Geometry::LineString(geo::LineString::from(Vec::<(
1479                f64,
1480                f64,
1481            )>::new(
1482            )))),
1483            properties: HashMap::new(),
1484            bbox: None,
1485            source: DataSource::IndiaBoundary,
1486        };
1487        assert!(!is_within_india_bbox(&feat));
1488    }
1489
1490    #[test]
1491    fn india_bbox_fallback_point_inside() {
1492        let feat = InputFeature {
1493            id: 1,
1494            geometry: Arc::new(geo::Geometry::Point(geo::Point::new(78.0, 20.0))),
1495            properties: HashMap::new(),
1496            bbox: None,
1497            source: DataSource::IndiaBoundary,
1498        };
1499        assert!(is_within_india_bbox(&feat));
1500    }
1501
1502    #[test]
1503    fn india_bbox_fallback_point_outside() {
1504        let feat = InputFeature {
1505            id: 1,
1506            geometry: Arc::new(geo::Geometry::Point(geo::Point::new(0.0, 0.0))),
1507            properties: HashMap::new(),
1508            bbox: None,
1509            source: DataSource::IndiaBoundary,
1510        };
1511        assert!(!is_within_india_bbox(&feat));
1512    }
1513
1514    #[test]
1515    fn india_bbox_fallback_other_geom() {
1516        let feat = InputFeature {
1517            id: 1,
1518            geometry: Arc::new(geo::Geometry::Polygon(geo::Polygon::new(
1519                geo::LineString::from(vec![(78.0, 20.0), (79.0, 20.0), (79.0, 21.0), (78.0, 20.0)]),
1520                vec![],
1521            ))),
1522            properties: HashMap::new(),
1523            bbox: None,
1524            source: DataSource::IndiaBoundary,
1525        };
1526        // Polygon falls into the `_ => {}` arm → false
1527        assert!(!is_within_india_bbox(&feat));
1528    }
1529
1530    // ─── the Survey of India map for region and county lines, and labels ──
1531
1532    /// An Overture boundary of `subtype` along `coords` with `extra` props.
1533    fn overture_line(
1534        subtype: &str,
1535        coords: Vec<(f64, f64)>,
1536        extra: &[(&str, PropValue)],
1537    ) -> ProcessedFeature {
1538        let mut props = vec![("subtype", PropValue::Str(subtype.into()))];
1539        props.extend(extra.iter().cloned());
1540        let mut feat = make_feature(&props);
1541        feat.geometry = Arc::new(geo::Geometry::LineString(geo::LineString::from(coords)));
1542        process(&feat).unwrap()
1543    }
1544
1545    fn country(code: &str) -> (&'static str, PropValue) {
1546        ("country", PropValue::Str(code.into()))
1547    }
1548
1549    fn has_key(feature: &ProcessedFeature, key: &str) -> bool {
1550        feature.properties.iter().any(|(k, _)| k == key)
1551    }
1552
1553    /// A Pakistani region line across India's land goes; the same line
1554    /// 50 degrees away stays; neither leaks the private owner mark.
1555    #[test]
1556    fn a_foreign_region_line_inside_india_is_dropped() {
1557        let mask = square_mask();
1558        let inside = overture_line("region", vec![(2.0, 2.0), (8.0, 8.0)], &[country("PK")]);
1559        assert!(mask.clip(inside).is_none());
1560        let far = overture_line("region", vec![(40.0, 40.0), (50.0, 50.0)], &[country("PK")]);
1561        let kept = mask.clip(far).unwrap();
1562        assert!(!has_key(&kept, crate::layers::OWNER_KEY));
1563        assert!((total_length(&kept) - 10.0 * 2f64.sqrt()).abs() < 1e-9);
1564    }
1565
1566    /// A line along the border stays: it is the neighbour's own border.
1567    #[test]
1568    fn a_foreign_line_along_the_border_stays() {
1569        let line = overture_line("region", vec![(10.0, 2.0), (10.0, 8.0)], &[country("PK")]);
1570        let kept = square_mask().clip(line).unwrap();
1571        assert!((total_length(&kept) - 6.0).abs() < 1e-6);
1572    }
1573
1574    /// An Indian line that carries a claim is a claim line inside India.
1575    #[test]
1576    fn a_claim_carrying_line_inside_india_is_dropped() {
1577        let mask = square_mask();
1578        let claim = overture_line(
1579            "county",
1580            vec![(2.0, 2.0), (8.0, 8.0)],
1581            &[country("IN"), ("is_disputed", PropValue::Bool(true))],
1582        );
1583        assert!(mask.clip(claim).is_none());
1584        let plain = overture_line("county", vec![(2.0, 2.0), (8.0, 8.0)], &[country("IN")]);
1585        let kept = mask.clip(plain).unwrap();
1586        assert!(!has_key(&kept, "disputed"));
1587        assert!((total_length(&kept) - 6.0 * 2f64.sqrt()).abs() < 1e-9);
1588    }
1589
1590    #[test]
1591    fn an_osm_line_of_an_admin_relation_of_another_country_is_foreign() {
1592        let mut tags = std::collections::HashMap::new();
1593        assert_eq!(relation_country(&tags), None);
1594        tags.insert("ISO3166-2".to_string(), "PK-GB".to_string());
1595        assert_eq!(relation_country(&tags).as_deref(), Some("PK"));
1596        tags.insert("ISO3166-1:alpha2".to_string(), "IN".to_string());
1597        assert_eq!(relation_country(&tags).as_deref(), Some("IN"));
1598    }
1599
1600    fn label(subtype: &str, props: &[(&str, &str)], at: (f64, f64)) -> ProcessedFeature {
1601        let mut all: Vec<(&str, PropValue)> = vec![
1602            ("subtype", PropValue::Str(subtype.into())),
1603            ("names.primary", PropValue::Str("X".into())),
1604        ];
1605        all.extend(props.iter().map(|(k, v)| (*k, PropValue::Str((*v).into()))));
1606        let mut feat = make_feature(&all);
1607        feat.geometry = Arc::new(geo::Geometry::Point(geo::Point::new(at.0, at.1)));
1608        crate::layers::places::process(&feat).unwrap()
1609    }
1610
1611    /// The labels of Overture's claim record, of a Pakistani division and
1612    /// of a Chinese prefecture are dropped on India's land; India's own
1613    /// state and county labels, and the same foreign labels outside it, stay.
1614    #[test]
1615    fn foreign_admin_labels_on_india_land_are_dropped() {
1616        let mask = square_mask();
1617        let at = (5.0, 5.0);
1618        let claim = label("region", &[("country", "IN")], at);
1619        let tibet = label("region", &[("country", "CN"), ("region", "CN-XZ")], at);
1620        let division = label("county", &[("country", "PK"), ("region", "PK-GB")], at);
1621        let pakistan = label("country", &[("country", "PK")], at);
1622        for (name, feature) in [
1623            ("claim region", claim),
1624            ("Chinese region", tibet),
1625            ("Pakistani division", division),
1626            ("Pakistan", pakistan),
1627        ] {
1628            assert!(mask.clip(feature).is_none(), "{name}");
1629        }
1630        let state = label("region", &[("country", "IN"), ("region", "IN-AR")], at);
1631        let county = label("county", &[("country", "IN"), ("region", "IN-AR")], at);
1632        let city = label("locality", &[("country", "PK")], at);
1633        for (name, feature) in [("state", state), ("county", county), ("city", city)] {
1634            let kept = mask.clip(feature).unwrap_or_else(|| panic!("{name} stays"));
1635            assert!(!has_key(&kept, crate::layers::OWNER_KEY), "{name}");
1636        }
1637        let outside = label(
1638            "region",
1639            &[("country", "PK"), ("region", "PK-GB")],
1640            (40.0, 40.0),
1641        );
1642        assert!(
1643            mask.clip(outside).is_some(),
1644            "outside India nothing changes"
1645        );
1646    }
1647
1648    /// With no mask the private mark still never reaches a tile.
1649    #[test]
1650    fn the_owner_mark_is_stripped_without_a_mask() {
1651        let foreign = overture_line("region", vec![(2.0, 2.0), (8.0, 8.0)], &[country("PK")]);
1652        assert!(has_key(&foreign, crate::layers::OWNER_KEY));
1653        let (clean, was_foreign) = crate::layers::take_owner(foreign);
1654        assert!(was_foreign);
1655        assert!(!has_key(&clean, crate::layers::OWNER_KEY));
1656    }
1657
1658    // ─── claim-marked lines inside India ───────────────────────────────
1659
1660    /// A boundaries feature of `kind` along `coords`, with `extra` properties
1661    /// and the owner mark when `foreign`.
1662    fn admin_line(
1663        kind: &str,
1664        coords: Vec<(f64, f64)>,
1665        extra: &[(&str, PropValue)],
1666        foreign: bool,
1667    ) -> ProcessedFeature {
1668        let mut properties: Vec<(String, PropValue)> = vec![
1669            ("kind".into(), PropValue::Str(kind.into())),
1670            ("kind_detail".into(), PropValue::I64(4)),
1671        ];
1672        for (k, v) in extra {
1673            properties.push(((*k).into(), v.clone()));
1674        }
1675        if foreign {
1676            mark_foreign(&mut properties);
1677        }
1678        ProcessedFeature {
1679            id: 1,
1680            geometry: Arc::new(geo::Geometry::LineString(geo::LineString::from(coords))),
1681            layer: Layer::Boundaries,
1682            min_zoom: 0,
1683            max_zoom: 15,
1684            sort_rank: 288,
1685            properties,
1686        }
1687    }
1688
1689    /// A vertical line `x` degrees east of the west edge of the square mask.
1690    fn vertical(
1691        kind: &str,
1692        x: f64,
1693        extra: &[(&str, PropValue)],
1694        foreign: bool,
1695    ) -> ProcessedFeature {
1696        admin_line(kind, vec![(x, 2.0), (x, 8.0)], extra, foreign)
1697    }
1698
1699    const CLAIM_MARKERS: [&str; 3] = ["disputed", "disputed_by", "claimed_by"];
1700
1701    fn marker(name: &str) -> (&'static str, PropValue) {
1702        match name {
1703            "disputed" => ("disputed", PropValue::Bool(true)),
1704            "disputed_by" => ("disputed_by", PropValue::Str("PK".into())),
1705            _ => ("claimed_by", PropValue::Str("CN".into())),
1706        }
1707    }
1708
1709    /// The owner's rule: no claim line inside India, whatever the kind and
1710    /// whatever the marker. A claim-marked line 0.01 deg inside the edge (the
1711    /// band the other rules keep) used to survive as a second border next to
1712    /// the Survey of India line.
1713    #[test]
1714    fn a_claim_marked_line_in_the_band_inside_india_is_dropped_for_every_kind_and_marker() {
1715        let mask = square_mask();
1716        for kind in ["country", "region", "county", "locality"] {
1717            for name in CLAIM_MARKERS {
1718                for foreign in [false, true] {
1719                    let (key, value) = marker(name);
1720                    let line = vertical(kind, 0.01, &[(key, value)], foreign);
1721                    assert!(
1722                        mask.clip(line).is_none(),
1723                        "{kind} with {name} (foreign={foreign}) at 0.01 deg inside survives"
1724                    );
1725                }
1726            }
1727        }
1728    }
1729
1730    /// A claim-marked line that weaves along the edge from the outside must not
1731    /// leave dashes hugging the border: the outward band is 0.02 deg too.
1732    #[test]
1733    fn a_claim_marked_line_within_the_margin_outside_india_is_dropped_too() {
1734        let mask = square_mask();
1735        for kind in ["country", "region", "county", "locality"] {
1736            for x in [-0.001, -0.015, -0.019] {
1737                let line = vertical(kind, x, &[marker("disputed_by")], true);
1738                assert!(mask.clip(line).is_none(), "{kind} at {x}");
1739            }
1740            let line = vertical(kind, -0.03, &[marker("disputed_by")], true);
1741            let kept = mask
1742                .clip(line)
1743                .expect("a claim line 0.03 deg outside stays");
1744            assert!((total_length(&kept) - 6.0).abs() < 1e-9, "{kind}");
1745        }
1746    }
1747
1748    /// Deep inside India the same rule holds, and a claim line that crosses the
1749    /// edge keeps only its part outside the outward band.
1750    #[test]
1751    fn a_claim_marked_line_crossing_the_edge_keeps_only_the_part_beyond_the_outward_band() {
1752        let mask = square_mask();
1753        let line = admin_line(
1754            "region",
1755            vec![(-5.0, 5.0), (15.0, 5.0)],
1756            &[marker("claimed_by")],
1757            true,
1758        );
1759        let kept = mask.clip(line).expect("the outside parts stay");
1760        let expected = 2.0 * (5.0 - CLAIM_MARGIN_DEG);
1761        assert!(
1762            (total_length(&kept) - expected).abs() < 1e-6,
1763            "{}",
1764            total_length(&kept)
1765        );
1766    }
1767
1768    /// Unclaimed lines keep today's behaviour: an unmarked line stays whole, a
1769    /// foreign unclaimed line keeps its part in the 0.02 band (avoids confetti
1770    /// along a border both sources agree on) and loses what is deeper.
1771    #[test]
1772    fn unclaimed_lines_keep_the_band_rule() {
1773        let mask = square_mask();
1774        let unmarked = vertical("region", 0.01, &[], false);
1775        let kept = mask.clip(unmarked.clone()).expect("unmarked stays");
1776        assert!(Arc::ptr_eq(&kept.geometry, &unmarked.geometry));
1777
1778        let foreign_band = vertical("region", 0.01, &[], true);
1779        let kept = mask
1780            .clip(foreign_band)
1781            .expect("a foreign line in the band stays");
1782        assert!((total_length(&kept) - 6.0).abs() < 1e-9);
1783
1784        let foreign_deep = vertical("region", 0.03, &[], true);
1785        assert!(
1786            mask.clip(foreign_deep).is_none(),
1787            "a foreign line deeper than the band goes"
1788        );
1789    }
1790
1791    /// The lines between Indian divisions carry no claim marker, from either
1792    /// source, so the claim rule never touches them.
1793    #[test]
1794    fn a_line_between_indian_divisions_carries_no_claim_marker_and_stays_whole() {
1795        let mask = square_mask();
1796        let inside = Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
1797            (2.0, 2.0),
1798            (8.0, 8.0),
1799        ])));
1800
1801        let mut overture = make_feature(&[
1802            ("subtype", PropValue::Str("region".into())),
1803            ("country", PropValue::Str("IN".into())),
1804        ]);
1805        overture.geometry = inside.clone();
1806        let overture = process(&overture).expect("an Indian region line");
1807        assert!(!carries_claim(&overture), "{:?}", overture.properties);
1808        let kept = mask.clip(overture.clone()).expect("stays");
1809        assert!(Arc::ptr_eq(&kept.geometry, &overture.geometry));
1810
1811        let mut way = make_osm_way(
1812            &[],
1813            vec![
1814                rel_with(
1815                    Some(4),
1816                    false,
1817                    &[("type", "boundary"), ("ISO3166-2", "IN-MH")],
1818                ),
1819                rel_with(
1820                    Some(4),
1821                    false,
1822                    &[("type", "boundary"), ("ISO3166-2", "IN-GJ")],
1823                ),
1824            ],
1825        );
1826        way.geometry = inside;
1827        let way = process(&way).expect("a line between two Indian states");
1828        assert!(!carries_claim(&way), "{:?}", way.properties);
1829        let (unmarked, foreign) = take_owner(way.clone());
1830        assert!(!foreign, "a line of two Indian relations is not foreign");
1831        let kept = mask.clip(way).expect("stays");
1832        assert!(Arc::ptr_eq(&kept.geometry, &unmarked.geometry) || total_length(&kept) > 8.0);
1833    }
1834
1835    /// An OSM way without a relation used to lose `disputed_by` and
1836    /// `claimed_by` (only the relation branch copied them), so the claim rule
1837    /// could not see it.
1838    #[test]
1839    fn a_way_without_a_relation_keeps_its_claim_tags() {
1840        let way = make_osm_way(
1841            &[
1842                ("boundary", PropValue::Str("administrative".into())),
1843                ("admin_level", PropValue::Str("4".into())),
1844                ("disputed_by", PropValue::Str("PK".into())),
1845                ("claimed_by", PropValue::Str("CN".into())),
1846            ],
1847            vec![],
1848        );
1849        let result = process(&way).expect("a region line");
1850        assert!(carries_claim(&result));
1851        assert!(
1852            result
1853                .properties
1854                .iter()
1855                .any(|(k, v)| k == "disputed_by" && *v == PropValue::Str("PK".into()))
1856        );
1857        assert!(
1858            result
1859                .properties
1860                .iter()
1861                .any(|(k, v)| k == "claimed_by" && *v == PropValue::Str("CN".into()))
1862        );
1863    }
1864}