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/// The stored geographic-longitude domain's lower bound, as `point()`
111/// validates it — the one home the bounds and one turn derive from.
112pub const LONGITUDE_MIN: f64 = -180.0;
113/// The stored geographic-longitude domain's upper bound.
114pub const LONGITUDE_MAX: f64 = 180.0;
115/// One full turn of [`LONGITUDE_MIN`]..[`LONGITUDE_MAX`] — the shift a
116/// wrapping band takes into the unwrapped frame.
117pub const LONGITUDE_TURN: f64 = LONGITUDE_MAX - LONGITUDE_MIN;
118/// The stored geographic-latitude domain's lower bound, as `point()`
119/// validates it.
120pub const LATITUDE_MIN: f64 = -90.0;
121/// The stored geographic-latitude domain's upper bound.
122pub const LATITUDE_MAX: f64 = 90.0;
123
124/// Neo4j's longitude wrap into `[LONGITUDE_MIN, LONGITUDE_MAX]`, keeping
125/// both endpoints (180.0 → 180.0, -180.0 → -180.0, 180.5 → -179.5,
126/// -200.0 → 160.0, -540.0 → -180.0). This is the stored
127/// geographic-longitude domain for the producers that uphold it — the
128/// engine's `point()` constructor and the Query API typed decoders — so the
129/// POINT index's envelope clip (which assumes the domain) and the residual
130/// scan cannot disagree (LABS-1236). Bolt point parameters are stored
131/// bit-for-bit instead, by ADR-0177 §2.
132pub fn wrap_longitude(longitude: f64) -> f64 {
133    // One pipeline over the domain constants: the remainder lands in
134    // (-360, 360), and the endpoint ladder folds the two half-turns
135    // outside the domain back onto it. In-domain values take the
136    // remainder untouched (fmod keeps them bit-identical).
137    let x = longitude % LONGITUDE_TURN;
138    let x = if x > LONGITUDE_MAX {
139        x - LONGITUDE_TURN
140    } else if x < LONGITUDE_MIN {
141        x + LONGITUDE_TURN
142    } else {
143        x
144    };
145    // Normalize -0.0 (from -360 % 360) to +0.0.
146    if x == 0.0 {
147        0.0
148    } else {
149        x
150    }
151}
152
153/// Why a coordinate triple is not a storable point.
154#[derive(Clone, Copy, Debug, PartialEq, Eq)]
155pub enum PointDomainError {
156    /// A geographic point's latitude is outside `[-90, 90]`.
157    InvalidLatitude,
158    /// A coordinate is not finite.
159    NonFiniteCoordinate,
160    /// The coordinate count disagrees with the SRID's fixed dimension.
161    InvalidDimension { srid: i32 },
162}
163
164/// Why an EWKT string was refused: the text does not match the grammar, or
165/// it does and the coordinates are outside the stored domain. One typed
166/// error so a caller can tell the two halves apart; `Display` is the text
167/// every surface already shows.
168#[derive(Clone, Debug, PartialEq, Eq)]
169pub enum EwktError {
170    /// The text does not match the EWKT grammar.
171    Grammar(String),
172    /// The coordinates are outside the stored domain.
173    Domain(PointDomainError),
174}
175
176impl fmt::Display for PointDomainError {
177    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178        match self {
179            PointDomainError::InvalidLatitude => {
180                f.write_str("latitude must be in the range [-90, 90]")
181            }
182            PointDomainError::NonFiniteCoordinate => f.write_str("a coordinate is not finite"),
183            PointDomainError::InvalidDimension { srid } => {
184                write!(f, "SRID={srid} does not match the coordinate dimension")
185            }
186        }
187    }
188}
189
190impl std::error::Error for PointDomainError {}
191
192impl fmt::Display for EwktError {
193    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194        match self {
195            EwktError::Grammar(detail) => f.write_str(detail),
196            EwktError::Domain(err) => err.fmt(f),
197        }
198    }
199}
200
201impl std::error::Error for EwktError {
202    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
203        match self {
204            EwktError::Grammar(_) => None,
205            EwktError::Domain(err) => Some(err),
206        }
207    }
208}
209
210/// The one stored-domain rule every point producer shares (the `point()`
211/// constructor and every wire decoder): a geographic point's longitude wraps
212/// into `[-180, 180]` by [`wrap_longitude`] and its latitude must already be
213/// in `[-90, 90]`; a cartesian point is stored as given. Keeping it here is
214/// what stops a decoder admitting a point the constructor refuses.
215///
216/// The **SRID** is the one discriminator, never the coordinate-key family:
217/// a `point({x, y, srid: 4326})` map and a decoded `SRID=4326` WKT are the
218/// same value, so they must pass the same rule (Neo4j validates by SRID too).
219/// The key family only decides which keys the map reader accepts. The whole
220/// domain lives here — finiteness, the SRID's dimension, and the geographic
221/// longitude/latitude rule — so every producer inherits it.
222pub fn stored_point(
223    srid: i32,
224    x: f64,
225    y: f64,
226    z: Option<f64>,
227) -> Result<crate::value::PointValue, PointDomainError> {
228    if !x.is_finite() || !y.is_finite() || z.is_some_and(|z| !z.is_finite()) {
229        return Err(PointDomainError::NonFiniteCoordinate);
230    }
231    if let Some(dimension) = srid_dimension(srid) {
232        let actual = if z.is_some() { 3 } else { 2 };
233        if actual != dimension {
234            return Err(PointDomainError::InvalidDimension { srid });
235        }
236    }
237    if is_geographic(srid) {
238        if !(LATITUDE_MIN..=LATITUDE_MAX).contains(&y) {
239            return Err(PointDomainError::InvalidLatitude);
240        }
241        Ok(crate::value::PointValue {
242            srid,
243            x: wrap_longitude(x),
244            y,
245            z,
246        })
247    } else {
248        Ok(crate::value::PointValue { srid, x, y, z })
249    }
250}
251
252/// The Query API's EWKT spelling of a point (ADR-0181 item 5) —
253/// `SRID=7203;POINT (1.0 2.0)` or `SRID=4979;POINT Z (12.5 55.7 10.0)`.
254/// Beside [`parse_ewkt`], the one grammar's two halves.
255pub fn ewkt(p: &crate::value::PointValue) -> String {
256    let text = crate::value::float_text;
257    match p.z {
258        Some(z) => format!(
259            "SRID={};POINT Z ({} {} {})",
260            p.srid,
261            text(p.x),
262            text(p.y),
263            text(z)
264        ),
265        None => format!("SRID={};POINT ({} {})", p.srid, text(p.x), text(p.y)),
266    }
267}
268
269/// Parse the Query API's EWKT point text into a stored point (ADR-0181
270/// item 5): `SRID=<i32>;POINT (<x> <y>)` or `SRID=<i32>;POINT Z (<x> <y>
271/// <z>)`, anything else refused. One grammar for every Query API surface
272/// that reads a point back (the typed wire decoder and the HTTP request
273/// fold), so the accepted shapes cannot drift; the stored domain is
274/// [`stored_point`]'s rule and coordinates must be finite.
275pub fn parse_ewkt(text: &str) -> Result<crate::value::PointValue, EwktError> {
276    let (srid, rest) = text
277        .strip_prefix("SRID=")
278        .and_then(|rest| rest.split_once(';'))
279        .ok_or_else(|| EwktError::Grammar(format!("{text:?} is not \"SRID=<i32>;POINT (…)\"")))?;
280    let srid: i32 = srid
281        .parse()
282        .map_err(|_| EwktError::Grammar(format!("{srid:?} is not an i32 SRID")))?;
283    let (three_d, inner) = if let Some(inner) = rest.strip_prefix("POINT Z (") {
284        (true, inner)
285    } else if let Some(inner) = rest.strip_prefix("POINT (") {
286        (false, inner)
287    } else {
288        return Err(EwktError::Grammar(format!(
289            "{rest:?} is not \"POINT (…)\" or \"POINT Z (…)\""
290        )));
291    };
292    let inner = inner
293        .strip_suffix(')')
294        .ok_or_else(|| EwktError::Grammar("missing the closing \")\"".to_string()))?;
295    let coords: Vec<&str> = inner.split_whitespace().collect();
296    let expected = if three_d { 3 } else { 2 };
297    if coords.len() != expected {
298        return Err(EwktError::Grammar(format!(
299            "expected {expected} coordinates, found {}",
300            coords.len()
301        )));
302    }
303    let x = coordinate(coords[0])?;
304    let y = coordinate(coords[1])?;
305    let z = coords.get(2).map(|z| coordinate(z)).transpose()?;
306    stored_point(srid, x, y, z).map_err(EwktError::Domain)
307}
308
309/// One point coordinate: a finite decimal (`NaN`/`Infinity` parse as
310/// floats but no point envelope contains them).
311fn coordinate(token: &str) -> Result<f64, EwktError> {
312    let value: f64 = token
313        .parse()
314        .map_err(|_| EwktError::Grammar(format!("{token:?} is not a decimal coordinate")))?;
315    if !value.is_finite() {
316        return Err(EwktError::Grammar(format!(
317            "{token:?} is not a finite coordinate"
318        )));
319    }
320    Ok(value)
321}
322
323#[cfg(test)]
324mod tests {
325    use super::*;
326
327    #[test]
328    fn longitude_wraps_into_the_stored_domain() {
329        for (longitude, wrapped) in [
330            (0.0, 0.0),
331            (180.0, 180.0),
332            (-180.0, -180.0),
333            (180.5, -179.5),
334            (-200.0, 160.0),
335            (370.0, 10.0),
336            (-540.0, -180.0),
337            (540.0, 180.0),
338        ] {
339            assert_eq!(wrap_longitude(longitude), wrapped, "{longitude}");
340        }
341        // -360 % 360 is -0.0; the wrap normalizes it to +0.0.
342        assert!(wrap_longitude(-360.0).is_sign_positive());
343        // Extreme longitudes stay finite and in range.
344        for longitude in [1e30, -1e30, 1e300, -1e300, f64::MAX, -f64::MAX] {
345            let wrapped = wrap_longitude(longitude);
346            assert!(
347                wrapped.is_finite() && (-180.0..=180.0).contains(&wrapped),
348                "longitude {longitude} wrapped to {wrapped}"
349            );
350        }
351    }
352}