Skip to content

Commit

Permalink
Merge pull request #10 from danielparks/misc
Browse files Browse the repository at this point in the history
Clear up safety in float rounding.
  • Loading branch information
danielparks authored Mar 16, 2024
2 parents 5c5018c + a234d21 commit 2fb7c7a
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,19 +149,22 @@ roundable_integer!(i8 i16 i32 i64 i128 isize);
macro_rules! roundable_float {
($($ty:ident)+) => {$(
impl Roundable for $ty {
#[allow(clippy::arithmetic_side_effects)]
fn try_round_to(self, factor: Self) -> Option<Self> {
assert!(factor > 0.0, "try_round_to() requires positive factor");

#[allow(clippy::arithmetic_side_effects)]
let remainder = self % factor;
let remainder = if remainder < 0.0 {
// Safe: remainder is negative so adding it to factor will
// never overflow (|remainder| < factor).
factor + remainder
} else {
remainder
};

// remainder <= self
#[allow(clippy::arithmetic_side_effects)]
// Safe: remainder has the same sign as self, so subtracting
// remainder will always be closer to 0. Also, remainder is
// always between 0 and self, so it base can never switch signs.
let base = self - remainder;

if remainder < factor / 2.0 {
Expand Down

0 comments on commit 2fb7c7a

Please sign in to comment.