Skip to main content

geolith/source/
exact_geojson.rs

1//! `GeoJSON` read with correctly rounded coordinates.
2//!
3//! `serde_json`'s default float parser may read a decimal one or two units in
4//! the last place away from the nearest double (on the pinned Survey of India
5//! file: 42,109 of 505,208 coordinates, up to 2 ULP). Its `float_roundtrip`
6//! feature would change number parsing for the whole workspace, so the Survey
7//! of India files are read the way `geolith-dataset-builder` reads its areas:
8//! the text of each `coordinates` array is kept (`serde_json` `raw_value`) and
9//! every number in it is parsed with [`str::parse::<f64>`], which is correctly
10//! rounded. Then a polygon file turned into lines is the lines file
11//! `tools/india-boundary/derive.py` writes, bit for bit.
12
13use serde::Deserialize;
14use serde_json::value::RawValue;
15
16use crate::error::{GeolithError, Result};
17
18#[derive(Deserialize)]
19struct RawTop<'a> {
20    #[serde(borrow, default)]
21    features: Option<Vec<RawFeature<'a>>>,
22    #[serde(borrow, default)]
23    geometry: Option<&'a RawValue>,
24    #[serde(borrow, default)]
25    coordinates: Option<&'a RawValue>,
26    #[serde(borrow, default)]
27    geometries: Option<Vec<&'a RawValue>>,
28}
29
30#[derive(Deserialize)]
31struct RawFeature<'a> {
32    #[serde(borrow, default)]
33    geometry: Option<&'a RawValue>,
34}
35
36#[derive(Deserialize)]
37struct RawGeometry<'a> {
38    #[serde(borrow, default)]
39    coordinates: Option<&'a RawValue>,
40    #[serde(borrow, default)]
41    geometries: Option<Vec<&'a RawValue>>,
42}
43
44fn data(message: impl Into<String>) -> GeolithError {
45    GeolithError::GeoJson(message.into())
46}
47
48/// The `GeoJSON` document `text`, every coordinate the correctly rounded f64 of
49/// its decimal text.
50///
51/// # Errors
52///
53/// `GeolithError::Json` when `text` is not `GeoJSON`; `GeolithError::GeoJson`
54/// when a `coordinates` array holds anything but numbers that match its
55/// geometry.
56pub fn parse(text: &str) -> Result<geojson::GeoJson> {
57    let mut document: geojson::GeoJson = serde_json::from_str(text)?;
58    let raw: RawTop<'_> = serde_json::from_str(text)?;
59    match &mut document {
60        geojson::GeoJson::FeatureCollection(collection) => {
61            let features = raw.features.unwrap_or_default();
62            if features.len() != collection.features.len() {
63                return Err(data("feature count differs between readings"));
64            }
65            for (n, (feature, raw)) in collection.features.iter_mut().zip(features).enumerate() {
66                match (feature.geometry.as_mut(), raw.geometry) {
67                    (Some(geometry), Some(raw)) => {
68                        exact_geometry(&mut geometry.value, raw.get())
69                            .map_err(|e| e.context(format!("coordinates of feature {}", n + 1)))?;
70                    }
71                    (None, None) => {}
72                    _ => {
73                        return Err(data(format!(
74                            "geometry of feature {} differs between readings",
75                            n + 1
76                        )));
77                    }
78                }
79            }
80        }
81        geojson::GeoJson::Feature(feature) => match (feature.geometry.as_mut(), raw.geometry) {
82            (Some(geometry), Some(raw)) => exact_geometry(&mut geometry.value, raw.get())?,
83            (None, None) => {}
84            _ => return Err(data("geometry differs between readings")),
85        },
86        geojson::GeoJson::Geometry(geometry) => {
87            let raw = RawGeometry {
88                coordinates: raw.coordinates,
89                geometries: raw.geometries,
90            };
91            exact_parts(&mut geometry.value, &raw)?;
92        }
93    }
94    Ok(document)
95}
96
97/// Overwrite the coordinates of `value` with the numbers of its text `raw`.
98fn exact_geometry(value: &mut geojson::GeometryValue, raw: &str) -> Result<()> {
99    let raw: RawGeometry<'_> = serde_json::from_str(raw)?;
100    exact_parts(value, &raw)
101}
102
103fn exact_parts(value: &mut geojson::GeometryValue, raw: &RawGeometry<'_>) -> Result<()> {
104    use geojson::GeometryValue as G;
105    if let G::GeometryCollection { geometries } = value {
106        let parts = raw.geometries.clone().unwrap_or_default();
107        if parts.len() != geometries.len() {
108            return Err(data("geometry count differs between readings"));
109        }
110        for (geometry, part) in geometries.iter_mut().zip(parts) {
111            exact_geometry(&mut geometry.value, part.get())?;
112        }
113        return Ok(());
114    }
115    let numbers = numbers(raw.coordinates.map_or("", |c| c.get()))?;
116    let positions: Vec<&mut geojson::Position> = match value {
117        G::Point { coordinates } => vec![coordinates],
118        G::MultiPoint { coordinates } | G::LineString { coordinates } => {
119            coordinates.iter_mut().collect()
120        }
121        G::MultiLineString { coordinates } | G::Polygon { coordinates } => {
122            coordinates.iter_mut().flatten().collect()
123        }
124        G::MultiPolygon { coordinates } => coordinates.iter_mut().flatten().flatten().collect(),
125        G::GeometryCollection { .. } => Vec::new(),
126    };
127    let mut next = numbers.into_iter();
128    for position in positions {
129        for slot in position.as_slice_mut() {
130            let Some(number) = next.next() else {
131                return Err(data("fewer numbers than coordinates"));
132            };
133            *slot = number;
134        }
135    }
136    if next.next().is_some() {
137        return Err(data("more numbers than coordinates"));
138    }
139    Ok(())
140}
141
142/// The numbers of the nested JSON arrays `text`, in document order.
143fn numbers(text: &str) -> Result<Vec<f64>> {
144    let mut out = Vec::new();
145    let mut start: Option<usize> = None;
146    let mut flush = |start: &mut Option<usize>, end: usize| -> Result<()> {
147        if let Some(from) = start.take() {
148            let token = text.get(from..end).unwrap_or_default();
149            out.push(
150                token
151                    .parse::<f64>()
152                    .map_err(|e| data(format!("bad number {token:?}: {e}")))?,
153            );
154        }
155        Ok(())
156    };
157    for (at, byte) in text.bytes().enumerate() {
158        match byte {
159            b'[' | b']' | b',' | b' ' | b'\t' | b'\n' | b'\r' => flush(&mut start, at)?,
160            b'0'..=b'9' | b'-' | b'+' | b'.' | b'e' | b'E' => {
161                start.get_or_insert(at);
162            }
163            _ => {
164                return Err(data(format!("unexpected byte {byte:#04x} in coordinates")));
165            }
166        }
167    }
168    flush(&mut start, text.len())?;
169    Ok(out)
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    /// 17 significant digits, from the pinned composite file. Python reads it
177    /// as 0x40536150FC72E8EC; `serde_json` by default as the double below it.
178    const LONG: &str = "77.520568001000072";
179    const LONG_BITS: u64 = 0x4053_6150_FC72_E8EC;
180
181    fn first_x(document: &geojson::GeoJson) -> f64 {
182        let geometry = match document {
183            geojson::GeoJson::FeatureCollection(c) => c.features[0].geometry.as_ref(),
184            geojson::GeoJson::Feature(f) => f.geometry.as_ref(),
185            geojson::GeoJson::Geometry(g) => Some(g),
186        }
187        .expect("a geometry");
188        match &geometry.value {
189            geojson::GeometryValue::LineString { coordinates } => coordinates[0][0],
190            other => panic!("not a line: {other:?}"),
191        }
192    }
193
194    #[test]
195    fn numbers_parse_json_number_forms() {
196        assert_eq!(
197            numbers("[[1, -2.5e-3],[ 1E+2 ,0.1]]").unwrap(),
198            [1.0, -0.0025, 100.0, 0.1]
199        );
200        assert!(numbers("[1, x]").is_err());
201        assert!(numbers("[1.2.3]").is_err());
202    }
203
204    /// A feature collection, a feature and a bare geometry each give the
205    /// nearest double.
206    #[test]
207    fn every_top_level_shape_is_read_to_the_nearest_double() {
208        let line = format!(r#"{{"type":"LineString","coordinates":[[{LONG},35.5],[78,36]]}}"#);
209        let feature = format!(r#"{{"type":"Feature","properties":{{}},"geometry":{line}}}"#);
210        let collection = format!(r#"{{"type":"FeatureCollection","features":[{feature}]}}"#);
211        for (name, text) in [
212            ("collection", &collection),
213            ("feature", &feature),
214            ("geometry", &line),
215        ] {
216            let document = parse(text).unwrap_or_else(|e| panic!("{name}: {e}"));
217            assert_eq!(first_x(&document).to_bits(), LONG_BITS, "{name}");
218        }
219    }
220
221    #[test]
222    fn text_that_is_not_geojson_is_an_error() {
223        assert!(parse("{not json").is_err());
224        assert!(parse(r#"{"type":"Banana"}"#).is_err());
225        assert!(parse(r#"{"type":"LineString","coordinates":[[1,"x"]]}"#).is_err());
226    }
227}