2
0

bsearch.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include "test_helpers.h"
  4. int int_cmp(const void* a, const void* b) {
  5. return *(const int*) a - *(const int*) b;
  6. }
  7. #define BSEARCH_TEST_INT(key, arr, len, expect) \
  8. do { \
  9. void* res = bsearch((const void*) &key, (void*) arr, len, sizeof(int), int_cmp); \
  10. if (res != expect) { \
  11. printf("FAIL bsearch for %d in [", key); \
  12. size_t i = 0; \
  13. for (; i < len; ++i) printf("%d,", arr[i]); \
  14. printf("] expected %p but got %p\n", (void*) expect, res); \
  15. exit(EXIT_FAILURE); \
  16. } \
  17. } while (0)
  18. int main(void) {
  19. int x = 0;
  20. int y = 1024;
  21. // TODO: Zero sized arrays are a non-standard GNU extension
  22. //int empty[] = {};
  23. //BSEARCH_TEST_INT(x, empty, 0, NULL);
  24. int singleton[] = {42};
  25. printf("%p\n%p\n", singleton, &singleton[1]);
  26. BSEARCH_TEST_INT(x, singleton, 1, NULL);
  27. BSEARCH_TEST_INT(singleton[0], singleton, 1, &singleton[0]);
  28. BSEARCH_TEST_INT(y, singleton, 1, NULL);
  29. int two[] = {14, 42};
  30. BSEARCH_TEST_INT(x, two, 2, NULL);
  31. BSEARCH_TEST_INT(y, two, 2, NULL);
  32. BSEARCH_TEST_INT(two[0], two, 2, &two[0]);
  33. BSEARCH_TEST_INT(two[0], two, 1, &two[0]);
  34. BSEARCH_TEST_INT(two[1], two, 2, &two[1]);
  35. BSEARCH_TEST_INT(two[1], two, 1, NULL);
  36. int three[] = {-5, -1, 4};
  37. BSEARCH_TEST_INT(three[0], three, 3, &three[0]);
  38. BSEARCH_TEST_INT(three[1], three, 3, &three[1]);
  39. BSEARCH_TEST_INT(three[2], three, 3, &three[2]);
  40. int big[] = {-19, -13, -7, -3, 2, 5, 11};
  41. BSEARCH_TEST_INT(big[0], big, 7, big);
  42. BSEARCH_TEST_INT(big[6], big, 7, &big[6]);
  43. BSEARCH_TEST_INT(big[3], big, 7, &big[3]);
  44. BSEARCH_TEST_INT(x, big, 7, NULL);
  45. printf("PASS bsearch\n");
  46. }