11/* Tests for the Bsearch and Lsearch macros */
22
33#include <stdio.h>
4+ #include <stdbool.h>
45#include <stdlib.h>
56#include <inttypes.h>
67
@@ -25,8 +26,9 @@ static uint32_t reduce_to_bits(int n_bits, uint32_t v)
2526 return v >> (32 - n_bits );
2627}
2728
28- int main ( int argc , char * * argv )
29+ bool test1 ( void )
2930{
31+ printf ("test1: Search pseudo-random lists with duplicates.\n" );
3032 uint64_t rstate = 1234 ;
3133 const int Ns [] = { 0 , 1 , 2 , 3 , 10 , 100 , 1000 };
3234 const int bs [] = { 0 , 1 , 2 , 3 , 4 , 8 , 16 , 32 };
@@ -68,17 +70,17 @@ int main(int argc, char** argv)
6870 if (idx < 0 || idx > N ) {
6971 fprintf (stderr , "Error: Result out "
7072 "of range (N = %d): %d\n" , N , idx );
71- return 1 ;
73+ return false ;
7274 }
7375 if (idx < N && red (a [idx ]) < d ) {
7476 fprintf (stderr , "Error: V1 constraint "
7577 "not met.\n" );
76- return 1 ;
78+ return false ;
7779 }
7880 if (idx > 0 && red (a [idx - 1 ]) >= d ) {
7981 fprintf (stderr , "Error: V1 minimality "
8082 "not satisfied.\n" );
81- return 1 ;
83+ return false ;
8284 }
8385
8486 /* Variants
@@ -90,17 +92,17 @@ int main(int argc, char** argv)
9092 if (idx < 0 || idx > N ) {
9193 fprintf (stderr , "Error: Result out "
9294 "of range (N = %d): %d\n" , N , idx );
93- return 1 ;
95+ return false ;
9496 }
9597 if (idx < N && red (a [idx ]) <= d ) {
9698 fprintf (stderr , "Error: V2 constraint "
9799 "not met.\n" );
98- return 1 ;
100+ return false ;
99101 }
100102 if (idx > 0 && red (a [idx - 1 ]) > d ) {
101103 fprintf (stderr , "Error: V2 minimality "
102104 "not satisfied.\n" );
103- return 1 ;
105+ return false ;
104106 }
105107#undef red
106108
@@ -110,5 +112,31 @@ int main(int argc, char** argv)
110112 printf (" All checks pass.\n" );
111113 }
112114 }
113- return 0 ;
115+ return true;
116+ }
117+
118+ /* Test corner cases */
119+ bool test_corner (void )
120+ {
121+ printf ("test_corner: Check corner case invariants.\n" );
122+
123+ /* Searching an empty list always returns 0 */
124+ int j = -999 ;
125+ Bsearch (int , u , u < 10 , 0 , j );
126+ if (j != 0 ) {
127+ fprintf (stderr , "Error: Searching an empty array must "
128+ "return 0.\n" );
129+ return false;
130+ }
131+
132+ return true;
133+ }
134+
135+ int main (int argc , char * * argv )
136+ {
137+ if (!test1 ())
138+ return EXIT_FAILURE ;
139+ if (!test_corner ())
140+ return EXIT_FAILURE ;
141+ return EXIT_SUCCESS ;
114142}
0 commit comments