memeq.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // SPDX-License-Identifier: GPL-2.0 or GPL-3.0
  2. // Copyright © 2018-2019 Ariadne Devos
  3. /* sHT -- test the sHT_memeq function */
  4. #include <sHT/string.h>
  5. #include <string.h>
  6. #include <stdio.h>
  7. /* Test a few special cases -- code that uses memeq and streq must come
  8. with their own tests, which supplements these.
  9. Symmetric cases are automatically generated, and the expected values are
  10. scrambled. */
  11. static const struct {
  12. const char *a;
  13. const char *b;
  14. size_t length;
  15. size_t expect;
  16. } cases[] = {
  17. /* It should not be accessed, because that's unnecessary
  18. -- it is allowed, however. */
  19. { .a = (char *) -1, .b = (char *) -2, .length = 0, .expect = 0 },
  20. /* zero-length */
  21. { .a = "", .b = "a", .length = 0, .expect = 0},
  22. /* don't be afraid of NUL */
  23. { .a = "", .b = "a", .length = 1, .expect = 1 },
  24. { .a = "", .b = "", .length = 1, .expect = 0 },
  25. { .a = "\0a", .b = "\0b", .length = 2, .expect = 1 },
  26. { .a = "\0a", .b = "\0b\xff", .length = 2, .expect = 1 },
  27. /* longer test cases -- exercise word-at-a-time implementations a little */
  28. { .a = "abcdefg\x00""abcdefg\x11", "abcdefg\x00""abcdefg\x11", .length = 16, .expect = 0 },
  29. { .a = "abcdefg\x00""abcdefg\x11""0", "abcdefg\x00""abcdefg\x11""0", .length = 17, .expect = 0 },
  30. { .a = "abcdefg\x00""abcdefg\x11", "abcdefg\x00""abcdefg\x12", .length = 16, .expect = 1 },
  31. { .a = "abcdefg\x00""abcdefg\x11""0", "abcdefg\x00""abcdefg\x11""1", .length = 17, .expect = 1 },
  32. };
  33. int
  34. main(void)
  35. {
  36. _Bool ioerr = 0;
  37. for (size_t i = 0; i < sizeof(cases)/sizeof(*cases); i++) {
  38. /* test the test case */
  39. if (!!memcmp(cases[i].a, cases[i].b, cases[i].length) != cases[i].expect)
  40. goto fail_testcase;
  41. if (sHT_memeq(cases[i].a, cases[i].b, 0, 1, cases[i].length) != cases[i].expect)
  42. goto fail;
  43. if (sHT_memeq(cases[i].b, cases[i].a, 0, 1, cases[i].length) != cases[i].expect)
  44. goto fail;
  45. if (sHT_memeq(cases[i].a, cases[i].b, 2000, 78, cases[i].length) != (cases[i].expect ? 78 : 2000))
  46. goto fail;
  47. if (sHT_memeq(cases[i].b, cases[i].a, 2000, 78, cases[i].length) != (cases[i].expect ? 78 : 2000))
  48. goto fail;
  49. }
  50. ioerr |= puts("PASS: memeq/special") < 0;
  51. ioerr |= puts("PASS: memeq/equi-stdlib") < 0;
  52. return ioerr ? 2 : 0;
  53. fail:
  54. ioerr |= puts("FAIL: memeq/special") < 0;
  55. ioerr |= puts("SKIP: memeq/equi-stdlib") < 0;
  56. return ioerr ? 2 : 1;
  57. fail_testcase:
  58. ioerr |= puts("FAIL: memeq/equi-stdlib") < 0;
  59. ioerr |= puts("SKIP: memeq/special") < 0;
  60. return ioerr ? 2 : 1;
  61. }