Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / scripts / maps / tile_build / src / geojson.rs

geojson.rs488 lines · 17.4 KiBRaw
1//! Reading the GeoJSONSeq the extractors emit.
2//!
3//! One `Feature` per line, with any of the six geometry types. Deliberately **not**
4//! a general GeoJSON parser and deliberately not serde: this crate's only
5//! dependency is `miniz_oxide`, which is what lets it resolve and build offline,
6//! and adding a JSON stack for a format we also write ourselves would throw that
7//! away.
8//!
9//! What that costs, stated plainly: nested objects inside `properties` are
10//! ignored, and so is any geometry the six types do not cover
11//! (`GeometryCollection`). Both are things our own writers never produce, and both
12//! are counted and reported rather than silently skipped.
13//!
14//! Key order is *not* assumed. The geometry object is located and its extent
15//! found by brace counting, then `type` and `coordinates` are looked up inside it,
16//! so `{"coordinates":...,"type":...}` reads the same as the other way round.
17
18use crate::geom::{Geometry, Pt};
19use crate::mvt::Value;
20
21/// One parsed feature: geometry in lon/lat, plus its flat properties.
22#[derive(Debug, Clone, PartialEq)]
23pub struct Feature {
24 pub geometry: Geometry,
25 pub props: Vec<(String, Value)>,
26}
27
28/// Parse one line. `None` when the line is not a feature we can use -- malformed,
29/// or a geometry type this reader does not cover.
30pub fn parse_feature(line: &str) -> Option<Feature> {
31 // Work on the object's body, so "top level" means depth 0 for both this call
32 // and the ones on the nested objects below.
33 let body = strip_outer_braces(line)?;
34 let geometry = find_object(body, "\"geometry\"")?;
35 let type_name = string_value(geometry, "\"type\"")?;
36 let coords_at = find_key(geometry, "\"coordinates\"")?;
37 let (coords, _) = parse_coords(&geometry[coords_at..])?;
38
39 let geometry = match type_name.as_str() {
40 "Point" => Geometry::Points(vec![coords.as_point()?]),
41 "MultiPoint" => Geometry::Points(coords.as_line()?),
42 "LineString" => Geometry::Lines(vec![coords.as_line()?]),
43 "MultiLineString" => Geometry::Lines(coords.as_lines()?),
44 "Polygon" => Geometry::Polygons(vec![coords.as_lines()?]),
45 "MultiPolygon" => Geometry::Polygons(coords.as_polygons()?),
46 _ => return None,
47 };
48
49 let props = match find_object(body, "\"properties\"") {
50 Some(p) => parse_props(p),
51 None => Vec::new(),
52 };
53 Some(Feature { geometry, props })
54}
55
56/// The contents of one enclosing `{...}`.
57fn strip_outer_braces(s: &str) -> Option<&str> {
58 let s = s.trim();
59 s.strip_prefix('{')?.strip_suffix('}')
60}
61
62/// The body of the object at `key`, without its braces. `hay` is an object *body*,
63/// so its own keys sit at depth 0.
64///
65/// Brace counting, ignoring braces inside strings, so a `properties` value that
66/// happens to contain `{` in a name does not truncate the object.
67fn find_object<'a>(hay: &'a str, key: &str) -> Option<&'a str> {
68 let at = find_key(hay, key)?;
69 let b = hay.as_bytes();
70 let mut i = at;
71 while i < b.len() && b[i] != b'{' {
72 // A non-object value for this key: not something we can read.
73 if b[i] == b'"' || b[i] == b'[' {
74 return None;
75 }
76 i += 1;
77 }
78 if i >= b.len() {
79 return None;
80 }
81 let start = i + 1;
82 let mut depth = 0usize;
83 let mut in_str = false;
84 while i < b.len() {
85 match b[i] {
86 b'\\' if in_str => i += 1,
87 b'"' => in_str = !in_str,
88 b'{' if !in_str => depth += 1,
89 b'}' if !in_str => {
90 depth -= 1;
91 if depth == 0 {
92 return Some(&hay[start..i]);
93 }
94 }
95 _ => {}
96 }
97 i += 1;
98 }
99 None
100}
101
102/// Byte offset just past `key":` at the top nesting level of `hay`.
103fn find_key(hay: &str, key: &str) -> Option<usize> {
104 let b = hay.as_bytes();
105 let k = key.as_bytes();
106 let mut i = 0usize;
107 let mut depth = 0i32;
108 let mut in_str = false;
109 while i < b.len() {
110 match b[i] {
111 b'\\' if in_str => {
112 i += 2;
113 continue;
114 }
115 b'"' if !in_str && depth == 0 && b[i..].starts_with(k) => {
116 let mut j = i + k.len();
117 while j < b.len() && (b[j] == b' ' || b[j] == b':') {
118 if b[j] == b':' {
119 return Some(j + 1);
120 }
121 j += 1;
122 }
123 i = j;
124 continue;
125 }
126 b'"' => in_str = !in_str,
127 b'{' | b'[' if !in_str => depth += 1,
128 b'}' | b']' if !in_str => depth -= 1,
129 _ => {}
130 }
131 i += 1;
132 }
133 None
134}
135
136fn string_value(hay: &str, key: &str) -> Option<String> {
137 let at = find_key(hay, key)?;
138 let rest = hay[at..].trim_start();
139 let rest = rest.strip_prefix('"')?;
140 let end = rest.find('"')?;
141 Some(rest[..end].to_string())
142}
143
144/// A JSON value that is either a number or a list, which is all a `coordinates`
145/// member can be at any depth.
146#[derive(Debug, PartialEq)]
147enum Coords {
148 Num(f64),
149 List(Vec<Coords>),
150}
151
152impl Coords {
153 fn as_point(&self) -> Option<Pt> {
154 match self {
155 Coords::List(v) if v.len() >= 2 => match (&v[0], &v[1]) {
156 // Extra ordinates (elevation, measure) are ignored, not rejected:
157 // GeoJSON permits them and they carry nothing a tile can show.
158 (Coords::Num(x), Coords::Num(y)) => Some((*x, *y)),
159 _ => None,
160 },
161 _ => None,
162 }
163 }
164
165 fn as_line(&self) -> Option<Vec<Pt>> {
166 match self {
167 Coords::List(v) => v.iter().map(Coords::as_point).collect(),
168 _ => None,
169 }
170 }
171
172 fn as_lines(&self) -> Option<Vec<Vec<Pt>>> {
173 match self {
174 Coords::List(v) => v.iter().map(Coords::as_line).collect(),
175 _ => None,
176 }
177 }
178
179 fn as_polygons(&self) -> Option<Vec<Vec<Vec<Pt>>>> {
180 match self {
181 Coords::List(v) => v.iter().map(Coords::as_lines).collect(),
182 _ => None,
183 }
184 }
185}
186
187/// Parse a number-or-list value, returning it and the bytes consumed.
188fn parse_coords(s: &str) -> Option<(Coords, usize)> {
189 let b = s.as_bytes();
190 let mut i = 0usize;
191 while i < b.len() && b[i].is_ascii_whitespace() {
192 i += 1;
193 }
194 if i >= b.len() {
195 return None;
196 }
197 if b[i] == b'[' {
198 i += 1;
199 let mut items = Vec::new();
200 loop {
201 while i < b.len() && (b[i].is_ascii_whitespace() || b[i] == b',') {
202 i += 1;
203 }
204 if i >= b.len() {
205 return None;
206 }
207 if b[i] == b']' {
208 return Some((Coords::List(items), i + 1));
209 }
210 let (v, used) = parse_coords(&s[i..])?;
211 items.push(v);
212 i += used;
213 }
214 }
215 // A number: take the longest run of characters a JSON number can use.
216 let start = i;
217 while i < b.len() && matches!(b[i], b'0'..=b'9' | b'-' | b'+' | b'.' | b'e' | b'E') {
218 i += 1;
219 }
220 if i == start {
221 return None;
222 }
223 Some((Coords::Num(s[start..i].parse().ok()?), i))
224}
225
226/// Parse a flat JSON object body into properties. Strings and numbers only, which
227/// is all our emitters write; a nested object or array value is skipped.
228pub fn parse_props(body: &str) -> Vec<(String, Value)> {
229 let mut out = Vec::new();
230 let b = body.as_bytes();
231 let mut i = 0usize;
232 while i < b.len() {
233 // Key.
234 while i < b.len() && b[i] != b'"' {
235 i += 1;
236 }
237 if i >= b.len() {
238 break;
239 }
240 i += 1;
241 let ks = i;
242 while i < b.len() && b[i] != b'"' {
243 if b[i] == b'\\' {
244 i += 1;
245 }
246 i += 1;
247 }
248 if i >= b.len() {
249 break;
250 }
251 let key = crate::geojson_extra::unescape(&body[ks..i]);
252 i += 1;
253 while i < b.len() && b[i] != b':' {
254 i += 1;
255 }
256 i += 1;
257 while i < b.len() && b[i].is_ascii_whitespace() {
258 i += 1;
259 }
260 if i >= b.len() {
261 break;
262 }
263 match b[i] {
264 b'"' => {
265 i += 1;
266 let vs = i;
267 while i < b.len() && b[i] != b'"' {
268 if b[i] == b'\\' {
269 i += 1;
270 }
271 i += 1;
272 }
273 out.push((key, Value::String(crate::geojson_extra::unescape(&body[vs..i.min(body.len())]))));
274 i += 1;
275 }
276 open @ (b'{' | b'[') => {
277 // Skip the whole nested value. Reporting it is the caller's job;
278 // guessing a scalar for it would be worse than omitting it.
279 let close = if open == b'{' { b'}' } else { b']' };
280 let mut depth = 0usize;
281 let mut in_str = false;
282 while i < b.len() {
283 match b[i] {
284 b'\\' if in_str => i += 1,
285 b'"' => in_str = !in_str,
286 c if c == open && !in_str => depth += 1,
287 c if c == close && !in_str => {
288 depth -= 1;
289 if depth == 0 {
290 i += 1;
291 break;
292 }
293 }
294 _ => {}
295 }
296 i += 1;
297 }
298 }
299 _ => {
300 let vs = i;
301 while i < b.len() && b[i] != b',' && b[i] != b'}' {
302 i += 1;
303 }
304 let raw = body[vs..i].trim();
305 // u64 before f64 so an integer property stays an integer on the
306 // wire, which is what tippecanoe emitted and what the styles read.
307 if let Ok(u) = raw.parse::<u64>() {
308 out.push((key, Value::Uint(u)));
309 } else if let Ok(f) = raw.parse::<f64>() {
310 out.push((key, Value::Double(f)));
311 } else if raw == "true" || raw == "false" {
312 out.push((key, Value::Bool(raw == "true")));
313 }
314 }
315 }
316 while i < b.len() && b[i] != b',' {
317 i += 1;
318 }
319 i += 1;
320 }
321 out
322}
323
324#[cfg(test)]
325mod tests {
326 use super::*;
327
328 #[test]
329 fn reads_what_osm_extract_emits_for_a_point() {
330 let line = r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[-122.4194000,37.7749000]},"properties":{"kind":"speed_camera","osm_id":"node/1001"}}"#;
331 let f = parse_feature(line).unwrap();
332 assert_eq!(f.geometry, Geometry::Points(vec![(-122.4194, 37.7749)]));
333 assert_eq!(
334 f.props,
335 vec![
336 ("kind".to_string(), Value::String("speed_camera".into())),
337 ("osm_id".to_string(), Value::String("node/1001".into())),
338 ]
339 );
340 }
341
342 #[test]
343 fn reads_a_linestring_and_a_multilinestring() {
344 let line = r#"{"type":"Feature","geometry":{"type":"LineString","coordinates":[[-122.42,37.77],[-122.41,37.78]]},"properties":{"maxspeed":"25 mph"}}"#;
345 let f = parse_feature(line).unwrap();
346 assert_eq!(
347 f.geometry,
348 Geometry::Lines(vec![vec![(-122.42, 37.77), (-122.41, 37.78)]])
349 );
350
351 let line = r#"{"type":"Feature","geometry":{"type":"MultiLineString","coordinates":[[[0,0],[1,1]],[[2,2],[3,3]]]},"properties":{}}"#;
352 let f = parse_feature(line).unwrap();
353 assert_eq!(
354 f.geometry,
355 Geometry::Lines(vec![
356 vec![(0.0, 0.0), (1.0, 1.0)],
357 vec![(2.0, 2.0), (3.0, 3.0)]
358 ])
359 );
360 }
361
362 #[test]
363 fn reads_a_polygon_with_a_hole_and_a_multipolygon() {
364 let line = r#"{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[0,0],[4,0],[4,4],[0,4],[0,0]],[[1,1],[2,1],[2,2],[1,1]]]},"properties":{"name":"Oakland"}}"#;
365 let f = parse_feature(line).unwrap();
366 let Geometry::Polygons(polys) = f.geometry else { panic!() };
367 assert_eq!(polys.len(), 1);
368 assert_eq!(polys[0].len(), 2, "exterior plus its hole");
369 assert_eq!(polys[0][0].len(), 5);
370
371 let line = r#"{"type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[[[[0,0],[1,0],[1,1],[0,0]]],[[[5,5],[6,5],[6,6],[5,5]]]]},"properties":{}}"#;
372 let Geometry::Polygons(polys) = parse_feature(line).unwrap().geometry else { panic!() };
373 assert_eq!(polys.len(), 2);
374 assert_eq!(polys[0][0].len(), 4);
375 }
376
377 #[test]
378 fn reads_a_multipoint() {
379 let line = r#"{"type":"Feature","geometry":{"type":"MultiPoint","coordinates":[[0,0],[1,1]]},"properties":{}}"#;
380 assert_eq!(
381 parse_feature(line).unwrap().geometry,
382 Geometry::Points(vec![(0.0, 0.0), (1.0, 1.0)])
383 );
384 }
385
386 #[test]
387 fn key_order_inside_the_geometry_does_not_matter() {
388 let a = r#"{"type":"Feature","geometry":{"type":"LineString","coordinates":[[0,0],[1,1]]},"properties":{}}"#;
389 let b = r#"{"type":"Feature","geometry":{"coordinates":[[0,0],[1,1]],"type":"LineString"},"properties":{}}"#;
390 assert_eq!(parse_feature(a), parse_feature(b));
391 }
392
393 #[test]
394 fn properties_before_geometry_still_reads() {
395 let line = r#"{"type":"Feature","properties":{"name":"X"},"geometry":{"type":"Point","coordinates":[1,2]}}"#;
396 let f = parse_feature(line).unwrap();
397 assert_eq!(f.geometry, Geometry::Points(vec![(1.0, 2.0)]));
398 assert_eq!(f.props, vec![("name".to_string(), Value::String("X".into()))]);
399 }
400
401 #[test]
402 fn numeric_and_boolean_properties_keep_their_types() {
403 let line = r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[0,0]},"properties":{"type":12,"score":1.5,"neg":-3,"ok":true}}"#;
404 let f = parse_feature(line).unwrap();
405 assert_eq!(
406 f.props,
407 vec![
408 ("type".to_string(), Value::Uint(12)),
409 ("score".to_string(), Value::Double(1.5)),
410 ("neg".to_string(), Value::Double(-3.0)),
411 ("ok".to_string(), Value::Bool(true)),
412 ]
413 );
414 }
415
416 #[test]
417 fn escapes_and_awkward_names_survive() {
418 let line = r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[0,0]},"properties":{"name":"A\"B\\C","other":"{not an object}"}}"#;
419 let f = parse_feature(line).unwrap();
420 assert_eq!(f.props[0].1, Value::String("A\"B\\C".into()));
421 // A brace inside a string must not truncate the properties object.
422 assert_eq!(f.props[1].1, Value::String("{not an object}".into()));
423 }
424
425 #[test]
426 fn a_nested_property_value_is_skipped_not_guessed_at() {
427 let line = r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[0,0]},"properties":{"a":1,"nested":{"x":1},"b":2}}"#;
428 let f = parse_feature(line).unwrap();
429 let keys: Vec<&str> = f.props.iter().map(|(k, _)| k.as_str()).collect();
430 assert_eq!(keys, vec!["a", "b"]);
431 }
432
433 #[test]
434 fn extra_ordinates_are_ignored() {
435 // GeoJSON allows a third (elevation) ordinate. A tile has nowhere to put it.
436 let line = r#"{"type":"Feature","geometry":{"type":"LineString","coordinates":[[1,2,300],[3,4,500]]},"properties":{}}"#;
437 assert_eq!(
438 parse_feature(line).unwrap().geometry,
439 Geometry::Lines(vec![vec![(1.0, 2.0), (3.0, 4.0)]])
440 );
441 }
442
443 #[test]
444 fn scientific_notation_and_signs_parse() {
445 let line = r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[-1.22e2,+3.7e1]},"properties":{}}"#;
446 assert_eq!(
447 parse_feature(line).unwrap().geometry,
448 Geometry::Points(vec![(-122.0, 37.0)])
449 );
450 }
451
452 #[test]
453 fn a_feature_with_no_properties_member_reads_as_empty() {
454 let line = r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[0,0]}}"#;
455 assert_eq!(parse_feature(line).unwrap().props, vec![]);
456 }
457
458 #[test]
459 fn unusable_lines_are_rejected_rather_than_guessed_at() {
460 for bad in [
461 "",
462 "not json",
463 r#"{"type":"Feature"}"#,
464 // No coordinates.
465 r#"{"type":"Feature","geometry":{"type":"Point"}}"#,
466 // A geometry type this reader does not cover.
467 r#"{"type":"Feature","geometry":{"type":"GeometryCollection","coordinates":[]}}"#,
468 // Point with one ordinate.
469 r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[1]}}"#,
470 // Wrong nesting for the declared type.
471 r#"{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[0,0],[1,1]]}}"#,
472 // Truncated array.
473 r#"{"type":"Feature","geometry":{"type":"LineString","coordinates":[[0,0],[1,"#,
474 ] {
475 assert!(parse_feature(bad).is_none(), "{bad:?} should not parse");
476 }
477 }
478
479 #[test]
480 fn a_top_level_type_key_is_not_mistaken_for_the_geometrys() {
481 // "type" appears at the top level too, and inside properties. Only the one
482 // inside the geometry object may decide the geometry.
483 let line = r#"{"type":"Feature","properties":{"type":99},"geometry":{"type":"LineString","coordinates":[[0,0],[1,1]]}}"#;
484 let f = parse_feature(line).unwrap();
485 assert!(matches!(f.geometry, Geometry::Lines(_)));
486 assert_eq!(f.props, vec![("type".to_string(), Value::Uint(99))]);
487 }
488}