Make DistanceAlg copyable
@@ -2,12 +2,13 @@ use crate::prelude::{Point, Point3};
use std::cmp::{max, min};
/// Enumeration of available 2D Distance algorithms
+#[derive(Clone, Copy)]
pub enum DistanceAlg {
Pythagoras,
PythagorasSquared,
Manhattan,
Chebyshev,
- Diagonal
+ Diagonal,
}
impl DistanceAlg {
@@ -18,7 +19,7 @@ impl DistanceAlg {
DistanceAlg::PythagorasSquared => distance2d_pythagoras_squared(start, end),
DistanceAlg::Manhattan => distance2d_manhattan(start, end),
DistanceAlg::Chebyshev => distance2d_chebyshev(start, end),
- DistanceAlg::Diagonal => distance2d_diagonal(start, end)
+ DistanceAlg::Diagonal => distance2d_diagonal(start, end),
}
}
/// Provides a 3D distance between points, using the specified algorithm.
@@ -28,7 +29,7 @@ impl DistanceAlg {
DistanceAlg::PythagorasSquared => distance3d_pythagoras_squared(start, end),
DistanceAlg::Manhattan => distance3d_manhattan(start, end),
DistanceAlg::Chebyshev => distance3d_pythagoras(start, end),
- DistanceAlg::Diagonal => distance3d_diagonal(start, end)
+ DistanceAlg::Diagonal => distance3d_diagonal(start, end),
}
}
}
@@ -89,19 +90,13 @@ fn distance3d_pythagoras(start: Point3, end: Point3) -> f32 {
// Calculates a diagonal distance
fn distance2d_diagonal(start: Point, end: Point) -> f32 {
- i32::max(
- (start.x - end.x).abs(),
- (start.y - end.y).abs()
- ) as f32
+ i32::max((start.x - end.x).abs(), (start.y - end.y).abs()) as f32
}
fn distance3d_diagonal(start: Point3, end: Point3) -> f32 {
i32::max(
(start.x - end.x).abs(),
- i32::max(
- (start.y - end.y).abs(),
- (start.z - end.z).abs()
- )
+ i32::max((start.y - end.y).abs(), (start.z - end.z).abs()),
) as f32
}
@@ -217,4 +212,19 @@ mod tests {
d = DistanceAlg::Chebyshev.distance2d(Point::new(0, 0), Point::new(5, 5));
assert!(f32::abs(d - 5.0) < std::f32::EPSILON);
}
+
+ #[test]
+ fn test_algorithm_from_shared_reference() {
+ let mut algorithm = DistanceAlg::Chebyshev;
+ let mut d = algorithm.distance2d(Point::new(0, 0), Point::new(5, 5));
+ assert!(f32::abs(d - 5.0) < std::f32::EPSILON);
+
+ algorithm = DistanceAlg::Manhattan;
+ d = algorithm.distance2d(Point::new(0, 0), Point::new(5, 5));
+ assert!(f32::abs(d - 10.0) < std::f32::EPSILON);
+
+ let shared_ref = &algorithm;
+ d = shared_ref.distance2d(Point::new(0, 0), Point::new(5, 5));
+ assert!(f32::abs(d - 10.0) < std::f32::EPSILON);
+ }
}
