1 use std::ops::Add;
2 use std::ops::Div;
3 use std::ops::Rem;
4 use std::ops::Sub;
5
gcd<T>(mut a: T, mut b: T) -> T where T: Copy + Default + PartialEq, T: Rem<Output = T>,6 pub fn gcd<T>(mut a: T, mut b: T) -> T
7 where
8 T: Copy + Default + PartialEq,
9 T: Rem<Output = T>,
10 {
11 let mut c = a % b;
12 while c != T::default() {
13 a = b;
14 b = c;
15 c = a % b;
16 }
17
18 b
19 }
20
align<T>(val: T, a: T) -> T where T: Add<Output = T>, T: Copy, T: Default, T: PartialEq, T: Rem<Output = T>, T: Sub<Output = T>,21 pub fn align<T>(val: T, a: T) -> T
22 where
23 T: Add<Output = T>,
24 T: Copy,
25 T: Default,
26 T: PartialEq,
27 T: Rem<Output = T>,
28 T: Sub<Output = T>,
29 {
30 let tmp = val % a;
31 if tmp == T::default() {
32 val
33 } else {
34 val + (a - tmp)
35 }
36 }
37
div_round_up<T>(a: T, b: T) -> T where T: Copy, T: Add<Output = T>, T: Div<Output = T>, T: Sub<Output = T>,38 pub fn div_round_up<T>(a: T, b: T) -> T
39 where
40 T: Copy,
41 T: Add<Output = T>,
42 T: Div<Output = T>,
43 T: Sub<Output = T>,
44 {
45 #[allow(clippy::eq_op)]
46 let one = b / b;
47
48 (a + b - one) / b
49 }
50
51 pub struct SetBitIndices<T> {
52 val: T,
53 }
54
55 impl<T> SetBitIndices<T> {
from_msb(val: T) -> Self56 pub fn from_msb(val: T) -> Self {
57 Self { val: val }
58 }
59 }
60
61 impl Iterator for SetBitIndices<u32> {
62 type Item = u32;
63
next(&mut self) -> Option<Self::Item>64 fn next(&mut self) -> Option<Self::Item> {
65 if self.val == 0 {
66 None
67 } else {
68 let pos = u32::BITS - self.val.leading_zeros() - 1;
69 self.val ^= 1 << pos;
70 Some(pos)
71 }
72 }
73 }
74