summaryrefslogtreecommitdiff
path: root/src/test
diff options
context:
space:
mode:
authorZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>2023-04-03 14:32:39 +0200
committerZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>2023-04-24 10:02:30 +0200
commita12bc99ef0fc04fa48767c891f7a6db6404e51d5 (patch)
treef5840c3081c8aea6cddd557635313a2ab2d426a4 /src/test
parent6eccc3cfa9dcfea3c8b508a66d2d592e6b9fcb93 (diff)
downloadsystemd-a12bc99ef0fc04fa48767c891f7a6db6404e51d5.tar.gz
basic/logarithm: add popcount() wrapper
__builtin_popcount() is a bit of a mouthful, so let's provide a helper. Using _Generic has the advantage that if a type other then the ones on the list is given, compilation will fail. This is nice, because if by any change we pass a wider type, it is rejected immediately instead of being truncated. log.h is also needed. It is included transitively, but let's include it directly. macro.h is *not* needed.
Diffstat (limited to 'src/test')
-rw-r--r--src/test/test-logarithm.c21
1 files changed, 21 insertions, 0 deletions
diff --git a/src/test/test-logarithm.c b/src/test/test-logarithm.c
index b6818b422c..b35fea9c27 100644
--- a/src/test/test-logarithm.c
+++ b/src/test/test-logarithm.c
@@ -71,4 +71,25 @@ TEST(log2i) {
assert_se(log2i(INT_MAX) == sizeof(int)*8-2);
}
+TEST(popcount) {
+ uint16_t u16a = 0x0000;
+ uint16_t u16b = 0xFFFF;
+ uint32_t u32a = 0x00000010;
+ uint32_t u32b = 0xFFFFFFFF;
+ uint64_t u64a = 0x0000000000000010;
+ uint64_t u64b = 0x0100000000100010;
+
+ assert_se(popcount(u16a) == 0);
+ assert_se(popcount(u16b) == 16);
+ assert_se(popcount(u32a) == 1);
+ assert_se(popcount(u32b) == 32);
+ assert_se(popcount(u64a) == 1);
+ assert_se(popcount(u64b) == 3);
+
+ /* This would fail:
+ * error: ‘_Generic’ selector of type ‘int’ is not compatible with any association
+ * assert_se(popcount(0x10) == 1);
+ */
+}
+
DEFINE_TEST_MAIN(LOG_INFO);