Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expand API of Scalar #1093

Merged
merged 4 commits into from
Sep 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/fj-math/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ pub use self::{
line::Line,
point::Point,
poly_chain::PolyChain,
scalar::Scalar,
scalar::{Scalar, Sign},
segment::Segment,
transform::Transform,
triangle::{Triangle, Winding},
Expand Down
57 changes: 52 additions & 5 deletions crates/fj-math/src/scalar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,16 +70,37 @@ impl Scalar {
self.0 as u64
}

/// Indicate whether the scalar is negative
pub fn is_negative(self) -> bool {
self < Self::ZERO
}

/// Indicate whether the scalar is positive
pub fn is_positive(self) -> bool {
self > Self::ZERO
}

/// Indicate whether the scalar is zero
pub fn is_zero(self) -> bool {
self == Scalar::ZERO
}

/// The sign of the scalar
///
/// Return `Scalar::ZERO`, if the scalar is zero, `Scalar::ONE`, if it is
/// positive, `-Scalar::ONE`, if it is negative.
pub fn sign(self) -> Scalar {
if self == Self::ZERO {
Self::ZERO
} else {
Self(self.0.signum())
pub fn sign(self) -> Sign {
if self.is_negative() {
return Sign::Negative;
}
if self.is_positive() {
return Sign::Positive;
}
if self.is_zero() {
return Sign::Zero;
}

unreachable!("Sign is neither negative, nor positive, nor zero.")
}

/// Compute the absolute value of the scalar
Expand Down Expand Up @@ -567,3 +588,29 @@ impl approx::AbsDiffEq for Scalar {
self.0.abs_diff_eq(&other.0, epsilon.0)
}
}

/// The sign of a [`Scalar`]
///
/// See [`Scalar::sign`]
#[derive(Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub enum Sign {
/// The scalar is negative
Negative,

/// The scalar is positive
Positive,

/// The scalar is zero
Zero,
}

impl Sign {
/// Convert this sign back to a scalar
pub fn to_scalar(self) -> Scalar {
match self {
Sign::Negative => -Scalar::ONE,
Sign::Positive => Scalar::ONE,
Sign::Zero => Scalar::ZERO,
}
}
}