1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! `strength_reduce` implements integer division and modulo via "arithmetic strength reduction"
//!
//! Modern processors can do multiplication and shifts much faster than division, and "arithmetic strength reduction" is an algorithm to transform divisions into multiplications and shifts.
//! Compilers already perform this optimization for divisors that are known at compile time; this library enables this optimization for divisors that are only known at runtime.
//!
//! Benchmarking shows a 5-10x speedup or integer division and modulo operations.
//!
//! # Example:
//! ```
//! use strength_reduce::StrengthReducedU64;
//! 
//! let mut my_array: Vec<u64> = (0..500).collect();
//! let divisor = 3;
//! let modulo = 14;
//!
//! // slow naive division and modulo
//! for element in &mut my_array {
//!     *element = (*element / divisor) % modulo;
//! }
//!
//! // fast strength-reduced division and modulo
//! let reduced_divisor = StrengthReducedU64::new(divisor);
//! let reduced_modulo = StrengthReducedU64::new(modulo);
//! for element in &mut my_array {
//!     *element = (*element / reduced_divisor) % reduced_modulo;
//! }
//! ```
//!
//! This library is intended for hot loops like the example above, where a division is repeated many times in a loop with the divisor remaining unchanged. 
//! There is a setup cost associated with creating stength-reduced division instances, so using strength-reduced division for 1-2 divisions is not worth the setup cost.
//! The break-even point differs by use-case, but is typically low: Benchmarking has shown that takes 3 to 4 repeated divisions with the same StengthReduced## instance to be worth it.
//! 
//! `strength_reduce` is `#![no_std]`
//!
//! The optimizations that this library provides are inherently dependent on architecture, compiler, and platform,
//! so test before you use. 
#![no_std]

use core::ops::{Div, Rem};

mod long_division;

/// Implements unsigned division and modulo via mutiplication and shifts.
///
/// Creating a an instance of this struct is more expensive than a single division, but if the division is repeated,
/// this version will be several times faster than naive division.
#[derive(Clone, Copy, Debug)]
pub struct StrengthReducedU8 {
    multiplier: u16,
    divisor: u8,
}
impl StrengthReducedU8 {
    /// Creates a new divisor instance.
    ///
    /// If possible, avoid calling new() from an inner loop: The intended usage is to create an instance of this struct outside the loop, and use it for divison and remainders inside the loop.
    ///
    /// # Panics:
    /// 
    /// Panics if `divisor` is 0
    #[inline]
    pub fn new(divisor: u8) -> Self {
        assert!(divisor > 0);

        if divisor.is_power_of_two() { 
            Self{ multiplier: 0, divisor }
        } else {
            let divided = core::u16::MAX / (divisor as u16);
            Self{ multiplier: divided + 1, divisor }
        }
    }

    /// Simultaneous truncated integer division and modulus.
    /// Returns `(quotient, remainder)`.
    #[inline]
    pub fn div_rem(numerator: u8, denom: Self) -> (u8, u8) {
        let quotient = numerator / denom;
        let remainder = numerator % denom;
        (quotient, remainder)
    }

    /// Retrieve the value used to create this struct
    #[inline]
    pub fn get(&self) -> u8 {
        self.divisor
    }
}

impl Div<StrengthReducedU8> for u8 {
    type Output = u8;

    #[inline]
    fn div(self, rhs: StrengthReducedU8) -> Self::Output {
        if rhs.multiplier == 0 {
            (self as u16 >> rhs.divisor.trailing_zeros()) as u8
        } else {
            let numerator = self as u16;
            let multiplied_hi = numerator * (rhs.multiplier >> 8);
            let multiplied_lo = (numerator * rhs.multiplier as u8 as u16) >> 8;

            ((multiplied_hi + multiplied_lo) >> 8) as u8
        }
    }
}

impl Rem<StrengthReducedU8> for u8 {
    type Output = u8;

