geolith-dataset-builder 0.2.2

Raster datasets for geolith: district areas, normals, numbers and a map layer per period, and the steps that stage, verify and publish them to any S3-compatible bucket
Documentation
//! `GeoJSON` feature collections read with correctly rounded coordinates.
//!
//! `serde_json`'s default float parser (without its `float_roundtrip`
//! feature) may read a decimal one ULP off. That feature would change number
//! parsing for the whole engine, so the dataset code reads the text of each
//! `coordinates` array (`serde_json` `raw_value`) and parses every number with
//! [`str::parse::<f64>`], which is correctly rounded.
//!
//! `bbox` members keep the default parsing: the dataset code derives every
//! bounding box from the coordinates. A geometry with a duplicate
//! `coordinates` key is refused.

use anyhow::{Context as _, Result, bail, ensure};
use serde::Deserialize;
use serde_json::value::RawValue;

#[derive(Deserialize)]
struct RawCollection<'a> {
    #[serde(borrow)]
    features: Vec<RawFeature<'a>>,
}

#[derive(Deserialize)]
struct RawFeature<'a> {
    #[serde(borrow, default)]
    geometry: Option<&'a RawValue>,
}

#[derive(Deserialize)]
struct RawGeometry<'a> {
    #[serde(borrow, default)]
    coordinates: Option<&'a RawValue>,
    #[serde(borrow, default)]
    geometries: Option<Vec<&'a RawValue>>,
}

/// The `GeoJSON` feature collection `bytes`; every geometry coordinate is the
/// correctly rounded f64 of its decimal text.
///
/// # Errors
///
/// Fails when `bytes` is not UTF-8 or not a feature collection, or a
/// `coordinates` array holds something else than numbers matching its
/// geometry.
pub fn parse_feature_collection(bytes: &[u8]) -> Result<geojson::FeatureCollection> {
    let text = std::str::from_utf8(bytes)?;
    let mut collection: geojson::FeatureCollection = serde_json::from_str(text)?;
    let raw: RawCollection<'_> = serde_json::from_str(text)?;
    ensure!(
        raw.features.len() == collection.features.len(),
        "feature count differs between readings"
    );
    for (n, (feature, raw)) in collection.features.iter_mut().zip(raw.features).enumerate() {
        match (feature.geometry.as_mut(), raw.geometry) {
            (Some(geometry), Some(raw)) => exact_geometry(&mut geometry.value, raw.get())
                .with_context(|| format!("coordinates of feature {}", n + 1))?,
            (None, None) => {}
            _ => bail!("geometry of feature {} differs between readings", n + 1),
        }
    }
    Ok(collection)
}

/// Overwrite the coordinates of `value` with the numbers of its text `raw`.
fn exact_geometry(value: &mut geojson::GeometryValue, raw: &str) -> Result<()> {
    use geojson::GeometryValue as G;
    let raw: RawGeometry<'_> = serde_json::from_str(raw)?;
    if let G::GeometryCollection { geometries } = value {
        let parts = raw.geometries.unwrap_or_default();
        ensure!(parts.len() == geometries.len(), "geometry count differs");
        for (geometry, part) in geometries.iter_mut().zip(parts) {
            exact_geometry(&mut geometry.value, part.get())?;
        }
        return Ok(());
    }
    let numbers = numbers(raw.coordinates.map_or("", RawValue::get))?;
    let positions: Vec<&mut geojson::Position> = match value {
        G::Point { coordinates } => vec![coordinates],
        G::MultiPoint { coordinates } | G::LineString { coordinates } => {
            coordinates.iter_mut().collect()
        }
        G::MultiLineString { coordinates } | G::Polygon { coordinates } => {
            coordinates.iter_mut().flatten().collect()
        }
        G::MultiPolygon { coordinates } => coordinates.iter_mut().flatten().flatten().collect(),
        G::GeometryCollection { .. } => Vec::new(),
    };
    let mut next = numbers.into_iter();
    for position in positions {
        for slot in position.as_slice_mut() {
            let Some(number) = next.next() else {
                bail!("fewer numbers than coordinates");
            };
            *slot = number;
        }
    }
    ensure!(next.next().is_none(), "more numbers than coordinates");
    Ok(())
}

