Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/korp-map

crates/korp-map-wire/src/geoarrow.rs

//! **GeoArrow native geometry**, the GeoParquet 1.1 separated layout osm-katana exports:
//! a coordinate is `struct<x: f64 not null, y: f64 not null>`; `multilinestring` is
//! `list<element: list<element: coord not null> not null>`; `multipolygon` adds one more
//! list level; only the outermost value may be null.
//!
//! [`NativeBuilder`] builds such a column row by row, from coordinates or from a WKB blob
//! (the files' generalised `geometry_z6/z9/z12` columns are WKB). A WKB row whose type
//! does not fit the column (a `Point` where areas are built, a truncated blob, a Z/M or
//! EWKB type) is pushed as null and reported, so the caller can leave the row out.

use std::sync::Arc;

use arrow_array::{ArrayRef, Float64Array, ListArray, StructArray};
use arrow_buffer::{NullBuffer, OffsetBuffer};
use arrow_schema::{DataType, Field, Fields};

use crate::source::Kind;

fn coord_fields() -> Fields {
    Fields::from(vec![
        Field::new("x", DataType::Float64, false),
        Field::new("y", DataType::Float64, false),
    ])
}

fn coord_type() -> DataType {
    DataType::Struct(coord_fields())
}

fn list_of(t: DataType) -> DataType {
    DataType::List(Arc::new(Field::new("element", t, false)))
}

/// The native `geometry` column type of `kind`.
#[must_use]
pub fn geometry_type(kind: Kind) -> DataType {
    match kind {
        Kind::Points => coord_type(),
        Kind::Lines => list_of(list_of(coord_type())),
        Kind::Areas => list_of(list_of(list_of(coord_type()))),
    }
}

/// Builds one native geometry column of a kind, row by row.
pub struct NativeBuilder {
    kind: Kind,
    xs: Vec<f64>,
    ys: Vec<f64>,
    /// Coordinate offset at the end of each linestring / ring.
    ring_off: Vec<i32>,
    /// Ring offset at the end of each polygon (areas only).
    poly_off: Vec<i32>,
    /// Part offset at the end of each row (lines: rings; areas: polygons).
    row_off: Vec<i32>,
    valid: Vec<bool>,
}

/// One parsed WKB shape, borrowed coordinates already copied out.
enum Shape {
    Point(f64, f64),
    /// Linestrings (one for a LineString, several for a MultiLineString).
    Lines(Vec<Vec<(f64, f64)>>),
    /// Polygons of rings (one for a Polygon, several for a MultiPolygon).
    Polygons(Vec<Vec<Vec<(f64, f64)>>>),
}

struct Wkb<'a> {
    b: &'a [u8],
    at: usize,
}

impl<'a> Wkb<'a> {
    fn take(&mut self, n: usize) -> Option<&'a [u8]> {
        let s = self.b.get(self.at..self.at + n)?;
        self.at += n;
        Some(s)
    }
    fn u32(&mut self, le: bool) -> Option<u32> {
        let a: [u8; 4] = self.take(4)?.try_into().ok()?;
        Some(if le {
            u32::from_le_bytes(a)
        } else {
            u32::from_be_bytes(a)
        })
    }
    fn f64(&mut self, le: bool) -> Option<f64> {
        let a: [u8; 8] = self.take(8)?.try_into().ok()?;
        Some(if le {
            f64::from_le_bytes(a)
        } else {
            f64::from_be_bytes(a)
        })
    }
    /// Byte order + 2D ISO type of the next geometry.
    fn header(&mut self) -> Option<(bool, u32)> {
        let le = match self.take(1)?[0] {
            0 => false,
            1 => true,
            _ => return None,
        };
        Some((le, self.u32(le)?))
    }
    fn coords(&mut self, le: bool) -> Option<Vec<(f64, f64)>> {
        let n = self.u32(le)? as usize;
        if n > self.b.len() / 16 + 1 {
            return None;
        }
        (0..n)
            .map(|_| Some((self.f64(le)?, self.f64(le)?)))
            .collect()
    }
    fn rings(&mut self, le: bool) -> Option<Vec<Vec<(f64, f64)>>> {
        let n = self.u32(le)? as usize;
        if n > self.b.len() / 4 + 1 {
            return None;
        }
        (0..n).map(|_| self.coords(le)).collect()
    }
    /// The members of a Multi* whose member type is `want`.
    fn members<T>(
        &mut self,
        le: bool,
        want: u32,
        f: impl Fn(&mut Self, bool) -> Option<T>,
    ) -> Option<Vec<T>> {
        let n = self.u32(le)? as usize;
        if n > self.b.len() / 9 + 1 {
            return None;
        }
        (0..n)
            .map(|_| {
                let (mle, t) = self.header()?;
                (t == want).then_some(())?;
                f(self, mle)
            })
            .collect()
    }
}