    #[inline]
    fn rem(self, rhs: StrengthReducedU8) -> Self::Output {
        if rhs.multiplier == 0 {
            self & (rhs.divisor - 1)
        } else {
            let product = rhs.multiplier.wrapping_mul(self as u16) as u32;
            let divisor = rhs.divisor as u32;

            let shifted = (product * divisor) >> 16;
            shifted as u8
        }
    }
}

// small types prefer to do work in the intermediate type
macro_rules! strength_reduced_u16 {
    ($struct_name:ident, $primitive_type:ident) => (
        /// Implements unsigned division and modulo via mutiplication and shifts.
        ///
        /// Creating a an instance of this struct is more expensive than a single division, but if the division is repeated,
        /// this version will be several times faster than naive division.
        #[derive(Clone, Copy, Debug)]
        pub struct $struct_name {
            multiplier: u32,
            divisor: $primitive_type,
        }
        impl $struct_name {
            /// Creates a new divisor instance.
            ///
            /// If possible, avoid calling new() from an inner loop: The intended usage is to create an instance of this struct outside the loop, and use it for divison and remainders inside the loop.
            ///
            /// # Panics:
            /// 
            /// Panics if `divisor` is 0
            #[inline]
            pub fn new(divisor: $primitive_type) -> Self {
                assert!(divisor > 0);

                if divisor.is_power_of_two() { 
                    Self{ multiplier: 0, divisor }
                } else {
                    let divided = core::u32::MAX / (divisor as u32);
                    Self{ multiplier: divided + 1, divisor }
                }
            }

            /// Simultaneous truncated integer division and modulus.
            /// Returns `(quotient, remainder)`.
            #[inline]
            pub fn div_rem(numerator: $primitive_type, denom: Self) -> ($primitive_type, $primitive_type) {
                let quotient = numerator / denom;
                let remainder = numerator - quotient * denom.divisor;
                (quotient, remainder)
            }

            /// Retrieve the value used to create this struct
            #[inline]
            pub fn get(&self) -> $primitive_type {
                self.divisor
            }
        }

        impl Div<$struct_name> for $primitive_type {
            type Output = $primitive_type;

            #[inline]
            fn div(self, rhs: $struct_name) -> Self::Output {
                if rhs.multiplier == 0 {
                    self >> rhs.divisor.trailing_zeros()
                } else {
                    let numerator = self as u32;
                    let multiplied_hi = numerator * (rhs.multiplier >> 16);
                    let multiplied_lo = (numerator * rhs.multiplier as u16 as u32) >> 16;

                    ((multiplied_hi + multiplied_lo) >> 16) as $primitive_type
                }
            }
        }

        impl Rem<$struct_name> for $primitive_type {
            type Output = $primitive_type;

            #[inline]
            fn rem(self, rhs: $struct_name) -> Self::Output {
                if rhs.multiplier == 0 {
                    self & (rhs.divisor - 1)
                } else {
                    let quotient = self / rhs;
                    self - quotient * rhs.divisor
                }
            }
        }
    )
}

