lib_jsl_geometry/dim_1/
unit_vector1d.rs1use crate::common::{
4 CanNormalize, CoordinatePrimitive, DotProduct, GeometricPrimitive, GeometryMeasure,
5 HasDimension, HasNorm, IsUnitVector, Normalize,
6};
7use std::fmt::{self, Display, Formatter};
8use std::hash::{Hash, Hasher};
9use std::ops::{Index, IndexMut};
10
11#[derive(Debug, Clone, Copy, PartialEq)]
13#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
14pub struct UnitVector1D {
15 coord: GeometryMeasure,
16}
17
18impl Eq for UnitVector1D {}
19
20impl Hash for UnitVector1D {
21 fn hash<H: Hasher>(&self, state: &mut H) {
22 self.coord.to_bits().hash(state);
23 }
24}
25
26impl UnitVector1D {
27 pub fn new(x: GeometryMeasure) -> Self {
29 if x < 0.0 {
30 Self { coord: -1.0 }
31 } else {
32 Self { coord: 1.0 }
33 }
34 }
35}
36
37impl Display for UnitVector1D {
38 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
39 write!(f, "UnitVector1D({})", self.coord)
40 }
41}
42
43impl GeometricPrimitive for UnitVector1D {}
44impl CoordinatePrimitive for UnitVector1D {}
45impl IsUnitVector for UnitVector1D {}
46impl HasDimension for UnitVector1D {
47 const DIM: usize = 1;
48}
49
50impl AsRef<GeometryMeasure> for UnitVector1D {
51 fn as_ref(&self) -> &GeometryMeasure {
52 &self.coord
53 }
54}
55
56impl AsMut<GeometryMeasure> for UnitVector1D {
57 fn as_mut(&mut self) -> &mut GeometryMeasure {
58 &mut self.coord
59 }
60}
61
62impl Index<usize> for UnitVector1D {
63 type Output = GeometryMeasure;
64
65 fn index(&self, index: usize) -> &Self::Output {
66 match index {
67 0 => &self.coord,
68 _ => panic!("UnitVector1D index out of bounds: {}", index),
69 }
70 }
71}
72
73impl IndexMut<usize> for UnitVector1D {
74 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
75 match index {
76 0 => &mut self.coord,
77 _ => panic!("UnitVector1D index out of bounds: {}", index),
78 }
79 }
80}
81
82impl DotProduct for UnitVector1D {
83 type Output = GeometryMeasure;
84
85 fn dot(&self, rhs: &Self) -> <Self as DotProduct>::Output {
86 self.coord * rhs.coord
87 }
88}
89
90impl HasNorm for UnitVector1D {
91 fn norm(&self) -> GeometryMeasure {
92 1.0
93 }
94}
95
96impl Normalize for UnitVector1D {
97 fn normalized(&self) -> Self {
98 *self
99 }
100}
101
102impl CanNormalize for UnitVector1D {
103 fn normalize(&mut self) {
104 *self = Self::new(self.coord);
105 }
106}