/// Parse a 2D ISO WKB blob of type 1..=6 (MultiPoint and collections are not shapes
/// the map draws). `None` for anything else or bytes after the geometry.
fn parse(b: &[u8]) -> Option<Shape> {
    let mut w = Wkb { b, at: 0 };
    let (le, t) = w.header()?;
    let s = match t {
        1 => Shape::Point(w.f64(le)?, w.f64(le)?),
        2 => Shape::Lines(vec![w.coords(le)?]),
        3 => Shape::Polygons(vec![w.rings(le)?]),
        5 => Shape::Lines(w.members(le, 2, |w, le| w.coords(le))?),
        6 => Shape::Polygons(w.members(le, 3, |w, le| w.rings(le))?),
        _ => return None,
    };
    (w.at == b.len()).then_some(s)
}

/// Would [`NativeBuilder::push_wkb`] take this blob for `kind`? (It parses: a malformed
/// blob does not fit either.)
#[must_use]
pub fn wkb_fits(kind: Kind, b: &[u8]) -> bool {
    matches!(
        (kind, parse(b)),
        (Kind::Points, Some(Shape::Point(..)))
            | (Kind::Lines, Some(Shape::Lines(_)))
            | (Kind::Areas, Some(Shape::Polygons(_)))
    )
}

impl NativeBuilder {
    /// An empty builder for `kind`.
    #[must_use]
    pub fn new(kind: Kind) -> Self {
        Self {
            kind,
            xs: Vec::new(),
            ys: Vec::new(),
            ring_off: vec![0],
            poly_off: vec![0],
            row_off: vec![0],
            valid: Vec::new(),
        }
    }

    fn coords(&mut self, c: &[(f64, f64)]) {
        self.xs.extend(c.iter().map(|p| p.0));
        self.ys.extend(c.iter().map(|p| p.1));
        self.ring_off.push(self.xs.len() as i32);
    }

    fn close_row(&mut self, valid: bool) {
        match self.kind {
            Kind::Points => {}
            Kind::Lines => self.row_off.push(self.ring_off.len() as i32 - 1),
            Kind::Areas => self.row_off.push(self.poly_off.len() as i32 - 1),
        }
        self.valid.push(valid);
    }

    /// A null row.
    pub fn push_null(&mut self) {
        if self.kind == Kind::Points {
            self.xs.push(0.0);
            self.ys.push(0.0);
        }
        self.close_row(false);
    }

    /// A point row (points kind).
    pub fn push_point(&mut self, x: f64, y: f64) {
        debug_assert_eq!(self.kind, Kind::Points);
        self.xs.push(x);
        self.ys.push(y);
        self.close_row(true);
    }

    /// A multilinestring row (lines kind).
    pub fn push_lines(&mut self, parts: &[Vec<(f64, f64)>]) {
        debug_assert_eq!(self.kind, Kind::Lines);
        for p in parts {
            self.coords(p);
        }
        self.close_row(true);
    }

    /// A multipolygon row (areas kind): polygons of rings, outer ring first.
    pub fn push_polygons(&mut self, polys: &[Vec<Vec<(f64, f64)>>]) {
        debug_assert_eq!(self.kind, Kind::Areas);
        for poly in polys {
            for ring in poly {
                self.coords(ring);
            }
            self.poly_off.push(self.ring_off.len() as i32 - 1);
        }
        self.close_row(true);
    }

    /// A row from WKB: a Point for points, (Multi)LineString for lines, (Multi)Polygon for
    /// areas. Anything else is pushed as null and `false` returned.
    pub fn push_wkb(&mut self, b: &[u8]) -> bool {
        match (self.kind, parse(b)) {
            (Kind::Points, Some(Shape::Point(x, y))) => self.push_point(x, y),
            (Kind::Lines, Some(Shape::Lines(p))) => self.push_lines(&p),
            (Kind::Areas, Some(Shape::Polygons(p))) => self.push_polygons(&p),
            _ => {
                self.push_null();
                return false;
            }
        }
        true
    }

    /// Rows pushed so far.
    #[must_use]
    pub fn len(&self) -> usize {
        self.valid.len()
    }

