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
use num_traits::PrimInt;
use std::mem::size_of;
pub trait Fixed {
fn floor_log2(&self, n: usize) -> usize;
fn ceil_log2(&self, n: usize) -> usize;
fn align_power_of_two(&self, n: usize) -> usize;
fn align_power_of_two_and_shift(&self, n: usize) -> usize;
}
impl Fixed for usize {
#[inline]
fn floor_log2(&self, n: usize) -> usize {
self & !((1 << n) - 1)
}
#[inline]
fn ceil_log2(&self, n: usize) -> usize {
(self + (1 << n) - 1).floor_log2(n)
}
#[inline]
fn align_power_of_two(&self, n: usize) -> usize {
self.ceil_log2(n)
}
#[inline]
fn align_power_of_two_and_shift(&self, n: usize) -> usize {
(self + (1 << n) - 1) >> n
}
}
pub fn clamp<T: PartialOrd>(input: T, min: T, max: T) -> T {
if input < min {
min
} else if input > max {
max
} else {
input
}
}
pub trait ILog: PrimInt {
fn ilog(self) -> usize {
size_of::<Self>() * 8 - self.leading_zeros() as usize
}
}
impl<T> ILog for T where T: PrimInt {}
#[inline(always)]
pub fn msb(x: i32) -> i32 {
debug_assert!(x > 0);
31 ^ (x.leading_zeros() as i32)
}
#[inline(always)]
pub const fn round_shift(value: i32, bit: usize) -> i32 {
(value + (1 << bit >> 1)) >> bit
}