Skip to content

Commit fb4a5ac

Browse files
committed
Add Sqrt trait and Vec2::length
1 parent 4f353af commit fb4a5ac

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

lighthouse-protocol/src/utils/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ mod direction;
33
mod rect;
44
mod rem_euclid;
55
mod rotation;
6+
mod sqrt;
67
mod unity;
78
mod vec2;
89
mod zero;
@@ -12,6 +13,7 @@ pub use direction::*;
1213
pub use rect::*;
1314
pub use rem_euclid::*;
1415
pub use rotation::*;
16+
pub use sqrt::*;
1517
pub use unity::*;
1618
pub use vec2::*;
1719
pub use zero::*;
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/// A type whose values have a square root.
2+
pub trait Sqrt {
3+
/// The square root.
4+
fn sqrt(self) -> Self;
5+
}
6+
7+
macro_rules! impl_sqrt {
8+
($($tys:ty),*) => {
9+
$(impl Sqrt for $tys {
10+
fn sqrt(self) -> Self {
11+
<$tys>::sqrt(self)
12+
}
13+
})*
14+
};
15+
}
16+
17+
impl_sqrt!(
18+
f32, f64
19+
);

lighthouse-protocol/src/utils/vec2.rs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
use std::{fmt, ops::{Add, AddAssign, Neg, Sub, SubAssign}};
1+
use std::{fmt, ops::{Add, AddAssign, Mul, Neg, Sub, SubAssign}};
22

33
use rand::{thread_rng, Rng};
44
use serde::{Deserialize, Serialize};
55

6-
use super::{Unity, Zero};
6+
use super::{Sqrt, Unity, Zero};
77

88
/// A 2D vector.
99
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -59,6 +59,13 @@ impl<T> Vec2<T> where T: Zero + Unity {
5959
}
6060
}
6161

62+
impl<T> Vec2<T> where T: Add<Output = T> + Mul<Output = T> + Sqrt + Copy {
63+
/// The vector's length.
64+
pub fn length(&self) -> T {
65+
(self.x * self.x + self.y * self.y).sqrt()
66+
}
67+
}
68+
6269
impl<T> fmt::Display for Vec2<T> where T: fmt::Display {
6370
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6471
write!(f, "({}, {})", self.x, self.y)

0 commit comments

Comments
 (0)