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