Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Fix PerThing::from_percent. #7701

Merged
merged 4 commits into from
Dec 11, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions primitives/arithmetic/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -515,3 +515,17 @@ mod threshold_compare_tests {
assert_eq!(Saturating::saturating_pow(i32::max_value(), 2), i32::max_value());
}
}

#[cfg(test)]
mod per_thing {
use super::*;

#[test]
fn per_thing_100_wont_overflow() {
<Percent as PerThing>::from_percent(100);
<PerU16 as PerThing>::from_percent(100);
<Permill as PerThing>::from_percent(100);
<Perbill as PerThing>::from_percent(100);
<Perquintill as PerThing>::from_percent(100);
}
}
5 changes: 3 additions & 2 deletions primitives/arithmetic/src/per_things.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ pub trait PerThing:
let b = Self::ACCURACY;
// if Self::ACCURACY % 100 > 0 then we need the correction for accuracy
let c = rational_mul_correction::<Self::Inner, Self>(b, a, 100.into(), Rounding::Nearest);
Self::from_parts(a / 100.into() * b + c)
let base: Self::Inner = 100.into();
Self::from_parts(a / base.saturating_mul(b).saturating_add(c))
kianenigma marked this conversation as resolved.
Show resolved Hide resolved
}

/// Return the product of multiplication of this value by itself.
Expand Down Expand Up @@ -334,7 +335,7 @@ macro_rules! implement_per_thing {
&self.0
}
fn decode_from(x: Self::As) -> Self {
// Saturates if `x` is more than `$max` internally.
// Saturates if `x` is more than `$max` internally.
Self::from_parts(x)
}
}
Expand Down