buddyalloc/math.rs
1/// Calculate the base-2 logarithm of this value.
2///
3/// This will normally round down, except for the case of `0.log2()`,
4/// which will return 0.
5///
6/// Based on the obvious code at
7/// http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious
8pub const fn log2(n: usize) -> u8 {
9 let mut temp = n;
10 let mut result = 0;
11 temp >>= 1;
12 while temp != 0 {
13 result += 1;
14 temp >>= 1;
15 }
16 result
17}
18
19#[test]
20fn test_log2() {
21 assert_eq!(0, log2(0));
22 assert_eq!(0, log2(1));
23 assert_eq!(1, log2(2));
24 assert_eq!(5, log2(32));
25 assert_eq!(10, log2(1024));
26}