Remove From implementations from the direction types (#10857)

This removes the `From<Vec2/3>` implementations for the direction types.
It doesn't seem right to have when it only works if the vector is
nonzero and finite and produces NaN otherwise.

Added `Direction2d/3d::new` which uses `Vec2/3::try_normalize` to
guarantee it returns either a valid direction or `None`.

This should make it impossible to create an invalid direction, which I
think was the intention with these types.
This commit is contained in:
irate 2023-12-05 03:44:27 +01:00 committed by GitHub
parent 2c5639e323
commit 83ee6de1da
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 12 deletions

View File

@ -5,13 +5,14 @@ use crate::Vec2;
#[derive(Clone, Copy, Debug)]
pub struct Direction2d(Vec2);
impl From<Vec2> for Direction2d {
fn from(value: Vec2) -> Self {
Self(value.normalize())
}
}
impl Direction2d {
/// Create a direction from a finite, nonzero [`Vec2`].
///
/// Returns `None` if the input is zero (or very close to zero), or non-finite.
pub fn new(value: Vec2) -> Option<Self> {
value.try_normalize().map(Self)
}
/// Create a direction from a [`Vec2`] that is already normalized
pub fn from_normalized(value: Vec2) -> Self {
debug_assert!(value.is_normalized());

View File

@ -5,13 +5,14 @@ use crate::Vec3;
#[derive(Clone, Copy, Debug)]
pub struct Direction3d(Vec3);
impl From<Vec3> for Direction3d {
fn from(value: Vec3) -> Self {
Self(value.normalize())
}
}
impl Direction3d {
/// Create a direction from a finite, nonzero [`Vec3`].
///
/// Returns `None` if the input is zero (or very close to zero), or non-finite.
pub fn new(value: Vec3) -> Option<Self> {
value.try_normalize().map(Self)
}
/// Create a direction from a [`Vec3`] that is already normalized
pub fn from_normalized(value: Vec3) -> Self {
debug_assert!(value.is_normalized());