use std::fmt;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PointAxis {
pub index: usize,
pub cartesian: &'static str,
pub geographic: &'static str,
}
impl PointAxis {
pub fn names(self, key: &str) -> bool {
key == self.cartesian || key == self.geographic
}
pub fn key(self, geographic: bool) -> &'static str {
if geographic {
self.geographic
} else {
self.cartesian
}
}
}
pub const POINT_AXES: [PointAxis; 3] = [
PointAxis {
index: 0,
cartesian: "x",
geographic: "longitude",
},
PointAxis {
index: 1,
cartesian: "y",
geographic: "latitude",
},
PointAxis {
index: 2,
cartesian: "z",
geographic: "height",
},
];
pub fn point_axis(key: &str) -> Option<PointAxis> {
POINT_AXES.into_iter().find(|axis| axis.names(key))
}
pub fn point_axis_keys(geographic: bool) -> [&'static str; 3] {
[
POINT_AXES[0].key(geographic),
POINT_AXES[1].key(geographic),
POINT_AXES[2].key(geographic),
]
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct SridFacts {
dimension: usize,
geographic: bool,
}
fn srid_facts(srid: i32) -> Option<SridFacts> {
let (dimension, geographic) = match srid {
7203 => (2, false),
4326 => (2, true),
9157 => (3, false),
4979 => (3, true),
_ => return None,
};
Some(SridFacts {
dimension,
geographic,
})
}
pub fn is_geographic(srid: i32) -> bool {
srid_facts(srid).is_some_and(|facts| facts.geographic)
}
pub fn srid_dimension(srid: i32) -> Option<usize> {
srid_facts(srid).map(|facts| facts.dimension)
}
pub fn wrap_longitude(longitude: f64) -> f64 {
let mut x = longitude;
if !(-180.0..=180.0).contains(&x) {
x %= 360.0;
if x > 180.0 {
x -= 360.0;
} else if x < -180.0 {
x += 360.0;
}
}
if x == 0.0 {
0.0
} else {
x
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PointDomainError {
InvalidLatitude,
NonFiniteCoordinate,
InvalidDimension { srid: i32 },
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EwktError {
Grammar(String),
Domain(PointDomainError),
}
impl fmt::Display for PointDomainError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PointDomainError::InvalidLatitude => {
f.write_str("latitude must be in the range [-90, 90]")
}
PointDomainError::NonFiniteCoordinate => f.write_str("a coordinate is not finite"),
PointDomainError::InvalidDimension { srid } => {
write!(f, "SRID={srid} does not match the coordinate dimension")
}
}
}
}
impl std::error::Error for PointDomainError {}
impl fmt::Display for EwktError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
EwktError::Grammar(detail) => f.write_str(detail),
EwktError::Domain(err) => err.fmt(f),
}
}
}
impl std::error::Error for EwktError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
EwktError::Grammar(_) => None,
EwktError::Domain(err) => Some(err),
}
}
}
pub fn stored_point(
srid: i32,
x: f64,
y: f64,
z: Option<f64>,
) -> Result<crate::value::PointValue, PointDomainError> {
if !x.is_finite() || !y.is_finite() || z.is_some_and(|z| !z.is_finite()) {
return Err(PointDomainError::NonFiniteCoordinate);
}
if let Some(dimension) = srid_dimension(srid) {
let actual = if z.is_some() { 3 } else { 2 };
if actual != dimension {
return Err(PointDomainError::InvalidDimension { srid });
}
}
if is_geographic(srid) {
if !(-90.0..=90.0).contains(&y) {
return Err(PointDomainError::InvalidLatitude);
}
Ok(crate::value::PointValue {
srid,
x: wrap_longitude(x),
y,
z,
})
} else {
Ok(crate::value::PointValue { srid, x, y, z })
}
}
pub fn ewkt(p: &crate::value::PointValue) -> String {
let text = crate::value::float_text;
match p.z {
Some(z) => format!(
"SRID={};POINT Z ({} {} {})",
p.srid,
text(p.x),
text(p.y),
text(z)
),
None => format!("SRID={};POINT ({} {})", p.srid, text(p.x), text(p.y)),
}
}
pub fn parse_ewkt(text: &str) -> Result<crate::value::PointValue, EwktError> {
let (srid, rest) = text
.strip_prefix("SRID=")
.and_then(|rest| rest.split_once(';'))
.ok_or_else(|| EwktError::Grammar(format!("{text:?} is not \"SRID=<i32>;POINT (…)\"")))?;
let srid: i32 = srid
.parse()
.map_err(|_| EwktError::Grammar(format!("{srid:?} is not an i32 SRID")))?;
let (three_d, inner) = if let Some(inner) = rest.strip_prefix("POINT Z (") {
(true, inner)
} else if let Some(inner) = rest.strip_prefix("POINT (") {
(false, inner)
} else {
return Err(EwktError::Grammar(format!(
"{rest:?} is not \"POINT (…)\" or \"POINT Z (…)\""
)));
};
let inner = inner
.strip_suffix(')')
.ok_or_else(|| EwktError::Grammar("missing the closing \")\"".to_string()))?;
let coords: Vec<&str> = inner.split_whitespace().collect();
let expected = if three_d { 3 } else { 2 };
if coords.len() != expected {
return Err(EwktError::Grammar(format!(
"expected {expected} coordinates, found {}",
coords.len()
)));
}
let x = coordinate(coords[0])?;
let y = coordinate(coords[1])?;
let z = coords.get(2).map(|z| coordinate(z)).transpose()?;
stored_point(srid, x, y, z).map_err(EwktError::Domain)
}
fn coordinate(token: &str) -> Result<f64, EwktError> {
let value: f64 = token
.parse()
.map_err(|_| EwktError::Grammar(format!("{token:?} is not a decimal coordinate")))?;
if !value.is_finite() {
return Err(EwktError::Grammar(format!(
"{token:?} is not a finite coordinate"
)));
}
Ok(value)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn longitude_wraps_into_the_stored_domain() {
for (longitude, wrapped) in [
(0.0, 0.0),
(180.0, 180.0),
(-180.0, -180.0),
(180.5, -179.5),
(-200.0, 160.0),
(370.0, 10.0),
(-540.0, -180.0),
(540.0, 180.0),
] {
assert_eq!(wrap_longitude(longitude), wrapped, "{longitude}");
}
assert!(wrap_longitude(-360.0).is_sign_positive());
for longitude in [1e30, -1e30, 1e300, -1e300, f64::MAX, -f64::MAX] {
let wrapped = wrap_longitude(longitude);
assert!(
wrapped.is_finite() && (-180.0..=180.0).contains(&wrapped),
"longitude {longitude} wrapped to {wrapped}"
);
}
}
}