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 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 if x == 0.0 {
130 0.0
131 } else {
132 x
133 }
134}
135
136#[derive(Clone, Copy, Debug, PartialEq, Eq)]
138pub enum PointDomainError {
139 InvalidLatitude,
141 NonFiniteCoordinate,
143 InvalidDimension { srid: i32 },
145}
146
147#[derive(Clone, Debug, PartialEq, Eq)]
152pub enum EwktError {
153 Grammar(String),
155 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
193pub 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
235pub 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
252pub 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
292fn 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 assert!(wrap_longitude(-360.0).is_sign_positive());
326 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}