picea/math/
segment.rs

1use std::{
2    mem,
3    ops::{Add, Neg, Sub},
4};
5
6use super::{point::Point, vector::Vector, FloatNum};
7
8pub type Axis<T> = Segment<T>;
9
10#[derive(Clone)]
11pub struct Segment<T: Clone + Copy = FloatNum> {
12    start_point: Point<T>,
13    end_point: Point<T>,
14}
15
16impl<T: Clone + Copy> Segment<T> {
17    pub fn new(start_point: Point<T>, end_point: Point<T>) -> Self {
18        Self {
19            start_point,
20            end_point,
21        }
22    }
23
24    pub fn start_point(&self) -> &Point<T> {
25        &self.start_point
26    }
27
28    pub fn start_point_mut(&mut self) -> &mut Point<T> {
29        &mut self.start_point
30    }
31
32    pub fn end_point(&self) -> &Point<T> {
33        &self.end_point
34    }
35
36    pub fn end_point_mut(&mut self) -> &mut Point<T> {
37        &mut self.end_point
38    }
39
40    pub fn flip(&self) -> Segment<T> {
41        (self.end_point, self.start_point).into()
42    }
43
44    pub fn flip_mut(&mut self) {
45        mem::swap(&mut self.end_point, &mut self.start_point);
46    }
47
48    pub fn ends(&self) -> (&Point<T>, &Point<T>) {
49        (&self.start_point, &self.end_point)
50    }
51
52    pub fn ends_mut(&mut self) -> (&mut Point<T>, &mut Point<T>) {
53        (&mut self.start_point, &mut self.end_point)
54    }
55}
56
57impl<T: Clone + Copy> Segment<T>
58where
59    T: Neg<Output = T> + Sub<Output = T>,
60{
61    pub fn to_vector(&self) -> Vector<T> {
62        (self.start_point, self.end_point).into()
63    }
64}
65
66impl<T: Clone + Copy> From<(Point<T>, Point<T>)> for Segment<T> {
67    fn from((start_point, end_point): (Point<T>, Point<T>)) -> Self {
68        Segment {
69            start_point,
70            end_point,
71        }
72    }
73}
74
75impl<T> Add<&Vector<T>> for &Segment<T>
76where
77    T: Add<Output = T> + Clone + Copy,
78{
79    type Output = Segment<T>;
80    fn add(self, rhs: &Vector<T>) -> Self::Output {
81        Segment::new(self.start_point + rhs, self.end_point + rhs)
82    }
83}