Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / osm_ingest / src / select.rs
select.rs192 lines · 6.9 KiBRaw
| 1 | //! Generic tag matching: the `osmium tags-filter` equivalent. |
| 2 | //! |
| 3 | //! Each layer script narrows a PBF with an expression like |
| 4 | //! |
| 5 | //! ```text |
| 6 | //! osmium tags-filter n/highway=speed_camera,stop,traffic_signals \ |
| 7 | //! n/man_made=surveillance \ |
| 8 | //! n/enforcement=maxspeed |
| 9 | //! ``` |
| 10 | //! |
| 11 | //! [`Select`] is that expression: a set of `key=v1,v2` clauses, matching when |
| 12 | //! **any** of them does, which is what osmium's OR semantics mean. A clause with |
| 13 | //! no `=` matches on key presence alone (`w/maxspeed`). |
| 14 | //! |
| 15 | //! ## Why a lookup closure rather than a tag map |
| 16 | //! |
| 17 | //! [`Select::matches`] takes `impl Fn(&str) -> Option<&str>`, the shape |
| 18 | //! [`crate::osm::Tags::get_str`] already has. That means no map is built per |
| 19 | //! element on the hot path, and -- more usefully -- a selector can be unit-tested |
| 20 | //! against a plain array of pairs with no PBF anywhere in sight, exactly like the |
| 21 | //! classifiers in [`crate::tags`]. |
| 22 | //! |
| 23 | //! This is a pre-filter, not the layer's schema decision. It exists to skip the |
| 24 | //! overwhelming majority of elements cheaply; the per-layer classifier still has |
| 25 | //! the final say on what is emitted and as what. |
| 26 | |
| 27 | use crate::proto::{Error, Result}; |
| 28 | |
| 29 | /// One `key` or `key=v1,v2` clause. |
| 30 | #[derive(Debug, Clone, PartialEq)] |
| 31 | pub struct Clause { |
| 32 | pub key: String, |
| 33 | /// Empty means "any value", i.e. match on the key being present at all. |
| 34 | pub values: Vec<String>, |
| 35 | } |
| 36 | |
| 37 | impl Clause { |
| 38 | fn matches(&self, value: Option<&str>) -> bool { |
| 39 | match value { |
| 40 | None => false, |
| 41 | Some(v) => { |
| 42 | if self.values.is_empty() { |
| 43 | // osmium's bare `w/maxspeed` matches a present key whatever |
| 44 | // its value, including the empty string. |
| 45 | true |
| 46 | } else { |
| 47 | self.values.iter().any(|w| w == v) |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | #[derive(Debug, Clone, Default, PartialEq)] |
| 55 | pub struct Select { |
| 56 | pub clauses: Vec<Clause>, |
| 57 | } |
| 58 | |
| 59 | impl Select { |
| 60 | /// Parse one clause per element of `specs`, in the `key` or `key=v1,v2` form. |
| 61 | pub fn parse(specs: &[&str]) -> Result<Select> { |
| 62 | let mut clauses = Vec::with_capacity(specs.len()); |
| 63 | for spec in specs { |
| 64 | let spec = spec.trim(); |
| 65 | if spec.is_empty() { |
| 66 | return Err(Error("empty tag filter".into())); |
| 67 | } |
| 68 | let (key, values) = match spec.split_once('=') { |
| 69 | None => (spec.to_string(), Vec::new()), |
| 70 | Some((k, v)) => { |
| 71 | let k = k.trim(); |
| 72 | if k.is_empty() { |
| 73 | return Err(Error(format!("tag filter has no key: {spec}"))); |
| 74 | } |
| 75 | let values: Vec<String> = v |
| 76 | .split(',') |
| 77 | .map(str::trim) |
| 78 | .filter(|s| !s.is_empty()) |
| 79 | .map(str::to_string) |
| 80 | .collect(); |
| 81 | if values.is_empty() { |
| 82 | return Err(Error(format!("tag filter has no values: {spec}"))); |
| 83 | } |
| 84 | (k.to_string(), values) |
| 85 | } |
| 86 | }; |
| 87 | clauses.push(Clause { key, values }); |
| 88 | } |
| 89 | if clauses.is_empty() { |
| 90 | return Err(Error("a selector needs at least one tag filter".into())); |
| 91 | } |
| 92 | Ok(Select { clauses }) |
| 93 | } |
| 94 | |
| 95 | /// True when any clause matches. `get` is a tag lookup, e.g. |
| 96 | /// `|k| tags.get_str(k)`. |
| 97 | pub fn matches<'a, F>(&self, get: F) -> bool |
| 98 | where |
| 99 | F: Fn(&str) -> Option<&'a str>, |
| 100 | { |
| 101 | self.clauses.iter().any(|c| c.matches(get(&c.key))) |
| 102 | } |
| 103 | |
| 104 | /// Every key any clause mentions, deduplicated. Useful for a cheap |
| 105 | /// "does this element carry any interesting key at all" screen. |
| 106 | pub fn keys(&self) -> Vec<&str> { |
| 107 | let mut out: Vec<&str> = self.clauses.iter().map(|c| c.key.as_str()).collect(); |
| 108 | out.sort_unstable(); |
| 109 | out.dedup(); |
| 110 | out |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | #[cfg(test)] |
| 115 | mod tests { |
| 116 | use super::*; |
| 117 | |
| 118 | /// A tag lookup over a plain slice -- the point of the closure-based API is |
| 119 | /// that a test needs nothing more than this. |
| 120 | fn tags<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<&'a str> + 'a { |
| 121 | move |k| pairs.iter().find(|(pk, _)| *pk == k).map(|(_, v)| *v) |
| 122 | } |
| 123 | |
| 124 | #[test] |
| 125 | fn parses_the_osmium_clause_forms() { |
| 126 | let s = Select::parse(&[ |
| 127 | "highway=speed_camera,stop,traffic_signals", |
| 128 | "man_made=surveillance", |
| 129 | "maxspeed", |
| 130 | ]) |
| 131 | .unwrap(); |
| 132 | assert_eq!(s.clauses.len(), 3); |
| 133 | assert_eq!(s.clauses[0].key, "highway"); |
| 134 | assert_eq!(s.clauses[0].values, ["speed_camera", "stop", "traffic_signals"]); |
| 135 | // A bare key means "present, any value". |
| 136 | assert_eq!(s.clauses[2].key, "maxspeed"); |
| 137 | assert!(s.clauses[2].values.is_empty()); |
| 138 | } |
| 139 | |
| 140 | #[test] |
| 141 | fn tolerates_whitespace_and_trailing_commas() { |
| 142 | let s = Select::parse(&[" highway = rail, subway , "]).unwrap(); |
| 143 | assert_eq!(s.clauses[0].key, "highway"); |
| 144 | assert_eq!(s.clauses[0].values, ["rail", "subway"]); |
| 145 | } |
| 146 | |
| 147 | #[test] |
| 148 | fn rejects_nonsense() { |
| 149 | assert!(Select::parse(&[]).is_err()); |
| 150 | assert!(Select::parse(&[""]).is_err()); |
| 151 | assert!(Select::parse(&["=value"]).is_err()); |
| 152 | assert!(Select::parse(&["key="]).is_err()); |
| 153 | assert!(Select::parse(&["key=,,"]).is_err()); |
| 154 | } |
| 155 | |
| 156 | #[test] |
| 157 | fn clauses_are_ored_not_anded() { |
| 158 | let s = Select::parse(&["highway=speed_camera", "man_made=surveillance"]).unwrap(); |
| 159 | assert!(s.matches(tags(&[("highway", "speed_camera")]))); |
| 160 | assert!(s.matches(tags(&[("man_made", "surveillance")]))); |
| 161 | // Either alone is enough; neither is not. |
| 162 | assert!(!s.matches(tags(&[("highway", "residential")]))); |
| 163 | assert!(!s.matches(tags(&[]))); |
| 164 | } |
| 165 | |
| 166 | #[test] |
| 167 | fn a_bare_key_matches_any_value_including_empty() { |
| 168 | let s = Select::parse(&["maxspeed"]).unwrap(); |
| 169 | assert!(s.matches(tags(&[("maxspeed", "50")]))); |
| 170 | assert!(s.matches(tags(&[("maxspeed", "none")]))); |
| 171 | // Present but empty still counts as present, as in osmium. |
| 172 | assert!(s.matches(tags(&[("maxspeed", "")]))); |
| 173 | assert!(!s.matches(tags(&[("highway", "residential")]))); |
| 174 | } |
| 175 | |
| 176 | #[test] |
| 177 | fn value_matching_is_exact_not_substring() { |
| 178 | let s = Select::parse(&["railway=rail"]).unwrap(); |
| 179 | assert!(s.matches(tags(&[("railway", "rail")]))); |
| 180 | // `narrow_gauge` contains no "rail" substring issue, but `light_rail` |
| 181 | // does -- and must not match a `railway=rail` clause. |
| 182 | assert!(!s.matches(tags(&[("railway", "light_rail")]))); |
| 183 | assert!(!s.matches(tags(&[("railway", "railway")]))); |
| 184 | } |
| 185 | |
| 186 | #[test] |
| 187 | fn keys_are_deduplicated_and_sorted() { |
| 188 | let s = Select::parse(&["highway=stop", "man_made=surveillance", "highway=speed_camera"]) |
| 189 | .unwrap(); |
| 190 | assert_eq!(s.keys(), ["highway", "man_made"]); |
| 191 | } |
| 192 | } |