strrstr.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Utility routines.
  4. *
  5. * Copyright (C) 2008 Bernhard Reutner-Fischer
  6. *
  7. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  8. */
  9. #include "libbb.h"
  10. /*
  11. * The strrstr() function finds the last occurrence of the substring needle
  12. * in the string haystack. The terminating nul characters are not compared.
  13. */
  14. char* FAST_FUNC strrstr(const char *haystack, const char *needle)
  15. {
  16. char *r = NULL;
  17. if (!needle[0])
  18. return (char*)haystack + strlen(haystack);
  19. while (1) {
  20. char *p = strstr(haystack, needle);
  21. if (!p)
  22. return r;
  23. r = p;
  24. haystack = p + 1;
  25. }
  26. }
  27. #if ENABLE_UNIT_TEST
  28. BBUNIT_DEFINE_TEST(strrstr)
  29. {
  30. static const struct {
  31. const char *h, *n;
  32. int pos;
  33. } test_array[] = {
  34. /* 0123456789 */
  35. { "baaabaaab", "aaa", 5 },
  36. { "baaabaaaab", "aaa", 6 },
  37. { "baaabaab", "aaa", 1 },
  38. { "aaa", "aaa", 0 },
  39. { "aaa", "a", 2 },
  40. { "aaa", "bbb", -1 },
  41. { "a", "aaa", -1 },
  42. { "aaa", "", 3 },
  43. { "", "aaa", -1 },
  44. { "", "", 0 },
  45. };
  46. int i;
  47. i = 0;
  48. while (i < sizeof(test_array) / sizeof(test_array[0])) {
  49. const char *r = strrstr(test_array[i].h, test_array[i].n);
  50. if (r == NULL)
  51. r = test_array[i].h - 1;
  52. BBUNIT_ASSERT_EQ(r, test_array[i].h + test_array[i].pos);
  53. i++;
  54. }
  55. BBUNIT_ENDTEST;
  56. }
  57. #endif /* ENABLE_UNIT_TEST */