]>
git.ipfire.org Git - thirdparty/bird.git/blob - lib/bitops_test.c
2 * BIRD Library -- Generic Bit Operations Tests
4 * (c) 2015 CZ.NIC z.s.p.o.
6 * Can be freely distributed and used under the terms of the GNU GPL.
9 #include "test/birdtest.h"
10 #include "test/bt-utils.h" /* naive_pow() */
12 #include "lib/bitops.h"
15 #define CHECK_BIT(var,pos) ((var) & (u32)(1<<(pos)))
23 bt_assert(u32_mkmask(0) == 0x00000000);
24 for (i
= 1; i
<= 32; i
++)
26 compute
= u32_mkmask(i
);
27 expect
= (u32
) (0xffffffff << (32-i
));
28 bt_assert_msg(compute
== expect
, "u32_mkmask(%d) = 0x%08X, expected 0x%08X", i
, compute
, expect
);
35 u32_masklen_expected(u32 mask
)
40 for (j
= 0; j
<= 32; j
++)
41 if (mask
== (j
? (0xffffffff << (32-j
)) : 0)) /* Shifting 32-bit value by 32 bits is undefined behavior */
44 if (!valid
&& mask
!= 0)
47 for (j
= 0; j
<= 31; j
++)
48 if (CHECK_BIT(mask
, (31-j
)))
58 int expected
, masklen
;
60 expected
= u32_masklen_expected(mask
);
61 masklen
= u32_masklen(mask
);
62 int ok
= (expected
== masklen
);
63 bt_debug("u32_masklen(Ox%08x) = %d, expected %d %s\n", mask
, masklen
, expected
, ok
? "OK" : "FAIL!");
72 check_mask(0x82828282);
73 check_mask(0x00000000);
75 for (i
= 0; i
<= 32; i
++)
76 check_mask(((u32
) (i
? (0xffffffff << (32-i
)) : 0)) & 0xffffffff); /* Shifting 32-bit value by 32 bits is undefined behavior */
78 for (i
= 0; i
<= MAX_NUM
; i
++)
79 check_mask(bt_random());
87 u32 log
= u32_log2(n
);
88 u32 low
= bt_naive_pow(2, log
);
89 u32 high
= bt_naive_pow(2, log
+1);
91 bt_assert_msg(n
>= low
&& n
< high
,
92 "u32_log2(%u) = %u, %u should be in the range <%u, %u)",
93 n
, log
, n
, low
, high
);
101 for (i
= 0; i
< 31; i
++)
102 bt_assert(u32_log2(bt_naive_pow(2, i
+1)) == i
+1);
104 for (i
= 1; i
< MAX_NUM
; i
++)
107 for (i
= 1; i
< MAX_NUM
; i
++)
108 check_log2(((u32
) bt_random()) % 0x0fffffff);
114 main(int argc
, char *argv
[])
118 bt_test_suite(t_mkmask
, "u32_mkmask()");
119 bt_test_suite(t_masklen
, "u32_masklen()");
120 bt_test_suite(t_log2
, "u32_log2()");
122 return bt_exit_value();