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

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

geojson.rs482 lines · 17.3 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((
274 key,
275 Value::String(crate::geojson_extra::unescape(&body[vs..i.min(body.len())])),
276 ));
277 i += 1;
278 }
279 open @ (b'{' | b'[') => {
280 // Skip the whole nested value. Reporting it is the caller's job;
281 // guessing a scalar for it would be worse than omitting it.
282 let close = if open == b'{' { b'}' } else { b']' };
283 let mut depth = 0usize;
284 let mut in_str = false;
285 while i < b.len() {
286 match b[i] {
287 b'\\' if in_str => i += 1,
288 b'"' => in_str = !in_str,
289 c if c == open && !in_str => depth += 1,
290 c if c == close && !in_str => {
291 depth -= 1;
292 if depth == 0 {
293 i += 1;
294 break;
295 }
296 }
297 _ => {}
298 }
299 i += 1;
300 }
301 }
302 _ => {
303 let vs = i;
304 while i < b.len() && b[i] != b',' && b[i] != b'}' {
305 i += 1;
306 }
307 let raw = body[vs..i].trim();
308 // u64 before f64 so an integer property stays an integer on the
309 // wire, which is what tippecanoe emitted and what the styles read.
310 if let Ok(u) = raw.parse::<u64>() {
311 out.push((key, Value::Uint(u)));
312 } else if let Ok(f) = raw.parse::<f64>() {
313 out.push((key, Value::Double(f)));
314 } else if raw == "true" || raw == "false" {
315 out.push((key, Value::Bool(raw == "true")));
316 }
317 }
318 }
319 while i < b.len() && b[i] != b',' {
320 i += 1;
321 }
322 i += 1;
323 }
324 out
325}
326
327#[cfg(test)]
328mod tests {
329 use super::*;
330
331 #[test]
332 fn reads_what_osm_extract_emits_for_a_point() {
333 let line = r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[-122.4194000,37.7749000]},"properties":{"kind":"speed_camera","osm_id":"node/1001"}}"#;
334 let f = parse_feature(line).unwrap();
335 assert_eq!(f.geometry, Geometry::Points(vec![(-122.4194, 37.7749)]));
336 assert_eq!(
337 f.props,
338 vec![
339 ("kind".to_string(), Value::String("speed_camera".into())),
340 ("osm_id".to_string(), Value::String("node/1001".into())),
341 ]
342 );
343 }
344
345 #[test]
346 fn reads_a_linestring_and_a_multilinestring() {
347 let line = r#"{"type":"Feature","geometry":{"type":"LineString","coordinates":[[-122.42,37.77],[-122.41,37.78]]},"properties":{"maxspeed":"25 mph"}}"#;
348 let f = parse_feature(line).unwrap();
349 assert_eq!(f.geometry, Geometry::Lines(vec![vec![(-122.42, 37.77), (-122.41, 37.78)]]));
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![vec![(0.0, 0.0), (1.0, 1.0)], vec![(2.0, 2.0), (3.0, 3.0)]])
356 );
357 }
358
359 #[test]
360 fn reads_a_polygon_with_a_hole_and_a_multipolygon() {
361 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"}}"#;
362 let f = parse_feature(line).unwrap();
363 let Geometry::Polygons(polys) = f.geometry else { panic!() };
364 assert_eq!(polys.len(), 1);
365 assert_eq!(polys[0].len(), 2, "exterior plus its hole");
366 assert_eq!(polys[0][0].len(), 5);
367
368 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":{}}"#;
369 let Geometry::Polygons(polys) = parse_feature(line).unwrap().geometry else { panic!() };
370 assert_eq!(polys.len(), 2);
371 assert_eq!(polys[0][0].len(), 4);
372 }
373
374 #[test]
375 fn reads_a_multipoint() {
376 let line = r#"{"type":"Feature","geometry":{"type":"MultiPoint","coordinates":[[0,0],[1,1]]},"properties":{}}"#;
377 assert_eq!(
378 parse_feature(line).unwrap().geometry,
379 Geometry::Points(vec![(0.0, 0.0), (1.0, 1.0)])
380 );
381 }
382
383 #[test]
384 fn key_order_inside_the_geometry_does_not_matter() {
385 let a = r#"{"type":"Feature","geometry":{"type":"LineString","coordinates":[[0,0],[1,1]]},"properties":{}}"#;
386 let b = r#"{"type":"Feature","geometry":{"coordinates":[[0,0],[1,1]],"type":"LineString"},"properties":{}}"#;
387 assert_eq!(parse_feature(a), parse_feature(b));
388 }
389
390 #[test]
391 fn properties_before_geometry_still_reads() {
392 let line = r#"{"type":"Feature","properties":{"name":"X"},"geometry":{"type":"Point","coordinates":[1,2]}}"#;
393 let f = parse_feature(line).unwrap();
394 assert_eq!(f.geometry, Geometry::Points(vec![(1.0, 2.0)]));
395 assert_eq!(f.props, vec![("name".to_string(), Value::String("X".into()))]);
396 }
397
398 #[test]
399 fn numeric_and_boolean_properties_keep_their_types() {
400 let line = r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[0,0]},"properties":{"type":12,"score":1.5,"neg":-3,"ok":true}}"#;
401 let f = parse_feature(line).unwrap();
402 assert_eq!(
403 f.props,
404 vec![
405 ("type".to_string(), Value::Uint(12)),
406 ("score".to_string(), Value::Double(1.5)),
407 ("neg".to_string(), Value::Double(-3.0)),
408 ("ok".to_string(), Value::Bool(true)),
409 ]
410 );
411 }
412
413 #[test]
414 fn escapes_and_awkward_names_survive() {
415 let line = r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[0,0]},"properties":{"name":"A\"B\\C","other":"{not an object}"}}"#;
416 let f = parse_feature(line).unwrap();
417 assert_eq!(f.props[0].1, Value::String("A\"B\\C".into()));
418 // A brace inside a string must not truncate the properties object.
419 assert_eq!(f.props[1].1, Value::String("{not an object}".into()));
420 }
421
422 #[test]
423 fn a_nested_property_value_is_skipped_not_guessed_at() {
424 let line = r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[0,0]},"properties":{"a":1,"nested":{"x":1},"b":2}}"#;
425 let f = parse_feature(line).unwrap();
426 let keys: Vec<&str> = f.props.iter().map(|(k, _)| k.as_str()).collect();
427 assert_eq!(keys, vec!["a", "b"]);
428 }
429
430 #[test]
431 fn extra_ordinates_are_ignored() {
432 // GeoJSON allows a third (elevation) ordinate. A tile has nowhere to put it.
433 let line = r#"{"type":"Feature","geometry":{"type":"LineString","coordinates":[[1,2,300],[3,4,500]]},"properties":{}}"#;
434 assert_eq!(
435 parse_feature(line).unwrap().geometry,
436 Geometry::Lines(vec![vec![(1.0, 2.0), (3.0, 4.0)]])
437 );
438 }
439
440 #[test]
441 fn scientific_notation_and_signs_parse() {
442 let line = r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[-1.22e2,+3.7e1]},"properties":{}}"#;
443 assert_eq!(parse_feature(line).unwrap().geometry, Geometry::Points(vec![(-122.0, 37.0)]));
444 }
445
446 #[test]
447 fn a_feature_with_no_properties_member_reads_as_empty() {
448 let line = r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[0,0]}}"#;
449 assert_eq!(parse_feature(line).unwrap().props, vec![]);
450 }
451
452 #[test]
453 fn unusable_lines_are_rejected_rather_than_guessed_at() {
454 for bad in [
455 "",
456 "not json",
457 r#"{"type":"Feature"}"#,
458 // No coordinates.
459 r#"{"type":"Feature","geometry":{"type":"Point"}}"#,
460 // A geometry type this reader does not cover.
461 r#"{"type":"Feature","geometry":{"type":"GeometryCollection","coordinates":[]}}"#,
462 // Point with one ordinate.
463 r#"{"type":"Feature","geometry":{"type":"Point","coordinates":[1]}}"#,
464 // Wrong nesting for the declared type.
465 r#"{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[0,0],[1,1]]}}"#,
466 // Truncated array.
467 r#"{"type":"Feature","geometry":{"type":"LineString","coordinates":[[0,0],[1,"#,
468 ] {
469 assert!(parse_feature(bad).is_none(), "{bad:?} should not parse");
470 }
471 }
472
473 #[test]
474 fn a_top_level_type_key_is_not_mistaken_for_the_geometrys() {
475 // "type" appears at the top level too, and inside properties. Only the one
476 // inside the geometry object may decide the geometry.
477 let line = r#"{"type":"Feature","properties":{"type":99},"geometry":{"type":"LineString","coordinates":[[0,0],[1,1]]}}"#;
478 let f = parse_feature(line).unwrap();
479 assert!(matches!(f.geometry, Geometry::Lines(_)));
480 assert_eq!(f.props, vec![("type".to_string(), Value::Uint(99))]);
481 }
482}