]> git.ipfire.org Git - thirdparty/lxc.git/commitdiff
utils: add lxc_find_next_power2()
authorChristian Brauner <christian.brauner@ubuntu.com>
Wed, 18 Oct 2017 19:20:37 +0000 (21:20 +0200)
committerChristian Brauner <christian.brauner@ubuntu.com>
Thu, 9 Nov 2017 00:06:34 +0000 (01:06 +0100)
Signed-off-by: Christian Brauner <christian.brauner@ubuntu.com>
src/lxc/utils.c
src/lxc/utils.h

index 887afdd03cf7c59c61ceaacd961da850b381f2c0..bb3ac4e9b45b751d1579f5e31a2d051aa8750e12 100644 (file)
@@ -2515,3 +2515,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;
+}
index 62c2d3c72674dd4fced0fe50eaa6b50ecf0dcd79..c96ce8ae6a5d480de85ef8450eae113181ac30c0 100644 (file)
@@ -462,4 +462,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 */