Skip to content

Commit

Permalink
Try to implement clamp
Browse files Browse the repository at this point in the history
  • Loading branch information
jacg committed Oct 27, 2023
1 parent 629f385 commit 3ffc216
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -754,6 +754,21 @@ macro_rules! system {
value: self.value.min(other.value),
}
}

/// f{32,64}: Restrict a value to a certain interval unless it is NaN.
/// Ord: Restrict a value to a certain interval.
#[must_use = "method returns a new number and does not mutate the original value"]
#[inline(always)]
pub fn clamp(self, min: Self, max: Self) -> Self
where
V: $crate::num::Float,
{
Quantity {
dimension: $crate::lib::marker::PhantomData,
units: $crate::lib::marker::PhantomData,
value: self.value.clamp(min.value, max.value),
}
}
}

// Explicitly definte floating point methods for float and complex storage types.
Expand Down Expand Up @@ -1083,6 +1098,15 @@ macro_rules! system {
value: self.value.min(other.value),
}
}

#[inline(always)]
fn clamp(self, min: Self, max: Self) -> Self {
Quantity {
dimension: $crate::lib::marker::PhantomData,
units: $crate::lib::marker::PhantomData,
value: self.value.clamp(min.value, max.value),
}
}
}

autoconvert! {
Expand Down
17 changes: 17 additions & 0 deletions src/tests/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,13 @@ mod float {
Test::eq(&Length::new::<meter>(l.min(*r)),
&Length::new::<meter>(*l).min(Length::new::<meter>(*r)))
}

#[allow(trivial_casts)]
fn clamp(x: A<V>, min: A<V>, max: A<V>) -> bool {
Test::eq(
&Length::new::<meter>(x.clamp(*min, *max)),
&Length::new::<meter>(*x).clamp(Length::new::<meter>(*min), Length::new::<meter>(*max)))
}
}
}
}
Expand Down Expand Up @@ -571,6 +578,16 @@ mod fixed {
&Ord::min(Length::new::<meter>((*l).clone()),
Length::new::<meter>((*r).clone())))
}

#[allow(trivial_casts)]
fn clamp(x: A<V>, min: A<V>, max: A<V>) -> bool {
Test::eq(&Length::new::<meter>((*x).clone().clamp((*min).clone(), (*max).clone())),
&Ord::clamp(
Length::new::<meter>((*x).clone()),
Length::new::<meter>((*min).clone()),
Length::new::<meter>((*max).clone()),
))
}
}
}
}
Expand Down

0 comments on commit 3ffc216

Please sign in to comment.