util: New function log_2_floor().
[sliver-openvswitch.git] / tests / test-util.c
1 /*
2  * Copyright (c) 2011 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include <inttypes.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22
23 #include "random.h"
24 #include "util.h"
25
26 static void
27 check(uint32_t x, int n)
28 {
29     if (log_2_floor(x) != n) {
30         fprintf(stderr, "log_2_floor(%"PRIu32") is %d but should be %d\n",
31                 x, log_2_floor(x), n);
32         abort();
33     }
34 }
35
36 int
37 main(void)
38 {
39     int n;
40
41     for (n = 0; n < 32; n++) {
42         /* Check minimum x that has log2(x) == n. */
43         check(1 << n, n);
44
45         /* Check maximum x that has log2(x) == n. */
46         check((1 << n) | ((1 << n) - 1), n);
47
48         /* Check a random value in the middle. */
49         check((random_uint32() & ((1 << n) - 1)) | (1 << n), n);
50     }
51     return 0;
52 }