Skip to main content

use_polyline/
lib.rs

1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4use use_distance::distance_2d;
5use use_point::Point2;
6
7/// An ordered 2D polyline.
8#[derive(Debug, Clone, PartialEq)]
9pub struct Polyline2 {
10    vertices: Vec<Point2>,
11}
12
13impl Polyline2 {
14    /// Creates a polyline from ordered vertices.
15    #[must_use]
16    pub const fn new(vertices: Vec<Point2>) -> Self {
17        Self { vertices }
18    }
19
20    /// Returns the vertices.
21    #[must_use]
22    pub fn vertices(&self) -> &[Point2] {
23        &self.vertices
24    }
25
26    /// Returns the number of vertices.
27    #[must_use]
28    pub fn len(&self) -> usize {
29        self.vertices.len()
30    }
31
32    /// Returns `true` when there are no vertices.
33    #[must_use]
34    pub fn is_empty(&self) -> bool {
35        self.vertices.is_empty()
36    }
37
38    /// Returns the total segment length.
39    #[must_use]
40    pub fn length(&self) -> f64 {
41        self.vertices
42            .windows(2)
43            .map(|pair| distance_2d(pair[0], pair[1]))
44            .sum()
45    }
46}
47
48#[cfg(test)]
49mod tests {
50    use super::Polyline2;
51    use use_point::Point2;
52
53    #[test]
54    fn computes_polyline_lengths() {
55        let polyline = Polyline2::new(vec![Point2::new(0.0, 0.0), Point2::new(3.0, 4.0)]);
56
57        assert_eq!(polyline.len(), 2);
58        assert!(!polyline.is_empty());
59        assert_eq!(polyline.length(), 5.0);
60    }
61}