From f01b71f4a631c7e9bb2d510c0cc6533dc0dae09e Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Mon, 8 Sep 2025 05:02:38 +0200 Subject: [PATCH] next_power_of_two bit hack function --- kern/libkern/util.h | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/kern/libkern/util.h b/kern/libkern/util.h index ffb9cf2..24df71d 100644 --- a/kern/libkern/util.h +++ b/kern/libkern/util.h @@ -4,6 +4,7 @@ /* * Give hints to the compiler for branch prediction optimization. */ +#include #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 2)) #define likely(c) (__builtin_expect(!!(c), 1)) #define unlikely(c) (__builtin_expect(!!(c), 0)) @@ -12,4 +13,16 @@ #define unlikely(c) (c) #endif +/* Round up to nearest power of two */ +static inline uint32_t next_power_of_two(uint32_t v) { + /* See: https://graphics.stanford.edu/%7Eseander/bithacks.html#RoundUpPowerOf2 */ + v--; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + return ++v; +} + #endif // UTIL_H