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

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

geojson.rs306 lines · 10.8 KiBRaw
1//! Shared GeoJSON writer for the extracted vector layers.
2//!
3//! The layer extractors emit newline-delimited GeoJSON (geojsonseq), which is
4//! what the tilers read. This module is the single place that turns geometry and
5//! properties into bytes, so every layer produces the same shape.
6//!
7//! ## Matching the Python normalisers
8//!
9//! The pipeline this replaces ended in
10//! `json.dumps(feature, separators=(",", ":"), ensure_ascii=False)`, so:
11//!
12//! * Key order is `type`, `geometry`, `properties`, and properties are written in
13//! the order the caller lists them. GeoJSON objects are unordered by spec, but
14//! fixing the order is what makes two runs byte-identical and a diff readable.
15//! * No whitespace anywhere: `,` and `:` separate, nothing else.
16//! * Non-ASCII passes through as UTF-8 rather than becoming `\uXXXX`, which is
17//! what `ensure_ascii=False` does. Only the JSON-mandatory escapes and C0
18//! controls are rewritten.
19//!
20//! One deliberate difference: coordinates are written with a fixed 7 decimal
21//! places, matching `poi_build`, where Python wrote the shortest round-tripping
22//! representation. `-122.4194` therefore comes out as `-122.4194000`. The values
23//! are identical once parsed -- OSM coordinates are 1e-7 integers, so 7 places is
24//! exact -- and the differential harness compares parsed numbers, not bytes.
25
26use std::io::{self, Write};
27
28/// A coordinate pair in GeoJSON order: longitude, then latitude.
29pub type Coord = (f64, f64);
30
31/// The geometry shapes the extracted layers produce.
32///
33/// `Polygon` and `MultiPolygon` carry rings as the spec orders them: the exterior
34/// ring first, then its holes.
35pub enum Geometry {
36 Point(Coord),
37 LineString(Vec<Coord>),
38 MultiLineString(Vec<Vec<Coord>>),
39 Polygon(Vec<Vec<Coord>>),
40 MultiPolygon(Vec<Vec<Vec<Coord>>>),
41}
42
43impl Geometry {
44 pub fn type_name(&self) -> &'static str {
45 match self {
46 Geometry::Point(_) => "Point",
47 Geometry::LineString(_) => "LineString",
48 Geometry::MultiLineString(_) => "MultiLineString",
49 Geometry::Polygon(_) => "Polygon",
50 Geometry::MultiPolygon(_) => "MultiPolygon",
51 }
52 }
53
54 /// True when there is nothing to draw. An empty geometry is never emitted:
55 /// tippecanoe and our own tilers both treat it as a feature that vanishes at
56 /// render time, which is worse than not being in the file.
57 pub fn is_empty(&self) -> bool {
58 match self {
59 Geometry::Point(_) => false,
60 Geometry::LineString(l) => l.len() < 2,
61 Geometry::MultiLineString(ls) => ls.iter().all(|l| l.len() < 2),
62 Geometry::Polygon(rings) => rings.first().is_none_or(|r| r.len() < 4),
63 Geometry::MultiPolygon(polys) => {
64 polys.iter().all(|rings| rings.first().is_none_or(|r| r.len() < 4))
65 }
66 }
67 }
68}
69
70/// A property value.
71pub enum Value {
72 /// A JSON string. Escaped on write; UTF-8 bytes pass through.
73 Str(Vec<u8>),
74 /// A pre-rendered JSON literal (a number, `true`/`false`/`null`), written
75 /// verbatim. Rendering numbers at the call site keeps this module out of the
76 /// business of deciding a layer's numeric formatting.
77 Raw(String),
78}
79
80impl Value {
81 pub fn str(s: impl AsRef<[u8]>) -> Value {
82 Value::Str(s.as_ref().to_vec())
83 }
84
85 pub fn num(n: impl std::fmt::Display) -> Value {
86 Value::Raw(n.to_string())
87 }
88}
89
90pub struct Feature<'a> {
91 pub geometry: Geometry,
92 pub props: Vec<(&'a str, Value)>,
93}
94
95/// Escape a string for a JSON string literal. UTF-8 bytes pass through verbatim;
96/// only the JSON-mandatory escapes and C0 controls are rewritten.
97pub fn json_escape(s: &[u8], out: &mut Vec<u8>) {
98 for &c in s {
99 match c {
100 b'"' => out.extend_from_slice(b"\\\""),
101 b'\\' => out.extend_from_slice(b"\\\\"),
102 b'\n' => out.extend_from_slice(b"\\n"),
103 b'\r' => out.extend_from_slice(b"\\r"),
104 b'\t' => out.extend_from_slice(b"\\t"),
105 c if c < 0x20 => out.extend_from_slice(format!("\\u{c:04x}").as_bytes()),
106 c => out.push(c),
107 }
108 }
109}
110
111/// Render one feature into `line`, which is cleared first, and terminate it with
112/// a newline. Reusing one buffer across a whole layer avoids a per-feature
113/// allocation.
114pub fn render_feature(f: &Feature, line: &mut Vec<u8>) {
115 line.clear();
116 line.extend_from_slice(b"{\"type\":\"Feature\",\"geometry\":{\"type\":\"");
117 line.extend_from_slice(f.geometry.type_name().as_bytes());
118 line.extend_from_slice(b"\",\"coordinates\":");
119 write_coords(&f.geometry, line);
120 line.extend_from_slice(b"},\"properties\":{");
121 for (i, (key, value)) in f.props.iter().enumerate() {
122 if i > 0 {
123 line.push(b',');
124 }
125 line.push(b'"');
126 json_escape(key.as_bytes(), line);
127 line.extend_from_slice(b"\":");
128 match value {
129 Value::Str(s) => {
130 line.push(b'"');
131 json_escape(s, line);
132 line.push(b'"');
133 }
134 Value::Raw(r) => line.extend_from_slice(r.as_bytes()),
135 }
136 }
137 line.extend_from_slice(b"}}\n");
138}
139
140pub fn write_feature<W: Write>(out: &mut W, f: &Feature, line: &mut Vec<u8>) -> io::Result<()> {
141 render_feature(f, line);
142 out.write_all(line)
143}
144
145fn write_coord((lon, lat): Coord, out: &mut Vec<u8>) {
146 // `write!` into a Vec<u8> is infallible.
147 let _ = write!(out, "[{lon:.7},{lat:.7}]");
148}
149
150fn write_ring(ring: &[Coord], out: &mut Vec<u8>) {
151 out.push(b'[');
152 for (i, c) in ring.iter().enumerate() {
153 if i > 0 {
154 out.push(b',');
155 }
156 write_coord(*c, out);
157 }
158 out.push(b']');
159}
160
161fn write_rings(rings: &[Vec<Coord>], out: &mut Vec<u8>) {
162 out.push(b'[');
163 for (i, r) in rings.iter().enumerate() {
164 if i > 0 {
165 out.push(b',');
166 }
167 write_ring(r, out);
168 }
169 out.push(b']');
170}
171
172fn write_coords(g: &Geometry, out: &mut Vec<u8>) {
173 match g {
174 Geometry::Point(c) => write_coord(*c, out),
175 Geometry::LineString(l) => write_ring(l, out),
176 Geometry::MultiLineString(ls) => write_rings(ls, out),
177 Geometry::Polygon(rings) => write_rings(rings, out),
178 Geometry::MultiPolygon(polys) => {
179 out.push(b'[');
180 for (i, rings) in polys.iter().enumerate() {
181 if i > 0 {
182 out.push(b',');
183 }
184 write_rings(rings, out);
185 }
186 out.push(b']');
187 }
188 }
189}
190
191/// An OSM element reference in the `node/123` form the normalisers emitted, and
192/// which the app and the differential harness pair features on.
193pub fn osm_ref(kind: &str, id: i64) -> Value {
194 Value::Str(format!("{kind}/{id}").into_bytes())
195}
196
197#[cfg(test)]
198mod tests {
199 use super::*;
200
201 fn render(f: &Feature) -> String {
202 let mut line = Vec::new();
203 render_feature(f, &mut line);
204 String::from_utf8(line).unwrap()
205 }
206
207 #[test]
208 fn a_point_feature_matches_the_python_shape() {
209 // Exactly what json.dumps(..., separators=(",", ":"), ensure_ascii=False)
210 // produced: no whitespace, key order type/geometry/properties.
211 let f = Feature {
212 geometry: Geometry::Point((-122.4194, 37.7749)),
213 props: vec![
214 ("kind", Value::str("speed_camera")),
215 ("direction", Value::str("forward")),
216 ("osm_id", osm_ref("node", 1001)),
217 ],
218 };
219 assert_eq!(
220 render(&f),
221 "{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\
222 \"coordinates\":[-122.4194000,37.7749000]},\"properties\":\
223 {\"kind\":\"speed_camera\",\"direction\":\"forward\",\
224 \"osm_id\":\"node/1001\"}}\n"
225 );
226 }
227
228 #[test]
229 fn numbers_are_written_verbatim() {
230 let f = Feature {
231 geometry: Geometry::Point((0.0, 0.0)),
232 props: vec![("type", Value::num(12u16)), ("osm_id", Value::num(-200i64))],
233 };
234 assert!(render(&f).contains("\"type\":12,\"osm_id\":-200"));
235 }
236
237 #[test]
238 fn lines_and_polygons_nest_correctly() {
239 let line = Feature {
240 geometry: Geometry::LineString(vec![(-122.42, 37.77), (-122.41, 37.78)]),
241 props: vec![],
242 };
243 assert!(render(&line)
244 .contains("\"coordinates\":[[-122.4200000,37.7700000],[-122.4100000,37.7800000]]"));
245
246 let multi = Feature {
247 geometry: Geometry::MultiLineString(vec![vec![(0.0, 0.0), (1.0, 1.0)]]),
248 props: vec![],
249 };
250 assert!(render(&multi)
251 .contains("\"coordinates\":[[[0.0000000,0.0000000],[1.0000000,1.0000000]]]"));
252
253 // A polygon's exterior ring comes first, then its holes.
254 let poly = Feature {
255 geometry: Geometry::Polygon(vec![
256 vec![(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0), (0.0, 0.0)],
257 vec![(0.5, 0.5), (1.5, 0.5), (1.5, 1.5), (0.5, 1.5), (0.5, 0.5)],
258 ]),
259 props: vec![],
260 };
261 let s = render(&poly);
262 assert!(s.contains("\"type\":\"Polygon\""));
263 assert!(
264 s.find("0.5000000").unwrap() > s.find("2.0000000").unwrap(),
265 "the hole must be written after the exterior ring: {s}"
266 );
267 }
268
269 #[test]
270 fn empty_properties_still_produce_a_valid_object() {
271 let f = Feature { geometry: Geometry::Point((1.0, 2.0)), props: vec![] };
272 assert!(render(&f).ends_with("\"properties\":{}}\n"));
273 }
274
275 #[test]
276 fn json_escapes_only_what_it_must() {
277 let mut out = Vec::new();
278 json_escape("Ben \"B\" \\ Jerry\n\tCafé".as_bytes(), &mut out);
279 assert_eq!(String::from_utf8(out).unwrap(), "Ben \\\"B\\\" \\\\ Jerry\\n\\tCafé");
280 let mut out = Vec::new();
281 json_escape(&[0x01, 0x1f], &mut out);
282 assert_eq!(String::from_utf8(out).unwrap(), "\\u0001\\u001f");
283 }
284
285 #[test]
286 fn a_name_with_a_quote_survives_a_round_trip_through_the_writer() {
287 let f = Feature {
288 geometry: Geometry::Point((0.0, 0.0)),
289 props: vec![("name", Value::str("Joe's \"Diner\""))],
290 };
291 assert!(render(&f).contains("\"name\":\"Joe's \\\"Diner\\\"\""));
292 }
293
294 #[test]
295 fn emptiness_is_judged_per_geometry_kind() {
296 assert!(!Geometry::Point((0.0, 0.0)).is_empty());
297 assert!(Geometry::LineString(vec![(0.0, 0.0)]).is_empty());
298 assert!(!Geometry::LineString(vec![(0.0, 0.0), (1.0, 1.0)]).is_empty());
299 assert!(Geometry::MultiLineString(vec![vec![(0.0, 0.0)]]).is_empty());
300 // A ring needs 4 points: three distinct corners plus the repeated close.
301 assert!(Geometry::Polygon(vec![vec![(0.0, 0.0), (1.0, 0.0), (0.0, 0.0)]]).is_empty());
302 assert!(!Geometry::Polygon(vec![vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)]])
303 .is_empty());
304 assert!(Geometry::MultiPolygon(vec![]).is_empty());
305 }
306}