#[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),
]
}
pub fn is_geographic(srid: i32) -> bool {
matches!(srid, 4326 | 4979)
}
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
}
}
#[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}"
);
}
}
}