]> git.ozlabs.org Git - ccan/blob - ccan/ilog/test/run.c
Tim's ilog module.
[ccan] / ccan / ilog / test / run.c
1 #include <stdio.h>
2 #include "ilog/ilog.h"
3 #include "tap/tap.h"
4 #if defined(__GNUC_PREREQ)
5 # if __GNUC_PREREQ(4,2)
6 #  pragma GCC diagnostic ignored "-Wparentheses"
7 # endif
8 #endif
9
10 /*Dead simple (but slow) versions to compare against.*/
11
12 static int test_ilog32(uint32_t _v){
13   int ret;
14   for(ret=0;_v;ret++)_v>>=1;
15   return ret;
16 }
17
18 static int test_ilog64(uint64_t _v){
19   int ret;
20   for(ret=0;_v;ret++)_v>>=1;
21   return ret;
22 }
23
24 #define NTRIALS (64)
25
26 int main(int _argc,const char *_argv[]){
27   int nmatches;
28   int i;
29   int j;
30   /*This is how many tests you plan to run.*/
31   plan_tests(2);
32   nmatches=0;
33   for(i=0;i<=32;i++){
34     uint32_t v;
35     /*Test each bit in turn (and 0).*/
36     v=i?(uint32_t)1U<<i-1:0;
37     for(j=0;j<NTRIALS;j++){
38       int l;
39       l=test_ilog32(v);
40       if(ILOG_32(v)!=l){
41         fprintf(stderr,"ILOG_32(0x%08lX): %i != %i\n",(long)v,ILOG_32(v),l);
42       }
43       else nmatches++;
44       if(ilog32(v)!=l){
45         fprintf(stderr,"ilog32(0x%08lX): %i != %i\n",(long)v,ilog32(v),l);
46       }
47       else nmatches++;
48       if(STATIC_ILOG_32(v)!=l){
49         fprintf(stderr,"STATIC_ILOG_32(0x%08lX): %i != %i\n",
50          (long)v,STATIC_ILOG_32(v),l);
51       }
52       else nmatches++;
53       /*Also try a few more pseudo-random values with at most the same number
54          of bits.*/
55       v=1103515245U*v+12345U&0xFFFFFFFFU>>(33-i>>1)>>(32-i>>1);
56     }
57   }
58   ok1(nmatches==3*(32+1)*NTRIALS);
59   nmatches=0;
60   for(i=0;i<=64;i++){
61     uint64_t v;
62     /*Test each bit in turn (and 0).*/
63     v=i?(uint64_t)1U<<i-1:0;
64     for(j=0;j<NTRIALS;j++){
65       int l;
66       l=test_ilog64(v);
67       if(ILOG_64(v)!=l){
68         fprintf(stderr,"ILOG_64(0x%016llX): %i != %i\n",
69          (long long)v,ILOG_64(v),l);
70       }
71       else nmatches++;
72       if(ilog64(v)!=l){
73         fprintf(stderr,"ilog64(0x%016llX): %i != %i\n",
74          (long long)v,ilog64(v),l);
75       }
76       else nmatches++;
77       if(STATIC_ILOG_64(v)!=l){
78         fprintf(stderr,"STATIC_ILOG_64(0x%016llX): %i != %i\n",
79          (long long)v,STATIC_ILOG_64(v),l);
80       }
81       else nmatches++;
82       /*Also try a few more pseudo-random values with at most the same number
83          of bits.*/
84       v=(uint64_t)(2862933555777941757ULL*v+3037000493ULL
85        &0xFFFFFFFFFFFFFFFFULL>>(65-i>>1)>>(64-i>>1));
86     }
87   }
88   ok1(nmatches==3*(64+1)*NTRIALS);
89   return exit_status();
90 }