#[non_exhaustive]pub enum DivisorI32 {
PowerOfTwo(PowerOfTwoDivisorI32),
AddIndicator(AddIndicatorDivisorI32),
}Expand description
A i32 divisor, precomputed once to divide many values by it
Division by a divisor that is only known at run time needs a divide instruction.
Self::new precomputes a shift and a mask when the magnitude of the divisor is a
power of two, and otherwise a multiplier, so that each division is a high multiply,
shifts and additions. Self::new picks the variant from the divisor and the target.
To divide many values, match on the variant once, before the loop, and call the
variant’s methods in the loop. They don’t branch on the divisor, so the loop doesn’t
depend on the compiler moving a branch out of it. Move the variant into the loop’s
closure, so that the compiler doesn’t reload its fields through a reference for each
value. Self::wrapping_div_rem matches on each call, so a match can fall back to it
for the variants it doesn’t specialize, including variants added later.
§Example
let values: Vec<i32> = vec![100, 7, 64];
let quotients: Vec<_> = match DivisorI32::new(7).unwrap() {
DivisorI32::PowerOfTwo(d) => values.iter().map(move |n| d.wrapping_div_rem(*n).0).collect(),
DivisorI32::AddIndicator(d) => values.iter().map(move |n| d.wrapping_div_rem(*n).0).collect(),
d => values.iter().map(move |n| d.wrapping_div_rem(*n).0).collect(),
};
assert_eq!(quotients, [14, 1, 9]);Variants (Non-exhaustive)§
This enum is marked as non-exhaustive
PowerOfTwo(PowerOfTwoDivisorI32)
A divisor whose magnitude is a power of two
AddIndicator(AddIndicatorDivisorI32)
Any other divisor
Implementations§
Source§impl DivisorI32
impl DivisorI32
Source§impl DivisorI32
impl DivisorI32
Sourcepub const fn new(divisor: i32) -> Option<Self>
pub const fn new(divisor: i32) -> Option<Self>
Returns a divisor for divisor, or None if divisor is zero
§Example
const SEVEN: DivisorI32 = DivisorI32::new(7).unwrap();
assert!(DivisorI32::new(0).is_none());Sourcepub const fn checked_div_rem(self, n: i32) -> Option<(i32, i32)>
pub const fn checked_div_rem(self, n: i32) -> Option<(i32, i32)>
Returns (n / divisor, n % divisor), or None for i32::MIN / -1
It matches on the variant on each call. Only Self::PowerOfTwo can return None.
§Example
let divisor = DivisorI32::new(-7).unwrap();
assert_eq!(divisor.checked_div_rem(-100), Some((14, -2)));
let minus_one = DivisorI32::new(-1).unwrap();
assert_eq!(minus_one.checked_div_rem(i32::MIN), None);