/// The numbers of the nested JSON arrays `text`, in document order.
fn numbers(text: &str) -> Result<Vec<f64>> {
    let mut out = Vec::new();
    let mut start: Option<usize> = None;
    let mut flush = |start: &mut Option<usize>, end: usize| -> Result<()> {
        if let Some(from) = start.take() {
            let token = text.get(from..end).unwrap_or_default();
            out.push(
                token
                    .parse::<f64>()
                    .with_context(|| format!("bad number {token:?}"))?,
            );
        }
        Ok(())
    };
    for (at, byte) in text.bytes().enumerate() {
        match byte {
            b'[' | b']' | b',' | b' ' | b'\t' | b'\n' | b'\r' => flush(&mut start, at)?,
            b'0'..=b'9' | b'-' | b'+' | b'.' | b'e' | b'E' => {
                start.get_or_insert(at);
            }
            _ => bail!("unexpected byte {byte:#04x} in coordinates"),
        }
    }
    flush(&mut start, text.len())?;
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn numbers_parse_json_number_forms() {
        let got = numbers("[[1, -2.5e-3],[ 1E+2 ,0.1]]").unwrap();
        assert_eq!(got, [1.0, -0.0025, 100.0, 0.1]);
        assert!(numbers("[1, x]").is_err());
        assert!(numbers("[1.2.3]").is_err());
    }

    #[test]
    fn geometry_collections_and_counts() {
        let text = r#"{"type":"FeatureCollection","features":[
            {"type":"Feature","properties":null,"geometry":{"type":"GeometryCollection","geometries":[
              {"type":"Point","coordinates":[21.546982095478498,1]},
              {"type":"LineString","coordinates":[[0,0],[1,1]]}]}},
            {"type":"Feature","properties":null,"geometry":null}]}"#;
        let collection = parse_feature_collection(text.as_bytes()).unwrap();
        let Some(geometry) = &collection.features[0].geometry else {
            panic!("no geometry");
        };
        let geojson::GeometryValue::GeometryCollection { geometries } = &geometry.value else {
            panic!("not a collection");
        };
        let geojson::GeometryValue::Point { coordinates } = &geometries[0].value else {
            panic!("not a point");
        };
        let exact: f64 = "21.546982095478498".parse().unwrap();
        assert_eq!(coordinates[0].to_bits(), exact.to_bits());
        assert!(collection.features[1].geometry.is_none());

        let mut value = geojson::GeometryValue::LineString {
            coordinates: vec![vec![0.0, 0.0].into()],
        };
        assert!(exact_geometry(&mut value, r#"{"coordinates":[[0,0],[1,1]]}"#).is_err());
        assert!(exact_geometry(&mut value, r#"{"coordinates":[[0]]}"#).is_err());
    }

    #[test]
    fn multipolygons_with_holes_and_3d_positions() {
        let m = "21.546982095478498";
        let text = format!(
            r#"{{"type":"FeatureCollection","features":[{{"type":"Feature","properties":null,
            "geometry":{{"type":"MultiPolygon","coordinates":[
              [[[0,0],[{m},0],[{m},{m}],[0,0]],[[1,1],[2,1,{m}],[2,2],[1,1]]],
              [[[30,30],[31,30],[31,{m}],[30,30]]]]}}}}]}}"#
        );
        let collection = parse_feature_collection(text.as_bytes()).unwrap();
        let Some(geometry) = &collection.features[0].geometry else {
            panic!("no geometry");
        };
        let geojson::GeometryValue::MultiPolygon { coordinates } = &geometry.value else {
            panic!("not a multipolygon");
        };
        let exact = m.parse::<f64>().unwrap().to_bits();
        let bits = |p: &geojson::Position, i: usize| p[i].to_bits();
        assert_eq!(bits(&coordinates[0][0][1], 0), exact);
        assert_eq!(bits(&coordinates[0][0][2], 0), exact);
        assert_eq!(bits(&coordinates[0][0][2], 1), exact);
        assert_eq!(
            coordinates[0][1][1].as_slice(),
            [2.0, 1.0, f64::from_bits(exact)]
        );
        assert_eq!(bits(&coordinates[1][0][2], 1), exact);
        assert_eq!(coordinates[1][0][3].as_slice(), [30.0, 30.0]);
    }

    #[test]
    fn non_utf8_text_is_refused() {
        assert!(parse_feature_collection(b"\xff").is_err());
    }
}