Kaynağa Gözat

Merge pull request #2463 from dgquintas/bitsetmacros

Added bitset macro ops
Craig Tiller 10 yıl önce
ebeveyn
işleme
be2b9b2563
2 değiştirilmiş dosya ile 34 ekleme ve 0 silme
  1. 20 0
      include/grpc/support/useful.h
  2. 14 0
      test/core/support/useful_test.c

+ 20 - 0
include/grpc/support/useful.h

@@ -52,4 +52,24 @@
     b = x;               \
   } while (0)
 
+/** Set the \a n-th bit of \a i (a mutable pointer). */
+#define GPR_BITSET(i, n) ((*(i)) |= (1u << (n)))
+
+/** Clear the \a n-th bit of \a i (a mutable pointer). */
+#define GPR_BITCLEAR(i, n) ((*(i)) &= ~(1u << (n)))
+
+/** Get the \a n-th bit of \a i */
+#define GPR_BITGET(i, n) (((i) & (1u << (n))) != 0)
+
+#define GPR_INTERNAL_HEXDIGIT_BITCOUNT(x)                        \
+  ((x) - (((x) >> 1) & 0x77777777) - (((x) >> 2) & 0x33333333) - \
+   (((x) >> 3) & 0x11111111))
+
+/** Returns number of bits set in bitset \a i */
+#define GPR_BITCOUNT(i)                          \
+  (((GPR_INTERNAL_HEXDIGIT_BITCOUNT(i) +         \
+     (GPR_INTERNAL_HEXDIGIT_BITCOUNT(i) >> 4)) & \
+    0x0f0f0f0f) %                                \
+   255)
+
 #endif  /* GRPC_SUPPORT_USEFUL_H */

+ 14 - 0
test/core/support/useful_test.c

@@ -39,6 +39,7 @@
 int main(int argc, char **argv) {
   int four[4];
   int five[5];
+  gpr_uint32 bitset = 0;
   grpc_test_init(argc, argv);
 
   GPR_ASSERT(GPR_MIN(1, 2) == 1);
@@ -55,5 +56,18 @@ int main(int argc, char **argv) {
   GPR_ASSERT(GPR_ARRAY_SIZE(four) == 4);
   GPR_ASSERT(GPR_ARRAY_SIZE(five) == 5);
 
+  GPR_ASSERT(GPR_BITCOUNT((1u << 31) - 1) == 31);
+  GPR_ASSERT(GPR_BITCOUNT(1u << 3) == 1);
+  GPR_ASSERT(GPR_BITCOUNT(0) == 0);
+
+  GPR_ASSERT(GPR_BITSET(&bitset, 3) == 8);
+  GPR_ASSERT(GPR_BITCOUNT(bitset) == 1);
+  GPR_ASSERT(GPR_BITGET(bitset, 3) == 1);
+  GPR_ASSERT(GPR_BITSET(&bitset, 1) == 10);
+  GPR_ASSERT(GPR_BITCOUNT(bitset) == 2);
+  GPR_ASSERT(GPR_BITCLEAR(&bitset, 3) == 2);
+  GPR_ASSERT(GPR_BITCOUNT(bitset) == 1);
+  GPR_ASSERT(GPR_BITGET(bitset, 3) == 0);
+
   return 0;
 }