1 /* Test program for sorting and searching in lib/stdlib.c.
3 Attempts to test the sorting and searching functionality that
4 is not sufficiently tested elsewhere in Pintos.
6 This is not a test we will run on your submitted projects.
7 It is here for completeness.
16 #include "threads/test.h"
18 /* Maximum number of elements in an array that we will test. */
21 static void shuffle (int[], size_t);
22 static int compare_ints (const void *, const void *);
23 static void verify_order (const int[], size_t);
24 static void verify_bsearch (const int[], size_t);
26 /* Test sorting and searching implementations. */
32 printf ("testing various size arrays:");
33 for (cnt = 0; cnt < MAX_CNT; cnt = cnt * 4 / 3 + 1)
38 for (repeat = 0; repeat < 10; repeat++)
40 static int values[MAX_CNT];
43 /* Put values 0...CNT in random order in VALUES. */
44 for (i = 0; i < cnt; i++)
46 shuffle (values, cnt);
48 /* Sort VALUES, then verify ordering. */
49 qsort (values, cnt, sizeof *values, compare_ints);
50 verify_order (values, cnt);
51 verify_bsearch (values, cnt);
56 printf ("stdlib: PASS\n");
59 /* Shuffles the CNT elements in ARRAY into random order. */
61 shuffle (int *array, size_t cnt)
65 for (i = 0; i < cnt; i++)
67 size_t j = i + random_ulong () % (cnt - i);
74 /* Returns 1 if *A is greater than *B,
76 -1 if *A is less than *B. */
78 compare_ints (const void *a_, const void *b_)
83 return *a < *b ? -1 : *a > *b;
86 /* Verifies that ARRAY contains the CNT ints 0...CNT-1. */
88 verify_order (const int *array, size_t cnt)
92 for (i = 0; (size_t) i < cnt; i++)
93 ASSERT (array[i] == i);
96 /* Checks that bsearch() works properly in ARRAY. ARRAY must
97 contain the values 0...CNT-1. */
99 verify_bsearch (const int *array, size_t cnt)
101 int not_in_array[] = {0, -1, INT_MAX, MAX_CNT, MAX_CNT + 1, MAX_CNT * 2};
104 /* Check that all the values in the array are found properly. */
105 for (i = 0; (size_t) i < cnt; i++)
106 ASSERT (bsearch (&i, array, cnt, sizeof *array, compare_ints)
109 /* Check that some values not in the array are not found. */
110 not_in_array[0] = cnt;
111 for (i = 0; (size_t) i < sizeof not_in_array / sizeof *not_in_array; i++)
112 ASSERT (bsearch (¬_in_array[i], array, cnt, sizeof *array, compare_ints)