fastrange_rs/
lib.rs

1#![no_std]
2
3/// Given a value "word", produces an integer in [0,p) without division.
4#[inline(always)]
5pub fn fastrange_32(word: u32, p: u32) -> u32 {
6    ((u64::from(word) * u64::from(p)) >> 32) as u32
7}
8
9/// Given a value "word", produces an integer in [0,p) without division.
10#[inline(always)]
11pub fn fastrange_64(word: u64, p: u64) -> u64 {
12    ((word as u128 * p as u128) >> 64) as u64
13}
14
15#[cfg(test)]
16mod tests {
17    use super::*;
18
19    #[test]
20    fn test_32() {
21        for x in 0..1_000_000 {
22            assert!(fastrange_32(x, 5) < 5);
23        }
24    }
25
26    #[test]
27    fn test_64() {
28        for x in 0..1_000_000 {
29            assert!(fastrange_64(x, 5) < 5);
30        }
31    }
32}