11use crate :: Vector ;
22
3+ use num_traits:: { Float , Num } ;
4+ use std:: fmt;
5+
36/// A 2D point.
4- #[ derive( Debug , Clone , Copy , PartialEq , Default ) ]
5- pub struct Point {
7+ #[ derive( Debug , Clone , Copy , PartialEq , Eq , Default ) ]
8+ pub struct Point < T = f32 > {
69 /// The X coordinate.
7- pub x : f32 ,
10+ pub x : T ,
811
912 /// The Y coordinate.
10- pub y : f32 ,
13+ pub y : T ,
1114}
1215
1316impl Point {
1417 /// The origin (i.e. a [`Point`] at (0, 0)).
15- pub const ORIGIN : Point = Point :: new ( 0.0 , 0.0 ) ;
18+ pub const ORIGIN : Self = Self :: new ( 0.0 , 0.0 ) ;
19+ }
1620
21+ impl < T : Num > Point < T > {
1722 /// Creates a new [`Point`] with the given coordinates.
18- pub const fn new ( x : f32 , y : f32 ) -> Self {
23+ pub const fn new ( x : T , y : T ) -> Self {
1924 Self { x, y }
2025 }
2126
2227 /// Computes the distance to another [`Point`].
23- pub fn distance ( & self , to : Point ) -> f32 {
28+ pub fn distance ( & self , to : Self ) -> T
29+ where
30+ T : Float ,
31+ {
2432 let a = self . x - to. x ;
2533 let b = self . y - to. y ;
2634
@@ -34,9 +42,9 @@ impl From<[f32; 2]> for Point {
3442 }
3543}
3644
37- impl From < [ u16 ; 2 ] > for Point {
45+ impl From < [ u16 ; 2 ] > for Point < u16 > {
3846 fn from ( [ x, y] : [ u16 ; 2 ] ) -> Self {
39- Point :: new ( x. into ( ) , y. into ( ) )
47+ Point :: new ( x, y)
4048 }
4149}
4250
@@ -46,32 +54,50 @@ impl From<Point> for [f32; 2] {
4654 }
4755}
4856
49- impl std:: ops:: Add < Vector > for Point {
57+ impl < T > std:: ops:: Add < Vector < T > > for Point < T >
58+ where
59+ T : std:: ops:: Add < Output = T > ,
60+ {
5061 type Output = Self ;
5162
52- fn add ( self , vector : Vector ) -> Self {
63+ fn add ( self , vector : Vector < T > ) -> Self {
5364 Self {
5465 x : self . x + vector. x ,
5566 y : self . y + vector. y ,
5667 }
5768 }
5869}
5970
60- impl std:: ops:: Sub < Vector > for Point {
71+ impl < T > std:: ops:: Sub < Vector < T > > for Point < T >
72+ where
73+ T : std:: ops:: Sub < Output = T > ,
74+ {
6175 type Output = Self ;
6276
63- fn sub ( self , vector : Vector ) -> Self {
77+ fn sub ( self , vector : Vector < T > ) -> Self {
6478 Self {
6579 x : self . x - vector. x ,
6680 y : self . y - vector. y ,
6781 }
6882 }
6983}
7084
71- impl std:: ops:: Sub < Point > for Point {
72- type Output = Vector ;
85+ impl < T > std:: ops:: Sub < Point < T > > for Point < T >
86+ where
87+ T : std:: ops:: Sub < Output = T > ,
88+ {
89+ type Output = Vector < T > ;
7390
74- fn sub ( self , point : Point ) -> Vector {
91+ fn sub ( self , point : Self ) -> Vector < T > {
7592 Vector :: new ( self . x - point. x , self . y - point. y )
7693 }
7794}
95+
96+ impl < T > fmt:: Display for Point < T >
97+ where
98+ T : fmt:: Display ,
99+ {
100+ fn fmt ( & self , f : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
101+ write ! ( f, "Point {{ x: {}, y: {} }}" , self . x, self . y)
102+ }
103+ }
0 commit comments