// small types prefer to do work in the intermediate type
macro_rules! strength_reduced_u32 {
    ($struct_name:ident, $primitive_type:ident) => (
        /// Implements unsigned division and modulo via mutiplication and shifts.
        ///
        /// Creating a an instance of this struct is more expensive than a single division, but if the division is repeated,
        /// this version will be several times faster than naive division.
        #[derive(Clone, Copy, Debug)]
        pub struct $struct_name {
            multiplier: u64,
            divisor: $primitive_type,
        }
        impl $struct_name {
            /// Creates a new divisor instance.
            ///
            /// If possible, avoid calling new() from an inner loop: The intended usage is to create an instance of this struct outside the loop, and use it for divison and remainders inside the loop.
            ///
            /// # Panics:
            /// 
            /// Panics if `divisor` is 0
            #[inline]
            pub fn new(divisor: $primitive_type) -> Self {
                assert!(divisor > 0);

                if divisor.is_power_of_two() { 
                    Self{ multiplier: 0, divisor }
                } else {
                    let divided = core::u64::MAX / (divisor as u64);
                    Self{ multiplier: divided + 1, divisor }
                }
            }

            /// Simultaneous truncated integer division and modulus.
            /// Returns `(quotient, remainder)`.
            #[inline]
            pub fn div_rem(numerator: $primitive_type, denom: Self) -> ($primitive_type, $primitive_type) {
                if denom.multiplier == 0 {
                    (numerator >> denom.divisor.trailing_zeros(), numerator & (denom.divisor - 1))
                }
                else {
                    let numerator64 = numerator as u64;
                    let multiplied_hi = numerator64 * (denom.multiplier >> 32);
                    let multiplied_lo = numerator64 * (denom.multiplier as u32 as u64) >> 32;

                    let quotient = ((multiplied_hi + multiplied_lo) >> 32) as $primitive_type;
                    let remainder = numerator - quotient * denom.divisor;
                    (quotient, remainder)
                }
            }

            /// Retrieve the value used to create this struct
            #[inline]
            pub fn get(&self) -> $primitive_type {
                self.divisor
            }
        }

        impl Div<$struct_name> for $primitive_type {
            type Output = $primitive_type;

            #[inline]
            fn div(self, rhs: $struct_name) -> Self::Output {
                if rhs.multiplier == 0 {
                    self >> rhs.divisor.trailing_zeros()
                } else {
                    let numerator = self as u64;
                    let multiplied_hi = numerator * (rhs.multiplier >> 32);
                    let multiplied_lo = numerator * (rhs.multiplier as u32 as u64) >> 32;

                    ((multiplied_hi + multiplied_lo) >> 32) as $primitive_type
                }
            }
        }

        impl Rem<$struct_name> for $primitive_type {
            type Output = $primitive_type;

            #[inline]
            fn rem(self, rhs: $struct_name) -> Self::Output {
                if rhs.multiplier == 0 {
                    self & (rhs.divisor - 1)
                } else {
                    let product = rhs.multiplier.wrapping_mul(self as u64) as u128;
                    let divisor = rhs.divisor as u128;

                    let shifted = (product * divisor) >> 64;
                    shifted as $primitive_type
                }
            }
        }
    )
}

macro_rules! strength_reduced_u64 {
    ($struct_name:ident, $primitive_type:ident) => (
        /// Implements unsigned division and modulo via mutiplication and shifts.
        ///
        /// Creating a an instance of this struct is more expensive than a single division, but if the division is repeated,
        /// this version will be several times faster than naive division.
        #[derive(Clone, Copy, Debug)]
        pub struct $struct_name {
            multiplier: u128,
            divisor: $primitive_type,
        }
        impl $struct_name {
            /// Creates a new divisor instance.
            ///
            /// If possible, avoid calling new() from an inner loop: The intended usage is to create an instance of this struct outside the loop, and use it for divison and remainders inside the loop.
            ///
            /// # Panics:
            /// 
            /// Panics if `divisor` is 0
            #[inline]
            pub fn new(divisor: $primitive_type) -> Self {
                assert!(divisor > 0);

                if divisor.is_power_of_two() { 
                    Self{ multiplier: 0, divisor }
                } else {
                    let divided = long_division::divide_128_max(divisor as u64);
                    Self{ multiplier: divided + 1, divisor }
                }
            }
            /// Simultaneous truncated integer division and modulus.
            /// Returns `(quotient, remainder)`.
            #[inline]
            pub fn div_rem(numerator: $primitive_type, denom: Self) -> ($primitive_type, $primitive_type) {
                if denom.multiplier == 0 {
                    (numerator >> denom.divisor.trailing_zeros(), numerator & (denom.divisor - 1))
                }
                else {
                    let numerator128 = numerator as u128;
                    let multiplied_hi = numerator128 * (denom.multiplier >> 64);
                    let multiplied_lo = numerator128 * (denom.multiplier as u64 as u128) >> 64;

                    let quotient = ((multiplied_hi + multiplied_lo) >> 64) as $primitive_type;
                    let remainder = numerator - quotient * denom.divisor;
                    (quotient, remainder)
                }
            }

            /// Retrieve the value used to create this struct
            #[inline]
            pub fn get(&self) -> $primitive_type {
                self.divisor
            }
        }

        impl Div<$struct_name> for $primitive_type {
            type Output = $primitive_type;

            #[inline]
            fn div(self, rhs: $struct_name) -> Self::Output {
                if rhs.multiplier == 0 {
                    self >> rhs.divisor.trailing_zeros()
                } else {
                    let numerator = self as u128;
                    let multiplied_hi = numerator * (rhs.multiplier >> 64);
                    let multiplied_lo = numerator * (rhs.multiplier as u64 as u128) >> 64;

                    ((multiplied_hi + multiplied_lo) >> 64) as $primitive_type
                }
            }
        }

        impl Rem<$struct_name> for $primitive_type {
            type Output = $primitive_type;

            #[inline]
            fn rem(self, rhs: $struct_name) -> Self::Output {
                if rhs.multiplier == 0 {
                    self & (rhs.divisor - 1)
                } else {
                    let quotient = self / rhs;
                    self - quotient * rhs.divisor
                }
            }
        }
    )
}

