1use std::fmt;
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub struct PointAxis {
14 pub index: usize,
16 pub cartesian: &'static str,
18 pub geographic: &'static str,
20}
21
22impl PointAxis {
23 pub fn names(self, key: &str) -> bool {
25 key == self.cartesian || key == self.geographic
26 }
27
28 pub fn key(self, geographic: bool) -> &'static str {
30 if geographic {
31 self.geographic
32 } else {
33 self.cartesian
34 }
35 }
36}
37
38pub 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
57pub fn point_axis(key: &str) -> Option<PointAxis> {
59 POINT_AXES.into_iter().find(|axis| axis.names(key))
60}
61
62pub 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#[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
99pub fn is_geographic(srid: i32) -> bool {
101 srid_facts(srid).is_some_and(|facts| facts.geographic)
102}
103
104pub fn srid_dimension(srid: i32) -> Option<usize> {
107 srid_facts(srid).map(|facts| facts.dimension)
108}
109
110pub const LONGITUDE_MIN: f64 = -180.0;
113pub const LONGITUDE_MAX: f64 = 180.0;
115pub const LONGITUDE_TURN: f64 = LONGITUDE_MAX - LONGITUDE_MIN;
118pub const LATITUDE_MIN: f64 = -90.0;
121pub const LATITUDE_MAX: f64 = 90.0;
123
124pub fn wrap_longitude(longitude: f64) -> f64 {
133 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 if x == 0.0 {
147 0.0
148 } else {
149 x
150 }
151}
152
153#[derive(Clone, Copy, Debug, PartialEq, Eq)]
155pub enum PointDomainError {
156 InvalidLatitude,
158 NonFiniteCoordinate,
160 InvalidDimension { srid: i32 },
162}
163
164#[derive(Clone, Debug, PartialEq, Eq)]
169pub enum EwktError {
170 Grammar(String),
172 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
210pub 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
252pub 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
269pub 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
309fn 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 assert!(wrap_longitude(-360.0).is_sign_positive());
343 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}