rayon/
math.rs

1use std::ops::{Bound, Range, RangeBounds};
2
3/// Divide `n` by `divisor`, and round up to the nearest integer
4/// if not evenly divisible.
5#[inline]
6pub(super) fn div_round_up(n: usize, divisor: usize) -> usize {
7    debug_assert!(divisor != 0, "Division by zero!");
8    if n == 0 {
9        0
10    } else {
11        (n - 1) / divisor + 1
12    }
13}
14
15/// Normalize arbitrary `RangeBounds` to a `Range`
16pub(super) fn simplify_range(range: impl RangeBounds<usize>, len: usize) -> Range<usize> {
17    let start = match range.start_bound() {
18        Bound::Unbounded => 0,
19        Bound::Included(&i) if i <= len => i,
20        Bound::Excluded(&i) if i < len => i + 1,
21        bound => panic!("range start {:?} should be <= length {}", bound, len),
22    };
23    let end = match range.end_bound() {
24        Bound::Unbounded => len,
25        Bound::Excluded(&i) if i <= len => i,
26        Bound::Included(&i) if i < len => i + 1,
27        bound => panic!("range end {:?} should be <= length {}", bound, len),
28    };
29    if start > end {
30        panic!(
31            "range start {:?} should be <= range end {:?}",
32            range.start_bound(),
33            range.end_bound()
34        );
35    }
36    start..end
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42
43    #[test]
44    fn check_div_round_up() {
45        assert_eq!(0, div_round_up(0, 5));
46        assert_eq!(1, div_round_up(5, 5));
47        assert_eq!(1, div_round_up(1, 5));
48        assert_eq!(2, div_round_up(3, 2));
49        assert_eq!(
50            usize::max_value() / 2 + 1,
51            div_round_up(usize::max_value(), 2)
52        );
53    }
54}