+static void
+test_ctz(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
+{
+ int n;
+
+ for (n = 0; n < 32; n++) {
+ /* Check minimum x such that f(x) == n. */
+ check_ctz(1 << n, n);
+
+ /* Check maximum x such that f(x) == n. */
+ check_ctz(UINT32_MAX << n, n);
+
+ /* Check a random value in the middle. */
+ check_ctz((random_uint32() | 1) << n, n);
+ }
+
+ /* Check ctz(0). */
+ check_ctz(0, 32);
+}
+
+static void
+shuffle(unsigned int *p, size_t n)
+{
+ for (; n > 1; n--, p++) {
+ unsigned int *q = &p[rand() % n];
+ unsigned int tmp = *p;
+ *p = *q;
+ *q = tmp;
+ }
+}
+
+static void
+check_popcount(uint32_t x, int n)
+{
+ if (popcount(x) != n) {
+ fprintf(stderr, "popcount(%#"PRIx32") is %d but should be %d\n",
+ x, popcount(x), n);
+ abort();
+ }
+}
+
+static void
+test_popcount(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
+{
+ unsigned int bits[32];
+ int i;
+
+ for (i = 0; i < ARRAY_SIZE(bits); i++) {
+ bits[i] = 1u << i;
+ }
+
+ check_popcount(0, 0);
+
+ for (i = 0; i < 1000; i++) {
+ uint32_t x = 0;
+ int j;
+
+ shuffle(bits, ARRAY_SIZE(bits));
+ for (j = 0; j < 32; j++) {
+ x |= bits[j];
+ check_popcount(x, j + 1);
+ }
+ assert(x == UINT32_MAX);
+
+ shuffle(bits, ARRAY_SIZE(bits));
+ for (j = 31; j >= 0; j--) {
+ x &= ~bits[j];
+ check_popcount(x, j);
+ }
+ assert(x == 0);
+ }
+}
+