Skip to main content

relate_model/
point.rs

1//! The point axis vocabulary: the two spellings of each coordinate
2//! (`x`/`longitude`, `y`/`latitude`, `z`/`height`) and the geographic-SRID
3//! predicate. One home for the alias fact, consulted by the `point()` input
4//! readers, the component accessors and the wire encoder.
5
6use std::fmt;
7
8/// One point axis with both of its spellings: the cartesian name and the
9/// geographic name denote the same coordinate (`x` is `longitude`). The one
10/// alias vocabulary the `point()` input readers, the component accessors and
11/// the wire encoder consult, so the pairs are never spelled at a fourth site.
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub struct PointAxis {
14    /// The axis position: 0 = x/longitude, 1 = y/latitude, 2 = z/height.
15    pub index: usize,
16    /// The cartesian spelling.
17    pub cartesian: &'static str,
18    /// The geographic spelling.
19    pub geographic: &'static str,
20}
21
22impl PointAxis {
23    /// Whether `key` is either spelling of this axis.
24    pub fn names(self, key: &str) -> bool {
25        key == self.cartesian || key == self.geographic
26    }
27
28    /// The spelling this axis uses on a point of the given family.
29    pub fn key(self, geographic: bool) -> &'static str {
30        if geographic {
31            self.geographic
32        } else {
33            self.cartesian
34        }
35    }
36}
37
38/// The three point axes in x/y/z order.
39pub const POINT_AXES: [PointAxis; 3] = [
40    PointAxis {
41        index: 0,
42        cartesian: "x",
43        geographic: "longitude",
44    },
45    PointAxis {
46        index: 1,
47        cartesian: "y",
48        geographic: "latitude",
49    },
50    PointAxis {
51        index: 2,
52        cartesian: "z",
53        geographic: "height",
54    },
55];
56
57/// The axis a coordinate key names, or `None` for a non-coordinate key.
58pub fn point_axis(key: &str) -> Option<PointAxis> {
59    POINT_AXES.into_iter().find(|axis| axis.names(key))
60}
61
62/// The three coordinate key spellings a point of the given family uses.
63pub fn point_axis_keys(geographic: bool) -> [&'static str; 3] {
64    [
65        POINT_AXES[0].key(geographic),
66        POINT_AXES[1].key(geographic),
67        POINT_AXES[2].key(geographic),
68    ]
69}
70
71/// The four `point()` SRIDs' fixed facts — their dimension (2 or 3) and
72/// whether they are geographic — one row each. `None` for any other SRID (a
73/// wire decoder can carry one; `point()` cannot).
74///
75/// This is the one dimension/axis-family table: [`is_geographic`],
76/// [`srid_dimension`], `PointValue::crs_name`'s dimensionality check and the
77/// executor's `Srid` family/dimension all derive from it, so a fifth code or
78/// a corrected dimension lands in exactly one place.
79#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80struct SridFacts {
81    dimension: usize,
82    geographic: bool,
83}
84
85fn srid_facts(srid: i32) -> Option<SridFacts> {
86    let (dimension, geographic) = match srid {
87        7203 => (2, false),
88        4326 => (2, true),
89        9157 => (3, false),
90        4979 => (3, true),
91        _ => return None,
92    };
93    Some(SridFacts {
94        dimension,
95        geographic,
96    })
97}
98
99/// Whether an SRID is geographic (longitude/latitude keys, `wgs-84*` CRS).
100pub fn is_geographic(srid: i32) -> bool {
101    srid_facts(srid).is_some_and(|facts| facts.geographic)
102}
103
104/// The dimension one of the four `point()` SRIDs fixes (`2` or `3`), or
105/// `None` for any other SRID.
106pub fn srid_dimension(srid: i32) -> Option<usize> {
107    srid_facts(srid).map(|facts| facts.dimension)
108}
109
110/// Neo4j's longitude wrap into `[-180, 180]`, keeping both endpoints
111/// (180.0 → 180.0, -180.0 → -180.0, 180.5 → -179.5, -200.0 → 160.0,
112/// -540.0 → -180.0). This is the stored geographic-longitude domain for
113/// the producers that uphold it — the engine's `point()` constructor and
114/// the Query API typed decoders — so the POINT index's envelope clip
115/// (which assumes the domain) and the residual scan cannot disagree
116/// (LABS-1236). Bolt point parameters are stored bit-for-bit instead, by
117/// ADR-0177 §2.
118pub fn wrap_longitude(longitude: f64) -> f64 {
119    let mut x = longitude;
120    if !(-180.0..=180.0).contains(&x) {
121        x %= 360.0;
122        if x > 180.0 {
123            x -= 360.0;
124        } else if x < -180.0 {
125            x += 360.0;
126        }
127    }
128    // Normalize -0.0 (from -360 % 360) to +0.0.
129    if x == 0.0 {
130        0.0
131    } else {
132        x
133    }
134}
135
136/// Why a coordinate triple is not a storable point.
137#[derive(Clone, Copy, Debug, PartialEq, Eq)]
138pub enum PointDomainError {
139    /// A geographic point's latitude is outside `[-90, 90]`.
140    InvalidLatitude,
141    /// A coordinate is not finite.
142    NonFiniteCoordinate,
143    /// The coordinate count disagrees with the SRID's fixed dimension.
144    InvalidDimension { srid: i32 },
145}
146
147/// Why an EWKT string was refused: the text does not match the grammar, or
148/// it does and the coordinates are outside the stored domain. One typed
149/// error so a caller can tell the two halves apart; `Display` is the text
150/// every surface already shows.
151#[derive(Clone, Debug, PartialEq, Eq)]
152pub enum EwktError {
153    /// The text does not match the EWKT grammar.
154    Grammar(String),
155    /// The coordinates are outside the stored domain.
156    Domain(PointDomainError),
157}
158
159impl fmt::Display for PointDomainError {
160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161        match self {
162            PointDomainError::InvalidLatitude => {
163                f.write_str("latitude must be in the range [-90, 90]")
164            }
165            PointDomainError::NonFiniteCoordinate => f.write_str("a coordinate is not finite"),
166            PointDomainError::InvalidDimension { srid } => {
167                write!(f, "SRID={srid} does not match the coordinate dimension")
168            }
169        }
170    }
171}
172
173impl std::error::Error for PointDomainError {}
174
175impl fmt::Display for EwktError {
176    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177        match self {
178            EwktError::Grammar(detail) => f.write_str(detail),
179            EwktError::Domain(err) => err.fmt(f),
180        }
181    }
182}
183
184impl std::error::Error for EwktError {
185    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
186        match self {
187            EwktError::Grammar(_) => None,
188            EwktError::Domain(err) => Some(err),
189        }
190    }
191}
192
193/// The one stored-domain rule every point producer shares (the `point()`
194/// constructor and every wire decoder): a geographic point's longitude wraps
195/// into `[-180, 180]` by [`wrap_longitude`] and its latitude must already be
196/// in `[-90, 90]`; a cartesian point is stored as given. Keeping it here is
197/// what stops a decoder admitting a point the constructor refuses.
198///
199/// The **SRID** is the one discriminator, never the coordinate-key family:
200/// a `point({x, y, srid: 4326})` map and a decoded `SRID=4326` WKT are the
201/// same value, so they must pass the same rule (Neo4j validates by SRID too).
202/// The key family only decides which keys the map reader accepts. The whole
203/// domain lives here — finiteness, the SRID's dimension, and the geographic
204/// longitude/latitude rule — so every producer inherits it.
205pub fn stored_point(
206    srid: i32,
207    x: f64,
208    y: f64,
209    z: Option<f64>,
210) -> Result<crate::value::PointValue, PointDomainError> {
211    if !x.is_finite() || !y.is_finite() || z.is_some_and(|z| !z.is_finite()) {
212        return Err(PointDomainError::NonFiniteCoordinate);
213    }
214    if let Some(dimension) = srid_dimension(srid) {
215        let actual = if z.is_some() { 3 } else { 2 };
216        if actual != dimension {
217            return Err(PointDomainError::InvalidDimension { srid });
218        }
219    }
220    if is_geographic(srid) {
221        if !(-90.0..=90.0).contains(&y) {
222            return Err(PointDomainError::InvalidLatitude);
223        }
224        Ok(crate::value::PointValue {
225            srid,
226            x: wrap_longitude(x),
227            y,
228            z,
229        })
230    } else {
231        Ok(crate::value::PointValue { srid, x, y, z })
232    }
233}
234
235/// The Query API's EWKT spelling of a point (ADR-0181 item 5) —
236/// `SRID=7203;POINT (1.0 2.0)` or `SRID=4979;POINT Z (12.5 55.7 10.0)`.
237/// Beside [`parse_ewkt`], the one grammar's two halves.
238pub fn ewkt(p: &crate::value::PointValue) -> String {
239    let text = crate::value::float_text;
240    match p.z {
241        Some(z) => format!(
242            "SRID={};POINT Z ({} {} {})",
243            p.srid,
244            text(p.x),
245            text(p.y),
246            text(z)
247        ),
248        None => format!("SRID={};POINT ({} {})", p.srid, text(p.x), text(p.y)),
249    }
250}
251
252/// Parse the Query API's EWKT point text into a stored point (ADR-0181
253/// item 5): `SRID=<i32>;POINT (<x> <y>)` or `SRID=<i32>;POINT Z (<x> <y>
254/// <z>)`, anything else refused. One grammar for every Query API surface
255/// that reads a point back (the typed wire decoder and the HTTP request
256/// fold), so the accepted shapes cannot drift; the stored domain is
257/// [`stored_point`]'s rule and coordinates must be finite.
258pub fn parse_ewkt(text: &str) -> Result<crate::value::PointValue, EwktError> {
259    let (srid, rest) = text
260        .strip_prefix("SRID=")
261        .and_then(|rest| rest.split_once(';'))
262        .ok_or_else(|| EwktError::Grammar(format!("{text:?} is not \"SRID=<i32>;POINT (…)\"")))?;
263    let srid: i32 = srid
264        .parse()
265        .map_err(|_| EwktError::Grammar(format!("{srid:?} is not an i32 SRID")))?;
266    let (three_d, inner) = if let Some(inner) = rest.strip_prefix("POINT Z (") {
267        (true, inner)
268    } else if let Some(inner) = rest.strip_prefix("POINT (") {
269        (false, inner)
270    } else {
271        return Err(EwktError::Grammar(format!(
272            "{rest:?} is not \"POINT (…)\" or \"POINT Z (…)\""
273        )));
274    };
275    let inner = inner
276        .strip_suffix(')')
277        .ok_or_else(|| EwktError::Grammar("missing the closing \")\"".to_string()))?;
278    let coords: Vec<&str> = inner.split_whitespace().collect();
279    let expected = if three_d { 3 } else { 2 };
280    if coords.len() != expected {
281        return Err(EwktError::Grammar(format!(
282            "expected {expected} coordinates, found {}",
283            coords.len()
284        )));
285    }
286    let x = coordinate(coords[0])?;
287    let y = coordinate(coords[1])?;
288    let z = coords.get(2).map(|z| coordinate(z)).transpose()?;
289    stored_point(srid, x, y, z).map_err(EwktError::Domain)
290}
291
292/// One point coordinate: a finite decimal (`NaN`/`Infinity` parse as
293/// floats but no point envelope contains them).
294fn coordinate(token: &str) -> Result<f64, EwktError> {
295    let value: f64 = token
296        .parse()
297        .map_err(|_| EwktError::Grammar(format!("{token:?} is not a decimal coordinate")))?;
298    if !value.is_finite() {
299        return Err(EwktError::Grammar(format!(
300            "{token:?} is not a finite coordinate"
301        )));
302    }
303    Ok(value)
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309
310    #[test]
311    fn longitude_wraps_into_the_stored_domain() {
312        for (longitude, wrapped) in [
313            (0.0, 0.0),
314            (180.0, 180.0),
315            (-180.0, -180.0),
316            (180.5, -179.5),
317            (-200.0, 160.0),
318            (370.0, 10.0),
319            (-540.0, -180.0),
320            (540.0, 180.0),
321        ] {
322            assert_eq!(wrap_longitude(longitude), wrapped, "{longitude}");
323        }
324        // -360 % 360 is -0.0; the wrap normalizes it to +0.0.
325        assert!(wrap_longitude(-360.0).is_sign_positive());
326        // Extreme longitudes stay finite and in range.
327        for longitude in [1e30, -1e30, 1e300, -1e300, f64::MAX, -f64::MAX] {
328            let wrapped = wrap_longitude(longitude);
329            assert!(
330                wrapped.is_finite() && (-180.0..=180.0).contains(&wrapped),
331                "longitude {longitude} wrapped to {wrapped}"
332            );
333        }
334    }
335}