use crate::error::GeometryError;
use crate::types3d::Coord3d;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Point3d(Coord3d);
impl Point3d {
#[inline]
pub fn new(coord: Coord3d) -> Result<Self, GeometryError> {
if !coord.x.is_finite() {
return Err(GeometryError::NonFiniteCoordinate {
coord_index: 0,
axis: 0,
});
}
if !coord.y.is_finite() {
return Err(GeometryError::NonFiniteCoordinate {
coord_index: 0,
axis: 1,
});
}
if !coord.z.is_finite() {
return Err(GeometryError::NonFiniteCoordinate {
coord_index: 0,
axis: 2,
});
}
Ok(Self(coord))
}
#[inline]
pub fn x(&self) -> f64 {
self.0.x
}
#[inline]
pub fn y(&self) -> f64 {
self.0.y
}
#[inline]
pub fn z(&self) -> f64 {
self.0.z
}
#[inline]
pub fn coord(&self) -> Coord3d {
self.0
}
}
impl TryFrom<Coord3d> for Point3d {
type Error = GeometryError;
#[inline]
fn try_from(coord: Coord3d) -> Result<Self, Self::Error> {
Self::new(coord)
}
}
impl From<Point3d> for Coord3d {
#[inline]
fn from(p: Point3d) -> Self {
p.0
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
#[allow(
clippy::float_cmp,
clippy::cast_possible_truncation,
clippy::cast_precision_loss,
clippy::cast_possible_wrap,
clippy::range_plus_one,
clippy::no_effect_underscore_binding
)]
mod tests {
use super::*;
#[test]
fn accessors_round_trip() {
let p = Point3d::new(Coord3d::new(1.0, 2.0, 3.0)).unwrap();
assert_eq!((p.x(), p.y(), p.z()), (1.0, 2.0, 3.0));
assert_eq!(p.coord(), Coord3d::new(1.0, 2.0, 3.0));
assert_eq!(Coord3d::from(p), Coord3d::new(1.0, 2.0, 3.0));
}
#[test]
fn extreme_but_finite_coordinates_are_accepted() {
assert!(Point3d::new(Coord3d::new(f64::MAX, f64::MIN, 0.0)).is_ok());
assert!(
Point3d::new(Coord3d::new(
f64::MIN_POSITIVE / 2.0,
-0.0,
f64::from_bits(1)
))
.is_ok()
);
}
#[test]
fn every_non_finite_component_is_rejected_with_its_axis() {
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
for (axis, coord) in [
(0u8, Coord3d::new(bad, 0.0, 0.0)),
(1, Coord3d::new(0.0, bad, 0.0)),
(2, Coord3d::new(0.0, 0.0, bad)),
] {
assert_eq!(
Point3d::new(coord).unwrap_err(),
GeometryError::NonFiniteCoordinate {
coord_index: 0,
axis
},
"{bad:?} on axis {axis} must be rejected"
);
}
}
}
#[test]
fn the_first_offending_axis_is_reported() {
assert_eq!(
Point3d::new(Coord3d::new(f64::NAN, f64::INFINITY, f64::NAN)).unwrap_err(),
GeometryError::NonFiniteCoordinate {
coord_index: 0,
axis: 0
}
);
assert_eq!(
Point3d::new(Coord3d::new(0.0, f64::NAN, f64::NAN)).unwrap_err(),
GeometryError::NonFiniteCoordinate {
coord_index: 0,
axis: 1
}
);
}
#[test]
fn try_from_matches_new() {
let c = Coord3d::new(1.0, 2.0, 3.0);
assert_eq!(Point3d::try_from(c), Point3d::new(c));
assert!(Point3d::try_from(Coord3d::new(f64::NAN, 2.0, 3.0)).is_err());
}
}