From 6222c3f48b87940377dec082c300770b1c773611 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Wed, 18 Oct 2017 21:20:37 +0200 Subject: [PATCH] utils: add lxc_find_next_power2() Signed-off-by: Christian Brauner --- src/lxc/utils.c | 18 ++++++++++++++++++ src/lxc/utils.h | 10 ++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/lxc/utils.c b/src/lxc/utils.c index 7c60a4451..19e6c2ee6 100644 --- a/src/lxc/utils.c +++ b/src/lxc/utils.c @@ -2457,3 +2457,21 @@ int parse_byte_size_string(const char *s, int64_t *converted) *converted = overflow; return 0; } + +uint64_t lxc_find_next_power2(uint64_t n) +{ + /* 0 is not valid input. We return 0 to the caller since 0 is not a + * valid power of two. + */ + if (n == 0) + return 0; + + if (!(n & (n - 1))) + return n; + + while (n & (n - 1)) + n = n & (n - 1); + + n = n << 1; + return n; +} diff --git a/src/lxc/utils.h b/src/lxc/utils.h index fa9f88cc2..7ef3056a5 100644 --- a/src/lxc/utils.h +++ b/src/lxc/utils.h @@ -472,4 +472,14 @@ extern bool lxc_nic_exists(char *nic); extern int lxc_make_tmpfile(char *template, bool rm); extern uint64_t lxc_getpagesize(void); +/* If n is not a power of 2 this function will return the next power of 2 + * greater than that number. Note that this function always returns the *next* + * power of 2 *greater* that number not the *nearest*. For example, passing 1025 + * as argument this function will return 2048 although the closest power of 2 + * would be 1024. + * If the caller passes in 0 they will receive 0 in return since this is invalid + * input and 0 is not a power of 2. + */ +extern uint64_t lxc_find_next_power2(uint64_t n); + #endif /* __LXC_UTILS_H */ -- 2.47.2