Skip to main content

geolith_tiles_builder/layers/
roads.rs

1//! Roads layer — highways, streets, paths, rail, ferries.
2//!
3//! Processes features from multiple data sources:
4//! - **OSM**: 15+ highway classes with bridge/tunnel/oneway/ref attributes
5//! - **Overture**: `transportation/segment` features, classified by `subtype`
6//!   (`road`, `rail`, `water`) and split where bridge/tunnel/link flags cover
7//!   only part of a segment. Mirrors protomaps `Roads.processOverture`.
8
9use std::sync::Arc;
10
11use geo::{Coord, Euclidean, Length, LineString};
12
13use geolith::names::push_names;
14
15use crate::layers::Layer;
16use crate::source::input::{DataSource, InputFeature};
17use crate::tile::feature::PropValue;
18
19use super::buildings::ProcessedFeature;
20
21/// Most concurrent route shields on one road, as protomaps
22/// `CartographicLocale.MAX_SHIELDS`.
23const MAX_SHIELDS: usize = 6;
24
25/// Route network prefixes by shield priority, most important tier first;
26/// the first matching prefix wins. The US and NL tiers are the protomaps
27/// `locales/US.java` and `locales/NL.java` `NETWORK_PRIORITY` lists; `BAB`
28/// (the German Autobahn) sits with the other national motorway networks.
29const NETWORK_PRIORITY: [&[&str]; 3] = [
30    &["US:I", "NL:A", "BAB"],
31    &["US:US", "NL:N"],
32    &["US:", "NL:S-road"],
33];
34
35/// International networks, ranked after every national and regional one:
36/// a road's own country numbers it first, its E-road number second.
37const INTERNATIONAL_NETWORKS: [&str; 2] = ["e-road", "AsianHighway"];
38
39/// One route shield: the route's `ref` with white space removed, and its
40/// network.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub(crate) struct Shield {
43    pub(crate) text: String,
44    pub(crate) network: String,
45}
46
47/// The network a shield is drawn and ranked with, as protomaps
48/// `normalizeNetwork`: US carriageway variants (`US:I:Express`) collapse
49/// onto their route and every NL city ring (`NL:S:Amsterdam`) onto
50/// `NL:S-road`.
51fn normalize_network(network: &str) -> String {
52    if network.starts_with("NL:S:") {
53        return "NL:S-road".into();
54    }
55    if network.starts_with("US:") {
56        for suffix in [":Local", ":Express"] {
57            if let Some(base) = network.strip_suffix(suffix) {
58                return base.into();
59            }
60        }
61    }
62    network.into()
63}
64
65/// Shield priority of a network; lower sorts first.
66fn network_rank(network: &str) -> usize {
67    if INTERNATIONAL_NETWORKS.contains(&network) {
68        return NETWORK_PRIORITY.len() + 1;
69    }
70    NETWORK_PRIORITY
71        .iter()
72        .position(|tier| tier.iter().any(|p| network.starts_with(p)))
73        .unwrap_or(NETWORK_PRIORITY.len())
74}
75
76/// The road's route shields, primary first.
77///
78/// Like protomaps (`Roads.preprocessOsmRelation` keeps `type=route` +
79/// `route=road` relations; `CartographicLocale.orderShields` drops shields
80/// without text, de-duplicates and caps them), only road routes with a
81/// network and a ref count, so bus and coach lines (Flixbus, VBB) never
82/// give a road its shield. Shields sort by network rank, then text, then
83/// network: a pure function of the relations, whatever their order.
84pub(crate) fn route_shields(relations: &[crate::source::input::RelationInfo]) -> Vec<Shield> {
85    let mut shields: Vec<Shield> = relations
86        .iter()
87        .filter(|r| {
88            r.tags.get("type").is_some_and(|t| t == "route")
89                && r.tags.get("route").is_some_and(|t| t == "road")
90        })
91        .filter_map(|r| {
92            let network = normalize_network(r.tags.get("network")?);
93            let text: String = r
94                .tags
95                .get("ref")?
96                .chars()
97                .filter(|c| !c.is_whitespace())
98                .collect();
99            (!text.is_empty()).then_some(Shield { text, network })
100        })
101        .collect();
102    shields.sort_by(|a, b| {
103        (network_rank(&a.network), &a.text, &a.network).cmp(&(
104            network_rank(&b.network),
105            &b.text,
106            &b.network,
107        ))
108    });
109    shields.dedup();
110    shields.truncate(MAX_SHIELDS);
111    shields
112}
113
114/// The `network_N` / `shield_text_N` property keys, indexed by `N - 1`, so the
115/// hot loop never builds a key with `format!` (rust-skills
116/// `mem-avoid-format`).
117const SHIELD_KEYS: [(&str, &str); MAX_SHIELDS] = [
118    ("network_1", "shield_text_1"),
119    ("network_2", "shield_text_2"),
120    ("network_3", "shield_text_3"),
121    ("network_4", "shield_text_4"),
122    ("network_5", "shield_text_5"),
123    ("network_6", "shield_text_6"),
124];
125
126/// Emit `network_N` / `shield_text_N` for every shield and the singular
127/// `network` / `shield_text` for the primary one, as protomaps
128/// `Roads.processOsmHighways` does.
129fn push_shields(properties: &mut Vec<(String, PropValue)>, shields: &[Shield]) {
130    for (s, (network_key, text_key)) in shields.iter().zip(SHIELD_KEYS) {
131        properties.push((network_key.into(), PropValue::Str(s.network.clone())));
132        properties.push((text_key.into(), PropValue::Str(s.text.clone())));
133    }
134    if let Some(primary) = shields.first() {
135        properties.push(("network".into(), PropValue::Str(primary.network.clone())));
136        properties.push(("shield_text".into(), PropValue::Str(primary.text.clone())));
137    }
138}
139
140/// Flags the style reads, in the order they are emitted.
141const SEGMENT_FLAGS: [&str; 3] = ["is_bridge", "is_tunnel", "is_link"];
142
143/// The property keys each [`SEGMENT_FLAGS`] entry is stored under, in the same
144/// order: the reader writes every flag to both `road_flags.<flag>` and
145/// `rail_flags.<flag>`, and a precomputed key keeps the hot loop free of
146/// `format!` (rust-skills `mem-avoid-format`).
147const SEGMENT_FLAG_KEYS: [[&str; 2]; 3] = [
148    ["road_flags.is_bridge", "rail_flags.is_bridge"],
149    ["road_flags.is_tunnel", "rail_flags.is_tunnel"],
150    ["road_flags.is_link", "rail_flags.is_link"],
151];
152
153/// Process a feature into a roads layer feature.
154///
155/// Routes to the appropriate handler based on data source. For Overture
156/// segments this returns the whole segment with only the flags that cover
157/// all of it; [`process_all`] also emits the partially flagged pieces.
158pub fn process(feature: &InputFeature) -> Option<ProcessedFeature> {
159    match &feature.source {
160        DataSource::Overture { .. } => {
161            let class = classify_overture(feature)?;
162            let whole = segment_flags(feature, 0.0, 1.0, true);
163            Some(overture_feature(
164                feature,
165                &class,
166                feature.geometry.clone(),
167                whole,
168            ))
169        }
170        DataSource::Osm { .. } => process_osm(feature),
171        _ => None,
172    }
173}
174
175/// Process a feature and return every roads-layer feature it produces.
176///
177/// An Overture segment whose flag rules cover only a fraction of the line
178/// (Overture `between`) is split at those fractions, so a bridge is drawn
179/// only where the bridge is. Every other feature yields at most one result.
180#[must_use]
181pub fn process_all(feature: &InputFeature) -> Vec<ProcessedFeature> {
182    if !matches!(feature.source, DataSource::Overture { .. }) {
183        return process(feature).into_iter().collect();
184    }
185    let Some(class) = classify_overture(feature) else {
186        return Vec::new();
187    };
188    let cuts = flag_cuts(feature);
189    let line = match feature.geometry.as_ref() {
190        geo::Geometry::LineString(line) if !cuts.is_empty() => line,
191        _ => return process(feature).into_iter().collect(),
192    };
193
194    let mut bounds = Vec::with_capacity(cuts.len() + 2);
195    bounds.push(0.0);
196    bounds.extend_from_slice(&cuts);
197    bounds.push(1.0);
198
199    let mut out = Vec::with_capacity(bounds.len() - 1);
200    for pair in bounds.windows(2) {
201        let (start, end) = (pair[0], pair[1]);
202        let Some(piece) = sub_line(line, start, end) else {
203            continue;
204        };
205        let flags = segment_flags(feature, start, end, false);
206        let geometry = Arc::new(geo::Geometry::LineString(piece));
207        out.push(overture_feature(feature, &class, geometry, flags));
208    }
209    out
210}
211
212/// Overture segment classification: (kind, `kind_detail`, `min_zoom`).
213struct OvertureClass {
214    kind: &'static str,
215    kind_detail: Option<String>,
216    min_zoom: u8,
217}
218
219/// Classify an Overture `transportation/segment` by `subtype`.
220///
221/// - `road`: `class` through [`classify_highway`]; `kind_detail` is the
222///   `subclass` when present, else the class.
223/// - `rail`: `kind = rail`, `kind_detail = class`; `standard_gauge` from z11,
224///   every other rail class from z14.
225/// - `water`: `kind = ferry` from z11.
226///
227/// A segment without `subtype` is treated as a road.
228fn classify_overture(feature: &InputFeature) -> Option<OvertureClass> {
229    match feature.get_str("subtype") {
230        Some("rail") => {
231            let class = feature.get_str("class").unwrap_or("unknown");
232            let min_zoom = if class == "standard_gauge" { 11 } else { 14 };
233            Some(OvertureClass {
234                kind: "rail",
235                kind_detail: Some(class.to_string()),
236                min_zoom,
237            })
238        }
239        Some("water") => Some(OvertureClass {
240            kind: "ferry",
241            kind_detail: None,
242            min_zoom: 11,
243        }),
244        Some("road") | None => {
245            let class = feature.get_str("class").unwrap_or("unknown");
246            let (kind, min_zoom) = classify_highway(class);
247            let detail = feature.get_str("subclass").unwrap_or(class);
248            Some(OvertureClass {
249                kind,
250                kind_detail: Some(detail.to_string()),
251                min_zoom,
252            })
253        }
254        Some(_) => None,
255    }
256}
257
258/// Parse the ranges of one flag from its two [`SEGMENT_FLAG_KEYS`] property
259/// keys.
260///
261/// The reader stores each flag as `start:end` ranges joined by `;`.
262fn flag_ranges(feature: &InputFeature, keys: [&str; 2]) -> Vec<(f64, f64)> {
263    keys.into_iter()
264        .filter_map(|key| feature.get_str(key))
265        .flat_map(|s| s.split(';'))
266        .filter_map(|r| {
267            let (a, b) = r.split_once(':')?;
268            Some((a.parse().ok()?, b.parse().ok()?))
269        })
270        .collect()
271}
272
273/// Sorted, de-duplicated range endpoints strictly inside (0, 1).
274fn flag_cuts(feature: &InputFeature) -> Vec<f64> {
275    let mut cuts: Vec<f64> = SEGMENT_FLAG_KEYS
276        .into_iter()
277        .flat_map(|keys| flag_ranges(feature, keys))
278        .flat_map(|(a, b)| [a, b])
279        .filter(|v| *v > 1e-9 && *v < 1.0 - 1e-9)
280        .collect();
281    cuts.sort_by(f64::total_cmp);
282    cuts.dedup_by(|a, b| (*a - *b).abs() < 1e-9);
283    cuts
284}
285
286/// Flags active on the `[start, end]` piece of the segment.
287///
288/// With `whole_only`, a flag counts only if one of its ranges covers the
289/// entire piece; otherwise any positive overlap counts. `subclass = link`
290/// always sets `is_link`.
291fn segment_flags(feature: &InputFeature, start: f64, end: f64, whole_only: bool) -> [bool; 3] {
292    let mut out = [false; 3];
293    for (slot, keys) in out.iter_mut().zip(SEGMENT_FLAG_KEYS) {
294        *slot = flag_ranges(feature, keys).iter().any(|&(a, b)| {
295            if whole_only {
296                a <= start + 1e-9 && b >= end - 1e-9
297            } else {
298                a < end - 1e-9 && b > start + 1e-9
299            }
300        });
301    }
302    if feature.get_str("subclass") == Some("link") {
303        out[2] = true;
304    }
305    out
306}
307
308/// The part of `line` between length fractions `start` and `end`.
309///
310/// Fractions are of planar length in the line's own coordinates, as in
311/// protomaps `Linear.splitAtFractions`. Returns `None` for a zero-length
312/// line or a degenerate piece.
313fn sub_line(line: &LineString<f64>, start: f64, end: f64) -> Option<LineString<f64>> {
314    let total = Euclidean.length(line);
315    if total <= 0.0 || end - start <= 1e-12 {
316        return None;
317    }
318    let (from, to) = (start * total, end * total);
319    let mut coords: Vec<Coord<f64>> = Vec::with_capacity(line.0.len());
320    let mut walked = 0.0;
321    for seg in line.lines() {
322        let len = (seg.dx().powi(2) + seg.dy().powi(2)).sqrt();
323        let (seg_from, seg_to) = (walked, walked + len);
324        if len > 0.0 && seg_to > from && seg_from < to {
325            let at = |d: f64| {
326                let t = ((d - seg_from) / len).clamp(0.0, 1.0);
327                Coord {
328                    x: seg.start.x + seg.dx() * t,
329                    y: seg.start.y + seg.dy() * t,
330                }
331            };
332            if coords.is_empty() {
333                coords.push(at(from.max(seg_from)));
334            }
335            coords.push(at(to.min(seg_to)));
336        }
337        walked = seg_to;
338    }
339    (coords.len() >= 2).then(|| LineString::new(coords))
340}
341
342/// Build a roads-layer feature for an Overture segment (or piece of one).
343fn overture_feature(
344    feature: &InputFeature,
345    class: &OvertureClass,
346    geometry: Arc<geo::Geometry<f64>>,
347    flags: [bool; 3],
348) -> ProcessedFeature {
349    let mut properties = Vec::with_capacity(8);
350    properties.push(("kind".into(), PropValue::Str(class.kind.into())));
351    if let Some(detail) = &class.kind_detail {
352        properties.push(("kind_detail".into(), PropValue::Str(detail.clone())));
353    }
354    for (on, flag) in flags.into_iter().zip(SEGMENT_FLAGS) {
355        if on {
356            properties.push((flag.into(), PropValue::Bool(true)));
357        }
358    }
359    if let Some(r) = feature.get_str("road_ref").or(feature.get_str("ref")) {
360        properties.push(("ref".into(), PropValue::Str(r.to_string())));
361    }
362    push_names(feature, &mut properties);
363
364    properties.push(("sort_rank".into(), PropValue::I64(400)));
365    properties.push((
366        "min_zoom".into(),
367        PropValue::I64((class.min_zoom + 1) as i64),
368    ));
369
370    ProcessedFeature {
371        id: feature.id,
372        geometry,
373        layer: Layer::Roads,
374        min_zoom: class.min_zoom,
375        max_zoom: 15,
376        sort_rank: 400,
377        properties,
378    }
379}
380
381/// Process OSM highway features.
382fn process_osm(feature: &InputFeature) -> Option<ProcessedFeature> {
383    let highway = feature.get_str("highway")?;
384
385    if !feature.can_be_line() {
386        return None;
387    }
388
389    let (kind, min_zoom) = classify_highway(highway);
390
391    // _link suffix roads (e.g., motorway_link) get +2 min_zoom
392    let is_link = highway.ends_with("_link");
393    let adjusted_zoom = if is_link {
394        min_zoom.saturating_add(2)
395    } else {
396        min_zoom
397    };
398
399    // service roads with specific service tag get +1
400    let service_zoom = if highway == "service" {
401        match feature.get_str("service") {
402            Some("parking_aisle") | Some("driveway") => adjusted_zoom.saturating_add(1),
403            _ => adjusted_zoom,
404        }
405    } else {
406        adjusted_zoom
407    };
408
409    let mut properties = Vec::with_capacity(12);
410    properties.push(("kind".into(), PropValue::Str(kind.into())));
411    properties.push(("kind_detail".into(), PropValue::Str(highway.to_string())));
412
413    if feature.get_str("bridge").is_some_and(|v| v != "no") {
414        properties.push(("is_bridge".into(), PropValue::Bool(true)));
415    } else if feature.get_str("tunnel").is_some_and(|v| v != "no") {
416        properties.push(("is_tunnel".into(), PropValue::Bool(true)));
417    }
418    if feature.get_str("oneway").is_some_and(|v| v == "yes") {
419        properties.push(("oneway".into(), PropValue::Str("yes".into())));
420    }
421
422    // `ref` is the way's own tag, as protomaps `Roads.processOsmHighways`
423    // sets it; the route shields come from road route relations only.
424    if let Some(r) = feature.get_str("ref") {
425        properties.push(("ref".into(), PropValue::Str(r.to_string())));
426    }
427    push_shields(&mut properties, &route_shields(feature.osm_relations()));
428
429    push_names(feature, &mut properties);
430
431    if is_link {
432        properties.push(("is_link".into(), PropValue::Bool(true)));
433    }
434
435    properties.push(("sort_rank".into(), PropValue::I64(400)));
436    properties.push(("min_zoom".into(), PropValue::I64((service_zoom + 1) as i64)));
437
438    Some(ProcessedFeature {
439        id: feature.id,
440        geometry: feature.geometry.clone(),
441        layer: Layer::Roads,
442        min_zoom: service_zoom,
443        max_zoom: 15,
444        sort_rank: 400,
445        properties,
446    })
447}
448
449/// Classify a highway tag value into (kind, `min_zoom`).
450fn classify_highway(highway: &str) -> (&'static str, u8) {
451    let base = highway.trim_end_matches("_link");
452    match base {
453        "motorway" => ("highway", 3),
454        "trunk" => ("major_road", 6),
455        "primary" => ("major_road", 7),
456        "secondary" => ("major_road", 9),
457        "tertiary" => ("major_road", 9),
458        "residential" | "unclassified" | "road" | "raceway" => ("minor_road", 12),
459        "service" => ("minor_road", 13),
460        "pedestrian" | "track" | "corridor" => ("path", 12),
461        "path" | "cycleway" | "bridleway" | "footway" | "steps" => ("path", 13),
462        "living_street" => ("minor_road", 12),
463        _ => ("minor_road", 14),
464    }
465}
466
467#[cfg(test)]
468mod tests {
469    use super::*;
470    use crate::source::input::{DataSource, OsmElementType, RelationInfo};
471    use std::collections::HashMap;
472    use std::sync::Arc;
473
474    fn make_feature(props: &[(&str, PropValue)]) -> InputFeature {
475        let mut properties = HashMap::new();
476        for (k, v) in props {
477            properties.insert(k.to_string(), v.clone());
478        }
479        InputFeature {
480            id: 1,
481            geometry: Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
482                (0.0, 0.0),
483                (1.0, 1.0),
484            ]))),
485            properties,
486            bbox: None,
487            source: DataSource::Overture {
488                theme: String::new(),
489                otype: String::new(),
490            },
491        }
492    }
493
494    fn make_osm_line(tags: &[(&str, &str)]) -> InputFeature {
495        let mut properties = HashMap::new();
496        for (k, v) in tags {
497            properties.insert(k.to_string(), PropValue::Str(v.to_string()));
498        }
499        InputFeature {
500            id: 100,
501            geometry: Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
502                (0.0, 0.0),
503                (1.0, 1.0),
504            ]))),
505            properties,
506            bbox: None,
507            source: DataSource::Osm {
508                element_type: OsmElementType::Way,
509                relations: vec![],
510            },
511        }
512    }
513
514    fn make_osm_line_with_relations(
515        tags: &[(&str, &str)],
516        relations: Vec<RelationInfo>,
517    ) -> InputFeature {
518        let mut properties = HashMap::new();
519        for (k, v) in tags {
520            properties.insert(k.to_string(), PropValue::Str(v.to_string()));
521        }
522        InputFeature {
523            id: 100,
524            geometry: Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
525                (0.0, 0.0),
526                (1.0, 1.0),
527            ]))),
528            properties,
529            bbox: None,
530            source: DataSource::Osm {
531                element_type: OsmElementType::Way,
532                relations,
533            },
534        }
535    }
536
537    // --- Overture tests ---
538
539    #[test]
540    fn motorway_is_highway() {
541        let feat = make_feature(&[("class", PropValue::Str("motorway".into()))]);
542        let result = process(&feat).unwrap();
543        assert_eq!(result.layer, Layer::Roads);
544        assert_eq!(result.min_zoom, 3);
545        assert_eq!(result.sort_rank, 400);
546        assert!(
547            result
548                .properties
549                .iter()
550                .any(|(k, v)| k == "kind" && *v == PropValue::Str("highway".into()))
551        );
552    }
553
554    #[test]
555    fn primary_is_major_road() {
556        let feat = make_feature(&[("class", PropValue::Str("primary".into()))]);
557        let result = process(&feat).unwrap();
558        assert_eq!(result.min_zoom, 7);
559        assert!(
560            result
561                .properties
562                .iter()
563                .any(|(k, v)| k == "kind" && *v == PropValue::Str("major_road".into()))
564        );
565    }
566
567    #[test]
568    fn service_is_minor_road() {
569        let feat = make_feature(&[("class", PropValue::Str("service".into()))]);
570        let result = process(&feat).unwrap();
571        assert_eq!(result.min_zoom, 13);
572        assert!(
573            result
574                .properties
575                .iter()
576                .any(|(k, v)| k == "kind" && *v == PropValue::Str("minor_road".into()))
577        );
578    }
579
580    #[test]
581    fn footway_is_path() {
582        for class in ["path", "cycleway", "bridleway", "footway", "steps"] {
583            let feat = make_feature(&[("class", PropValue::Str(class.into()))]);
584            let result = process(&feat).expect(class);
585            assert_eq!(result.min_zoom, 13, "{class}");
586            assert!(
587                result
588                    .properties
589                    .iter()
590                    .any(|(k, v)| k == "kind" && *v == PropValue::Str("path".into())),
591                "{class}"
592            );
593        }
594    }
595
596    #[test]
597    fn bridge_property_extracted() {
598        let feat = make_feature(&[
599            ("class", PropValue::Str("motorway".into())),
600            ("road_flags.is_bridge", PropValue::Str("0:1".into())),
601        ]);
602        let result = process(&feat).unwrap();
603        assert!(
604            result
605                .properties
606                .iter()
607                .any(|(k, v)| k == "is_bridge" && *v == PropValue::Bool(true))
608        );
609    }
610
611    #[test]
612    fn overture_trunk_min_zoom_6() {
613        let feat = make_feature(&[("class", PropValue::Str("trunk".into()))]);
614        let result = process(&feat).unwrap();
615        assert_eq!(result.min_zoom, 6);
616    }
617
618    #[test]
619    fn overture_secondary_tertiary_min_zoom_9() {
620        for class in ["secondary", "tertiary"] {
621            let feat = make_feature(&[("class", PropValue::Str(class.into()))]);
622            let result = process(&feat).unwrap();
623            assert_eq!(result.min_zoom, 9, "class={class}");
624        }
625    }
626
627    #[test]
628    fn overture_residential_min_zoom_12() {
629        for class in ["residential", "unclassified", "road", "raceway"] {
630            let feat = make_feature(&[("class", PropValue::Str(class.into()))]);
631            let result = process(&feat).unwrap();
632            assert_eq!(result.min_zoom, 12, "class={class}");
633            assert!(
634                result
635                    .properties
636                    .iter()
637                    .any(|(k, v)| k == "kind" && *v == PropValue::Str("minor_road".into()))
638            );
639        }
640    }
641
642    #[test]
643    fn overture_living_street_min_zoom_12() {
644        let feat = make_feature(&[("class", PropValue::Str("living_street".into()))]);
645        let result = process(&feat).unwrap();
646        assert_eq!(result.min_zoom, 12);
647    }
648
649    #[test]
650    fn overture_pedestrian_track_corridor_path_min_zoom_12() {
651        for class in ["pedestrian", "track", "corridor"] {
652            let feat = make_feature(&[("class", PropValue::Str(class.into()))]);
653            let result = process(&feat).unwrap();
654            assert_eq!(result.min_zoom, 12, "class={class}");
655            assert!(
656                result
657                    .properties
658                    .iter()
659                    .any(|(k, v)| k == "kind" && *v == PropValue::Str("path".into()))
660            );
661        }
662    }
663
664    #[test]
665    fn overture_unknown_class_falls_through() {
666        // An unknown or a missing class is a minor road.
667        let weird = [("class", PropValue::Str("weird_class".into()))];
668        for props in [&weird[..], &[]] {
669            let result = process(&make_feature(props)).expect("a road");
670            assert_eq!(result.min_zoom, 14, "{props:?}");
671            assert!(
672                result
673                    .properties
674                    .iter()
675                    .any(|(k, v)| k == "kind" && *v == PropValue::Str("minor_road".into())),
676                "{props:?}"
677            );
678        }
679    }
680
681    fn prop<'a>(result: &'a ProcessedFeature, key: &str) -> Option<&'a PropValue> {
682        result
683            .properties
684            .iter()
685            .find(|(k, _)| k == key)
686            .map(|(_, v)| v)
687    }
688
689    fn s(v: &str) -> PropValue {
690        PropValue::Str(v.into())
691    }
692
693    /// A 10-unit straight line so length fractions map to x coordinates.
694    fn make_long_feature(props: &[(&str, PropValue)]) -> InputFeature {
695        let mut feat = make_feature(props);
696        feat.geometry = Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
697            (0.0, 0.0),
698            (4.0, 0.0),
699            (10.0, 0.0),
700        ])));
701        feat
702    }
703
704    fn x_span(result: &ProcessedFeature) -> (f64, f64) {
705        match result.geometry.as_ref() {
706            geo::Geometry::LineString(l) => (l.0[0].x, l.0[l.0.len() - 1].x),
707            other => panic!("expected a LineString, got {other:?}"),
708        }
709    }
710
711    /// Overture `subtype = rail` values from the 2026-08-19.0 release.
712    #[test]
713    fn overture_standard_gauge_rail_is_rail_from_z11() {
714        let feat = make_feature(&[("subtype", s("rail")), ("class", s("standard_gauge"))]);
715        let result = process(&feat).unwrap();
716        assert_eq!(prop(&result, "kind"), Some(&s("rail")));
717        assert_eq!(prop(&result, "kind_detail"), Some(&s("standard_gauge")));
718        assert_eq!(result.min_zoom, 11);
719    }
720
721    #[test]
722    fn overture_minor_rail_classes_are_rail_from_z14() {
723        for class in [
724            "subway",
725            "light_rail",
726            "tram",
727            "monorail",
728            "narrow_gauge",
729            "funicular",
730            "unknown",
731        ] {
732            let feat = make_feature(&[("subtype", s("rail")), ("class", s(class))]);
733            let result = process(&feat).unwrap();
734            assert_eq!(prop(&result, "kind"), Some(&s("rail")), "{class}");
735            assert_eq!(prop(&result, "kind_detail"), Some(&s(class)), "{class}");
736            assert_eq!(result.min_zoom, 14, "{class}");
737        }
738    }
739
740    #[test]
741    fn overture_water_segment_is_ferry_from_z11() {
742        let feat = make_feature(&[("subtype", s("water"))]);
743        let result = process(&feat).unwrap();
744        assert_eq!(prop(&result, "kind"), Some(&s("ferry")));
745        assert!(prop(&result, "kind_detail").is_none());
746        assert_eq!(result.min_zoom, 11);
747    }
748
749    #[test]
750    fn overture_unknown_subtype_is_dropped() {
751        let feat = make_feature(&[("subtype", s("hyperloop")), ("class", s("motorway"))]);
752        assert!(process(&feat).is_none());
753        assert!(process_all(&feat).is_empty());
754    }
755
756    #[test]
757    fn overture_subclass_becomes_kind_detail() {
758        let feat = make_feature(&[
759            ("subtype", s("road")),
760            ("class", s("footway")),
761            ("subclass", s("sidewalk")),
762        ]);
763        let result = process(&feat).unwrap();
764        assert_eq!(prop(&result, "kind"), Some(&s("path")));
765        assert_eq!(prop(&result, "kind_detail"), Some(&s("sidewalk")));
766    }
767
768    #[test]
769    fn overture_link_subclass_sets_is_link() {
770        let feat = make_feature(&[
771            ("subtype", s("road")),
772            ("class", s("primary")),
773            ("subclass", s("link")),
774        ]);
775        let result = process(&feat).unwrap();
776        assert_eq!(prop(&result, "is_link"), Some(&PropValue::Bool(true)));
777    }
778
779    #[test]
780    fn overture_whole_segment_flags_are_emitted() {
781        let feat = make_feature(&[
782            ("class", s("motorway")),
783            ("road_flags.is_bridge", s("0:1")),
784            ("road_flags.is_tunnel", s("0:1")),
785            ("road_flags.is_link", s("0:1")),
786        ]);
787        let result = process(&feat).unwrap();
788        for flag in ["is_bridge", "is_tunnel", "is_link"] {
789            assert_eq!(prop(&result, flag), Some(&PropValue::Bool(true)), "{flag}");
790        }
791        assert_eq!(process_all(&feat).len(), 1);
792    }
793
794    #[test]
795    fn overture_rail_flags_are_read() {
796        let feat = make_feature(&[
797            ("subtype", s("rail")),
798            ("class", s("subway")),
799            ("rail_flags.is_tunnel", s("0:1")),
800        ]);
801        let result = process(&feat).unwrap();
802        assert_eq!(prop(&result, "is_tunnel"), Some(&PropValue::Bool(true)));
803    }
804
805    /// Every segment flag is read from `road_flags` and from `rail_flags`: the
806    /// two precomputed key columns stay in step with [`SEGMENT_FLAGS`].
807    #[test]
808    fn segment_flags_are_read_from_both_overture_columns() {
809        for (key, property) in [
810            ("road_flags.is_bridge", "is_bridge"),
811            ("rail_flags.is_bridge", "is_bridge"),
812            ("road_flags.is_tunnel", "is_tunnel"),
813            ("rail_flags.is_tunnel", "is_tunnel"),
814            ("road_flags.is_link", "is_link"),
815            ("rail_flags.is_link", "is_link"),
816        ] {
817            let feat = make_feature(&[
818                ("subtype", s("road")),
819                ("class", s("primary")),
820                (key, s("0:1")),
821            ]);
822            let result = process(&feat).unwrap();
823            assert_eq!(
824                prop(&result, property),
825                Some(&PropValue::Bool(true)),
826                "{key}"
827            );
828        }
829    }
830
831    #[test]
832    fn overture_partial_bridge_is_not_on_the_whole_segment() {
833        let feat = make_long_feature(&[
834            ("class", s("primary")),
835            ("road_flags.is_bridge", s("0.2:0.5")),
836        ]);
837        let whole = process(&feat).unwrap();
838        assert!(prop(&whole, "is_bridge").is_none());
839    }
840
841    /// A bridge on 20%-50% of a 10-unit line: three pieces, and only the
842    /// middle one (x = 2..5) is a bridge.
843    #[test]
844    fn overture_partial_bridge_splits_the_segment() {
845        let feat = make_long_feature(&[
846            ("class", s("primary")),
847            ("road_flags.is_bridge", s("0.2:0.5")),
848        ]);
849        let pieces = process_all(&feat);
850        assert_eq!(pieces.len(), 3);
851
852        let bridge: Vec<_> = pieces
853            .iter()
854            .filter(|p| prop(p, "is_bridge").is_some())
855            .collect();
856        assert_eq!(bridge.len(), 1);
857        let (x0, x1) = x_span(bridge[0]);
858        assert!(
859            (x0 - 2.0).abs() < 1e-9 && (x1 - 5.0).abs() < 1e-9,
860            "{x0}..{x1}"
861        );
862
863        let total: f64 = pieces
864            .iter()
865            .map(|p| {
866                let (a, b) = x_span(p);
867                b - a
868            })
869            .sum();
870        assert!((total - 10.0).abs() < 1e-9, "pieces cover {total}");
871        for p in &pieces {
872            assert_eq!(prop(p, "kind"), Some(&s("major_road")));
873        }
874    }
875
876    /// A cut that falls between vertices keeps the interior vertex (4, 0).
877    #[test]
878    fn overture_split_piece_keeps_interior_vertices() {
879        let feat = make_long_feature(&[
880            ("class", s("primary")),
881            ("road_flags.is_tunnel", s("0.3:0.6")),
882        ]);
883        let tunnel = process_all(&feat)
884            .into_iter()
885            .find(|p| prop(p, "is_tunnel").is_some())
886            .unwrap();
887        match tunnel.geometry.as_ref() {
888            geo::Geometry::LineString(l) => {
889                let xs: Vec<f64> = l.0.iter().map(|c| c.x).collect();
890                assert_eq!(xs.len(), 3);
891                assert!((xs[1] - 4.0).abs() < 1e-9, "{xs:?}");
892            }
893            other => panic!("expected a LineString, got {other:?}"),
894        }
895    }
896
897    #[test]
898    fn overture_malformed_flag_ranges_are_ignored() {
899        let feat = make_long_feature(&[
900            ("class", s("primary")),
901            ("road_flags.is_bridge", s("nonsense;0.4")),
902        ]);
903        let pieces = process_all(&feat);
904        assert_eq!(pieces.len(), 1);
905        assert!(prop(&pieces[0], "is_bridge").is_none());
906    }
907
908    #[test]
909    fn overture_partial_flag_on_a_multilinestring_is_not_split() {
910        let mut feat = make_feature(&[
911            ("class", s("primary")),
912            ("road_flags.is_bridge", s("0.2:0.5")),
913        ]);
914        feat.geometry = Arc::new(geo::Geometry::MultiLineString(geo::MultiLineString::new(
915            vec![geo::LineString::from(vec![(0.0, 0.0), (1.0, 0.0)])],
916        )));
917        let pieces = process_all(&feat);
918        assert_eq!(pieces.len(), 1);
919        assert!(prop(&pieces[0], "is_bridge").is_none());
920    }
921
922    /// A degenerate zero-length segment has no piece to draw.
923    #[test]
924    fn overture_zero_length_segment_with_partial_flag_yields_nothing() {
925        let mut feat = make_feature(&[
926            ("class", s("primary")),
927            ("road_flags.is_bridge", s("0.2:0.5")),
928        ]);
929        feat.geometry = Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
930            (3.0, 3.0),
931            (3.0, 3.0),
932        ])));
933        assert!(process_all(&feat).is_empty());
934    }
935
936    #[test]
937    fn sub_line_of_zero_length_line_is_none() {
938        let line = geo::LineString::from(vec![(1.0, 1.0), (1.0, 1.0)]);
939        assert!(sub_line(&line, 0.0, 1.0).is_none());
940    }
941
942    #[test]
943    fn osm_process_all_matches_process() {
944        let feat = make_osm_line(&[("highway", "primary")]);
945        let all = process_all(&feat);
946        assert_eq!(all.len(), 1);
947        assert_eq!(prop(&all[0], "kind"), Some(&s("major_road")));
948    }
949    #[test]
950    fn overture_road_ref_extracted() {
951        let feat = make_feature(&[
952            ("class", PropValue::Str("motorway".into())),
953            ("road_ref", PropValue::Str("I-95".into())),
954        ]);
955        let result = process(&feat).unwrap();
956        assert!(
957            result
958                .properties
959                .iter()
960                .any(|(k, v)| k == "ref" && *v == PropValue::Str("I-95".into()))
961        );
962    }
963
964    #[test]
965    fn overture_falls_back_to_ref_field() {
966        let feat = make_feature(&[
967            ("class", PropValue::Str("motorway".into())),
968            ("ref", PropValue::Str("A1".into())),
969        ]);
970        let result = process(&feat).unwrap();
971        assert!(
972            result
973                .properties
974                .iter()
975                .any(|(k, v)| k == "ref" && *v == PropValue::Str("A1".into()))
976        );
977    }
978
979    #[test]
980    fn overture_names_primary_extracted() {
981        let feat = make_feature(&[
982            ("class", PropValue::Str("motorway".into())),
983            ("names.primary", PropValue::Str("Autobahn 5".into())),
984        ]);
985        let result = process(&feat).unwrap();
986        assert!(
987            result
988                .properties
989                .iter()
990                .any(|(k, v)| k == "name" && *v == PropValue::Str("Autobahn 5".into()))
991        );
992    }
993
994    fn has(r: &ProcessedFeature, key: &str, value: &str) -> bool {
995        r.properties
996            .iter()
997            .any(|(k, v)| k == key && *v == PropValue::Str(value.into()))
998    }
999
1000    #[test]
1001    fn osm_road_with_a_two_script_name_splits_it_and_keeps_name_en() {
1002        let r = process(&make_osm_line(&[
1003            ("highway", "primary"),
1004            ("name", "Rue Principale / شارع رئيسي"),
1005            ("name:en", "Main Street"),
1006        ]))
1007        .unwrap();
1008        assert!(has(&r, "name", "Rue Principale"));
1009        assert!(has(&r, "name2", "شارع رئيسي"));
1010        assert!(has(&r, "script2", "Arabic"));
1011        assert!(has(&r, "name:en", "Main Street"));
1012        assert!(r.properties.iter().all(|(k, _)| k != "script"));
1013    }
1014
1015    #[test]
1016    fn overture_road_takes_name_en_from_the_common_names() {
1017        let r = process(&make_feature(&[
1018            ("class", PropValue::Str("motorway".into())),
1019            ("names.primary", PropValue::Str("شارع النيل".into())),
1020            ("names.common.en", PropValue::Str("Nile Street".into())),
1021        ]))
1022        .unwrap();
1023        assert!(has(&r, "name", "شارع النيل"));
1024        assert!(has(&r, "script", "Arabic"));
1025        assert!(has(&r, "name:en", "Nile Street"));
1026    }
1027
1028    #[test]
1029    fn overture_falls_back_to_name_field() {
1030        let feat = make_feature(&[
1031            ("class", PropValue::Str("motorway".into())),
1032            ("name", PropValue::Str("Main St".into())),
1033        ]);
1034        let result = process(&feat).unwrap();
1035        assert!(
1036            result
1037                .properties
1038                .iter()
1039                .any(|(k, v)| k == "name" && *v == PropValue::Str("Main St".into()))
1040        );
1041    }
1042
1043    #[test]
1044    fn overture_min_zoom_property_set() {
1045        let feat = make_feature(&[("class", PropValue::Str("motorway".into()))]);
1046        let result = process(&feat).unwrap();
1047        // Property is min_zoom + 1 = 4
1048        assert!(
1049            result
1050                .properties
1051                .iter()
1052                .any(|(k, v)| k == "min_zoom" && *v == PropValue::I64(4))
1053        );
1054    }
1055
1056    // --- OSM tests ---
1057
1058    #[test]
1059    fn osm_motorway_basic() {
1060        let feat = make_osm_line(&[("highway", "motorway")]);
1061        let result = process(&feat).unwrap();
1062        assert_eq!(result.layer, Layer::Roads);
1063        assert_eq!(result.min_zoom, 3);
1064        assert!(
1065            result
1066                .properties
1067                .iter()
1068                .any(|(k, v)| k == "kind" && *v == PropValue::Str("highway".into()))
1069        );
1070    }
1071
1072    #[test]
1073    fn osm_no_highway_returns_none() {
1074        let feat = make_osm_line(&[("name", "Foo")]);
1075        assert!(process(&feat).is_none());
1076    }
1077
1078    #[test]
1079    fn osm_non_line_geometry_returns_none() {
1080        let mut props = HashMap::new();
1081        props.insert("highway".to_string(), PropValue::Str("motorway".into()));
1082        let feat = InputFeature {
1083            id: 1,
1084            geometry: Arc::new(geo::Geometry::Point(geo::Point::new(0.0, 0.0))),
1085            properties: props,
1086            bbox: None,
1087            source: DataSource::Osm {
1088                element_type: OsmElementType::Node,
1089                relations: vec![],
1090            },
1091        };
1092        assert!(process(&feat).is_none());
1093    }
1094
1095    #[test]
1096    fn osm_motorway_link_zoom_offset_plus_2() {
1097        let feat = make_osm_line(&[("highway", "motorway_link")]);
1098        let result = process(&feat).unwrap();
1099        // base 3 + 2 = 5
1100        assert_eq!(result.min_zoom, 5);
1101        assert!(
1102            result
1103                .properties
1104                .iter()
1105                .any(|(k, v)| k == "is_link" && *v == PropValue::Bool(true))
1106        );
1107    }
1108
1109    #[test]
1110    fn osm_service_driveway_zoom_plus_1() {
1111        // Driveways and parking aisles: base 13 + 1.
1112        for service in ["driveway", "parking_aisle"] {
1113            let feat = make_osm_line(&[("highway", "service"), ("service", service)]);
1114            assert_eq!(process(&feat).expect(service).min_zoom, 14, "{service}");
1115        }
1116    }
1117
1118    #[test]
1119    fn osm_service_other_no_offset() {
1120        // Neither an untagged service road nor an alley is pushed a zoom out.
1121        let alley = [("highway", "service"), ("service", "alley")];
1122        for tags in [&alley[..], &[("highway", "service")]] {
1123            assert_eq!(
1124                process(&make_osm_line(tags)).expect("a road").min_zoom,
1125                13,
1126                "{tags:?}"
1127            );
1128        }
1129    }
1130
1131    #[test]
1132    fn osm_bridge_no_skipped() {
1133        let feat = make_osm_line(&[("highway", "primary"), ("bridge", "no")]);
1134        let result = process(&feat).unwrap();
1135        assert!(!result.properties.iter().any(|(k, _)| k == "is_bridge"));
1136    }
1137
1138    #[test]
1139    fn osm_tunnel_extracted_when_no_bridge() {
1140        let feat = make_osm_line(&[("highway", "primary"), ("tunnel", "yes")]);
1141        let result = process(&feat).unwrap();
1142        assert!(
1143            result
1144                .properties
1145                .iter()
1146                .any(|(k, v)| k == "is_tunnel" && *v == PropValue::Bool(true))
1147        );
1148    }
1149
1150    #[test]
1151    fn osm_tunnel_no_skipped() {
1152        let feat = make_osm_line(&[("highway", "primary"), ("tunnel", "no")]);
1153        let result = process(&feat).unwrap();
1154        assert!(!result.properties.iter().any(|(k, _)| k == "is_tunnel"));
1155    }
1156
1157    #[test]
1158    fn osm_bridge_takes_priority_over_tunnel() {
1159        let bridge = [("highway", "primary"), ("bridge", "yes")];
1160        let both = [("highway", "primary"), ("bridge", "yes"), ("tunnel", "yes")];
1161        for tags in [&bridge[..], &both] {
1162            let result = process(&make_osm_line(tags)).expect("a road");
1163            assert!(
1164                result
1165                    .properties
1166                    .iter()
1167                    .any(|(k, v)| k == "is_bridge" && *v == PropValue::Bool(true)),
1168                "{tags:?}"
1169            );
1170            assert!(
1171                !result.properties.iter().any(|(k, _)| k == "is_tunnel"),
1172                "{tags:?}"
1173            );
1174        }
1175    }
1176
1177    #[test]
1178    fn osm_oneway_yes_extracted() {
1179        let feat = make_osm_line(&[("highway", "primary"), ("oneway", "yes")]);
1180        let result = process(&feat).unwrap();
1181        assert!(
1182            result
1183                .properties
1184                .iter()
1185                .any(|(k, v)| k == "oneway" && *v == PropValue::Str("yes".into()))
1186        );
1187    }
1188
1189    #[test]
1190    fn osm_oneway_no_skipped() {
1191        let feat = make_osm_line(&[("highway", "primary"), ("oneway", "no")]);
1192        let result = process(&feat).unwrap();
1193        assert!(!result.properties.iter().any(|(k, _)| k == "oneway"));
1194    }
1195
1196    #[test]
1197    fn osm_ref_from_direct_tag() {
1198        let feat = make_osm_line(&[("highway", "primary"), ("ref", "B12")]);
1199        let result = process(&feat).unwrap();
1200        assert!(
1201            result
1202                .properties
1203                .iter()
1204                .any(|(k, v)| k == "ref" && *v == PropValue::Str("B12".into()))
1205        );
1206    }
1207
1208    /// A relation with `id` and `tags`.
1209    fn relation(id: i64, tags: &[(&str, &str)]) -> RelationInfo {
1210        RelationInfo {
1211            id,
1212            admin_level: None,
1213            disputed: false,
1214            role: String::new(),
1215            tags: tags
1216                .iter()
1217                .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
1218                .collect(),
1219        }
1220    }
1221
1222    /// A `type=route` relation with `route`, `network` and `ref`.
1223    fn route(id: i64, route: &str, network: &str, reference: &str) -> RelationInfo {
1224        relation(
1225            id,
1226            &[
1227                ("type", "route"),
1228                ("route", route),
1229                ("network", network),
1230                ("ref", reference),
1231            ],
1232        )
1233    }
1234
1235    fn text(value: &str) -> Option<PropValue> {
1236        Some(PropValue::Str(value.into()))
1237    }
1238
1239    /// `ref` is the way's own tag (protomaps `Roads.java`
1240    /// `.setAttrWithMinzoom("ref", sf.getString("ref"), ...)`); the route
1241    /// relation gives the shield.
1242    #[test]
1243    fn osm_ref_is_the_way_tag_and_the_route_gives_the_shield() {
1244        let feat = make_osm_line_with_relations(
1245            &[("highway", "motorway"), ("ref", "I 90")],
1246            vec![route(1, "road", "US:I", "90")],
1247        );
1248        let result = process(&feat).unwrap();
1249        assert_eq!(prop(&result, "ref").cloned(), text("I 90"));
1250        assert_eq!(prop(&result, "network").cloned(), text("US:I"));
1251        assert_eq!(prop(&result, "shield_text").cloned(), text("90"));
1252        assert_eq!(prop(&result, "network_1").cloned(), text("US:I"));
1253        assert_eq!(prop(&result, "shield_text_1").cloned(), text("90"));
1254        assert!(prop(&result, "network_2").is_none());
1255    }
1256
1257    /// Way 81631742 (AVUS, `ref=A 115`, `int_ref=E 51`) in the Geofabrik
1258    /// Berlin extract of 2026-10 belongs to road routes 80053
1259    /// (`network=e-road`, `ref=E 51`) and 5485765 (`network=BAB`,
1260    /// `ref=A 115`), to route 1516377 (`route=road`, no network or ref), to
1261    /// Flixbus bus route 3046906 (`ref=009`), to Eurolines bus route 9581031
1262    /// (`ref=EU0328`) and to 3144678 (`type=route`, `network=Flixbus`,
1263    /// `ref=038`, `disused:route=bus`). The Autobahn number is the primary
1264    /// shield, then the E-road; no bus line becomes a shield, in any input
1265    /// order.
1266    #[test]
1267    fn the_autobahn_number_is_the_primary_shield_over_e_road_and_bus_routes() {
1268        let relations = vec![
1269            route(80053, "road", "e-road", "E 51"),
1270            relation(1_516_377, &[("type", "route"), ("route", "road")]),
1271            route(3_046_906, "bus", "Flixbus", "009"),
1272            relation(
1273                3_144_678,
1274                &[
1275                    ("type", "route"),
1276                    ("disused:route", "bus"),
1277                    ("network", "Flixbus"),
1278                    ("ref", "038"),
1279                ],
1280            ),
1281            route(5_485_765, "road", "BAB", "A 115"),
1282            route(9_581_031, "bus", "Eurolines", "EU0328"),
1283        ];
1284        let expected = vec![
1285            Shield {
1286                text: "A115".into(),
1287                network: "BAB".into(),
1288            },
1289            Shield {
1290                text: "E51".into(),
1291                network: "e-road".into(),
1292            },
1293        ];
1294        let mut reversed = relations.clone();
1295        reversed.reverse();
1296        assert_eq!(route_shields(&relations), expected);
1297        assert_eq!(route_shields(&reversed), expected);
1298
1299        let feat =
1300            make_osm_line_with_relations(&[("highway", "motorway"), ("ref", "A 115")], relations);
1301        let result = process(&feat).unwrap();
1302        assert_eq!(prop(&result, "ref").cloned(), text("A 115"));
1303        assert_eq!(prop(&result, "network").cloned(), text("BAB"));
1304        assert_eq!(prop(&result, "shield_text").cloned(), text("A115"));
1305        assert_eq!(prop(&result, "network_2").cloned(), text("e-road"));
1306        assert_eq!(prop(&result, "shield_text_2").cloned(), text("E51"));
1307        assert!(prop(&result, "network_3").is_none());
1308    }
1309
1310    /// Interstate before US highway before state route, as protomaps
1311    /// `locales/US.java`; a carriageway variant shares its route's shield and
1312    /// the forward and backward relations of one route give one shield.
1313    #[test]
1314    fn us_shields_follow_the_protomaps_us_priority() {
1315        let shields = route_shields(&[
1316            route(1, "road", "US:CA", "1"),
1317            route(2, "road", "US:US", "101"),
1318            route(3, "road", "US:I:Express", "5"),
1319            route(4, "road", "US:I", "5"),
1320        ]);
1321        let got: Vec<(&str, &str)> = shields
1322            .iter()
1323            .map(|s| (s.network.as_str(), s.text.as_str()))
1324            .collect();
1325        assert_eq!(got, [("US:I", "5"), ("US:US", "101"), ("US:CA", "1")]);
1326    }
1327
1328    /// NL A-road before N-road before a city ring, whose per-city network
1329    /// collapses onto `NL:S-road` as protomaps `locales/NL.java` does; equal
1330    /// ranks fall back to the shield text, and at most six shields remain.
1331    #[test]
1332    fn nl_shields_and_the_six_shield_cap() {
1333        let shields = route_shields(&[
1334            route(1, "road", "NL:S:Amsterdam", "S 100"),
1335            route(2, "road", "NL:N", "N 200"),
1336            route(3, "road", "NL:A", "A 10"),
1337            route(4, "road", "other", "Z9"),
1338            route(5, "road", "other", "B2"),
1339            route(6, "road", "e-road", "E 22"),
1340            route(7, "road", "other", "C3"),
1341        ]);
1342        let got: Vec<(&str, &str)> = shields
1343            .iter()
1344            .map(|s| (s.network.as_str(), s.text.as_str()))
1345            .collect();
1346        assert_eq!(
1347            got,
1348            [
1349                ("NL:A", "A10"),
1350                ("NL:N", "N200"),
1351                ("NL:S-road", "S100"),
1352                ("other", "B2"),
1353                ("other", "C3"),
1354                ("other", "Z9"),
1355            ]
1356        );
1357    }
1358
1359    /// A road route without a network or ref gives no shield, nor does a
1360    /// bus route that has both; the way keeps its own `ref`.
1361    #[test]
1362    fn routes_without_network_or_ref_and_bus_routes_give_no_shield() {
1363        let feat = make_osm_line_with_relations(
1364            &[("highway", "motorway"), ("ref", "E5")],
1365            vec![
1366                relation(1, &[("type", "route"), ("route", "road"), ("ref", "1")]),
1367                relation(2, &[("type", "route"), ("route", "road"), ("network", "x")]),
1368                route(3, "road", "x", " "),
1369                route(4, "bus", "Flixbus", "042"),
1370            ],
1371        );
1372        let result = process(&feat).unwrap();
1373        assert_eq!(prop(&result, "ref").cloned(), text("E5"));
1374        assert!(prop(&result, "network").is_none());
1375        assert!(prop(&result, "shield_text").is_none());
1376    }
1377
1378    #[test]
1379    fn osm_no_ref_or_network() {
1380        let feat = make_osm_line(&[("highway", "primary")]);
1381        let result = process(&feat).unwrap();
1382        assert!(!result.properties.iter().any(|(k, _)| k == "ref"));
1383        assert!(!result.properties.iter().any(|(k, _)| k == "network"));
1384    }
1385
1386    #[test]
1387    fn osm_name_extracted() {
1388        let feat = make_osm_line(&[("highway", "primary"), ("name", "Main Street")]);
1389        let result = process(&feat).unwrap();
1390        assert!(
1391            result
1392                .properties
1393                .iter()
1394                .any(|(k, v)| k == "name" && *v == PropValue::Str("Main Street".into()))
1395        );
1396    }
1397
1398    #[test]
1399    fn osm_residential_min_zoom_12() {
1400        let feat = make_osm_line(&[("highway", "residential")]);
1401        let result = process(&feat).unwrap();
1402        assert_eq!(result.min_zoom, 12);
1403    }
1404
1405    #[test]
1406    fn osm_link_strips_link_for_classify() {
1407        // primary_link → base classify of "primary" (zoom 7) + 2 = 9
1408        let feat = make_osm_line(&[("highway", "primary_link")]);
1409        let result = process(&feat).unwrap();
1410        assert_eq!(result.min_zoom, 9);
1411        assert!(
1412            result
1413                .properties
1414                .iter()
1415                .any(|(k, v)| k == "is_link" && *v == PropValue::Bool(true))
1416        );
1417    }
1418
1419    #[test]
1420    fn osm_unknown_highway_min_zoom_14() {
1421        let feat = make_osm_line(&[("highway", "weird_class")]);
1422        let result = process(&feat).unwrap();
1423        assert_eq!(result.min_zoom, 14);
1424    }
1425
1426    #[test]
1427    fn osm_min_zoom_property_set() {
1428        let feat = make_osm_line(&[("highway", "motorway")]);
1429        let result = process(&feat).unwrap();
1430        assert!(
1431            result
1432                .properties
1433                .iter()
1434                .any(|(k, v)| k == "min_zoom" && *v == PropValue::I64(4))
1435        );
1436    }
1437
1438    #[test]
1439    fn other_data_source_returns_none() {
1440        let feat = InputFeature {
1441            id: 1,
1442            geometry: Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
1443                (0.0, 0.0),
1444                (1.0, 1.0),
1445            ]))),
1446            properties: HashMap::new(),
1447            bbox: None,
1448            source: DataSource::LandPolygons,
1449        };
1450        assert!(process(&feat).is_none());
1451    }
1452}