    /// No rows yet.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.valid.is_empty()
    }

    /// The column, typed [`geometry_type`]`(kind)`.
    #[must_use]
    pub fn finish(self) -> ArrayRef {
        let nulls = self
            .valid
            .iter()
            .any(|v| !v)
            .then(|| NullBuffer::from(self.valid.clone()));
        let coords = StructArray::new(
            coord_fields(),
            vec![
                Arc::new(Float64Array::from(self.xs)) as ArrayRef,
                Arc::new(Float64Array::from(self.ys)),
            ],
            None,
        );
        let list = |child: DataType,
                    off: Vec<i32>,
                    values: ArrayRef,
                    nulls: Option<NullBuffer>|
         -> ArrayRef {
            Arc::new(ListArray::new(
                Arc::new(Field::new("element", child, false)),
                OffsetBuffer::new(off.into()),
                values,
                nulls,
            ))
        };
        match self.kind {
            Kind::Points => {
                let (f, c, _) = coords.into_parts();
                Arc::new(StructArray::new(f, c, nulls))
            }
            Kind::Lines => {
                let rings = list(coord_type(), self.ring_off, Arc::new(coords), None);
                list(list_of(coord_type()), self.row_off, rings, nulls)
            }
            Kind::Areas => {
                let rings = list(coord_type(), self.ring_off, Arc::new(coords), None);
                let polys = list(list_of(coord_type()), self.poly_off, rings, None);
                list(list_of(list_of(coord_type())), self.row_off, polys, nulls)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use arrow_array::Array;
    use arrow_array::cast::AsArray;

    fn wkb_le(t: u32, body: &[u8]) -> Vec<u8> {
        let mut v = vec![1u8];
        v.extend(t.to_le_bytes());
        v.extend(body);
        v
    }

    fn pts_le(c: &[(f64, f64)]) -> Vec<u8> {
        let mut v = (c.len() as u32).to_le_bytes().to_vec();
        for (x, y) in c {
            v.extend(x.to_le_bytes());
            v.extend(y.to_le_bytes());
        }
        v
    }

    #[test]
    fn a_polygon_becomes_a_one_member_multipolygon_and_a_point_is_left_out() {
        let ring = [(1.0, 2.0), (3.0, 2.0), (3.0, 4.0), (1.0, 2.0)];
        let mut body = 1u32.to_le_bytes().to_vec();
        body.extend(pts_le(&ring));
        let mut b = NativeBuilder::new(Kind::Areas);
        assert!(b.push_wkb(&wkb_le(3, &body)));
        assert!(!b.push_wkb(&wkb_le(1, &[0u8; 16])));
        let a = b.finish();
        assert_eq!(a.data_type(), &geometry_type(Kind::Areas));
        assert_eq!((a.len(), a.null_count()), (2, 1));
        let polys = a.as_list::<i32>().value(0);
        let rings = polys.as_list::<i32>().value(0);
        let c = rings.as_list::<i32>().value(0);
        let x = c
            .as_struct()
            .column(0)
            .as_primitive::<arrow_array::types::Float64Type>()
            .values()
            .to_vec();
        assert_eq!(x, vec![1.0, 3.0, 3.0, 1.0]);
    }

    #[test]
    fn big_endian_linestrings_and_multilinestrings_decode() {
        let mut be = vec![0u8];
        be.extend(2u32.to_be_bytes());
        be.extend(2u32.to_be_bytes());
        for v in [1.0f64, 2.0, 3.0, 4.0] {
            be.extend(v.to_be_bytes());
        }
        let mut multi = 2u32.to_le_bytes().to_vec();
        multi.extend(wkb_le(2, &pts_le(&[(0.0, 0.0), (1.0, 1.0)])));
        multi.extend(be.clone());
        let mut b = NativeBuilder::new(Kind::Lines);
        assert!(b.push_wkb(&be));
        assert!(b.push_wkb(&wkb_le(5, &multi)));
        let a = b.finish();
        assert_eq!(a.null_count(), 0);
        assert_eq!(a.as_list::<i32>().value(1).len(), 2);
    }

    #[test]
    fn truncated_trailing_and_z_blobs_are_refused() {
        let good = wkb_le(2, &pts_le(&[(0.0, 0.0), (1.0, 1.0)]));
        let mut b = NativeBuilder::new(Kind::Lines);
        assert!(!b.push_wkb(&good[..good.len() - 1]));
        let mut long = good.clone();
        long.push(0);
        assert!(!b.push_wkb(&long));
        assert!(!b.push_wkb(&wkb_le(1002, &pts_le(&[]))));
        assert!(!b.push_wkb(&[]));
        assert_eq!(b.finish().null_count(), 4);
    }
}