// We just hardcoded u8, since it will never be a usize. for therest, we have macros, so we can reuse the same code for usize
strength_reduced_u16!(StrengthReducedU16, u16);
strength_reduced_u32!(StrengthReducedU32, u32);
strength_reduced_u64!(StrengthReducedU64, u64);

// Our definition for usize will depend on how big usize is
#[cfg(target_pointer_width = "16")]
strength_reduced_u16!(StrengthReducedUsize, usize);
#[cfg(target_pointer_width = "32")]
strength_reduced_u32!(StrengthReducedUsize, usize);
#[cfg(target_pointer_width = "64")]
strength_reduced_u64!(StrengthReducedUsize, usize);



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

    macro_rules! reduction_test {
        ($test_name:ident, $struct_name:ident, $primitive_type:ident) => (
            #[test]
            fn $test_name() {
                let max = core::$primitive_type::MAX;
                let divisors = [7,8,9,10,11,12,13,14,15,16,17,18,19,20,max-1,max];
                let numerators = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,max-1,max];

                for &divisor in &divisors {
                    let reduced_divisor = $struct_name::new(divisor);
                    for &numerator in &numerators {
                        let expected_div = numerator / divisor;
                        let expected_rem = numerator % divisor;

                        let reduced_div = numerator / reduced_divisor;
                        assert_eq!(expected_div, reduced_div, "Divide failed with numerator: {}, divisor: {}", numerator, divisor);
                        let reduced_rem = numerator % reduced_divisor;

                        let (reduced_combined_div, reduced_combined_rem) = $struct_name::div_rem(numerator, reduced_divisor);

                        
                        assert_eq!(expected_rem, reduced_rem, "Modulo failed with numerator: {}, divisor: {}", numerator, divisor);
                        assert_eq!(expected_div, reduced_combined_div, "div_rem divide failed with numerator: {}, divisor: {}", numerator, divisor);
                        assert_eq!(expected_rem, reduced_combined_rem, "div_rem modulo failed with numerator: {}, divisor: {}", numerator, divisor);
                    }
                }
            }
        )
    }

    reduction_test!(test_strength_reduced_u8, StrengthReducedU8, u8);
    reduction_test!(test_strength_reduced_u16, StrengthReducedU16, u16);
    reduction_test!(test_strength_reduced_u32, StrengthReducedU32, u32);
    reduction_test!(test_strength_reduced_u64, StrengthReducedU64, u64);
    reduction_test!(test_strength_reduced_usize, StrengthReducedUsize, usize);
}