utils: add popcount function Signed-off-by: Ran Benita <ran234@gmail.com>
diff --git a/configure.ac b/configure.ac
index 3f8de97..da201e1 100644
--- a/configure.ac
+++ b/configure.ac
@@ -83,6 +83,7 @@ AS_IF([test "x$ac_cv_func_secure_getenv" = xno -a \
])
AX_GCC_BUILTIN(__builtin_expect)
+AX_GCC_BUILTIN(__builtin_popcount)
# Some tests use Linux-specific headers
AC_CHECK_HEADER([linux/input.h])
diff --git a/src/utils.h b/src/utils.h
index 4b7e81c..11ef735 100644
--- a/src/utils.h
+++ b/src/utils.h
@@ -178,6 +178,19 @@ msb_pos(uint32_t mask)
return pos;
}
+static inline int
+popcount(uint32_t x)
+{
+ int count;
+#if defined(HAVE___BUILTIN_POPCOUNT)
+ count = __builtin_popcount(x);
+#else
+ for (count = 0; x; count++)
+ x &= x - 1;
+#endif
+ return count;
+}
+
bool
map_file(FILE *file, char **string_out, size_t *size_out);