1 /*
2  * Copyright (c) 2008-2014 Travis Geiselbrecht
3  *
4  * Use of this source code is governed by a MIT-style
5  * license that can be found in the LICENSE file or at
6  * https://opensource.org/licenses/MIT
7  */
8 #pragma once
9 
10 #include <lk/compiler.h>
11 #include <stdbool.h>
12 #include <stdint.h>
13 #include <sys/types.h>
14 
15 __BEGIN_CDECLS
16 
17 /* routines for dealing with power of 2 values for efficiency */
ispow2(uint val)18 static inline __ALWAYS_INLINE bool ispow2(uint val) {
19     return ((val - 1) & val) == 0;
20 }
21 
log2_uint(uint val)22 static inline __ALWAYS_INLINE uint log2_uint(uint val) {
23     if (val == 0)
24         return 0; // undefined
25 
26     return (sizeof(val) * 8) - 1 - __builtin_clz(val);
27 }
28 
valpow2(uint valp2)29 static inline __ALWAYS_INLINE uint valpow2(uint valp2) {
30     return 1U << valp2;
31 }
32 
divpow2(uint val,uint divp2)33 static inline __ALWAYS_INLINE uint divpow2(uint val, uint divp2) {
34     return val >> divp2;
35 }
36 
modpow2(uint val,uint modp2)37 static inline __ALWAYS_INLINE uint modpow2(uint val, uint modp2) {
38     return val & ((1UL << modp2) - 1);
39 }
40 
41 // Cribbed from:
42 // http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
round_up_pow2_u32(uint32_t v)43 static inline __ALWAYS_INLINE uint32_t round_up_pow2_u32(uint32_t v) {
44     v--;
45     v |= v >> 1;
46     v |= v >> 2;
47     v |= v >> 4;
48     v |= v >> 8;
49     v |= v >> 16;
50     v++;
51     return v;
52 }
53 __END_CDECLS
54