Skip to main content

use_distance/
lib.rs

1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4//! Distance and interpolation helpers for 2D points.
5
6use use_point::Point2;
7
8/// Returns the Euclidean distance between two 2D points.
9#[must_use]
10pub fn distance_2d(left: Point2, right: Point2) -> f64 {
11    left.distance_to(right)
12}
13
14/// Returns the squared Euclidean distance between two 2D points.
15#[must_use]
16pub fn distance_squared_2d(left: Point2, right: Point2) -> f64 {
17    left.distance_squared_to(right)
18}
19
20/// Returns the midpoint between two 2D points.
21#[must_use]
22pub const fn midpoint_2d(left: Point2, right: Point2) -> Point2 {
23    left.midpoint(right)
24}
25
26#[cfg(test)]
27mod tests {
28    use super::{distance_2d, distance_squared_2d, midpoint_2d};
29    use use_point::Point2;
30
31    fn approx_eq(left: f64, right: f64) -> bool {
32        (left - right).abs() < 1.0e-10
33    }
34
35    #[test]
36    fn computes_distance() {
37        let left = Point2::new(0.0, 0.0);
38        let right = Point2::new(3.0, 4.0);
39
40        assert!(approx_eq(distance_2d(left, right), 5.0));
41    }
42
43    #[test]
44    fn computes_squared_distance() {
45        let left = Point2::new(-1.0, 2.0);
46        let right = Point2::new(2.0, 6.0);
47
48        assert!(approx_eq(distance_squared_2d(left, right), 25.0));
49    }
50
51    #[test]
52    fn computes_midpoints() {
53        let left = Point2::new(0.0, 0.0);
54        let right = Point2::new(4.0, 2.0);
55
56        assert_eq!(midpoint_2d(left, right), Point2::new(2.0, 1.0));
57    }
58}