2008-05-28 14:19:27 +00:00
|
|
|
/* vi: set sw=4 ts=4: */
|
|
|
|
/*
|
|
|
|
* Utility routines.
|
|
|
|
*
|
2008-09-25 12:13:34 +00:00
|
|
|
* Copyright (C) 2008 Bernhard Reutner-Fischer
|
2008-05-28 14:19:27 +00:00
|
|
|
*
|
2010-08-16 18:14:46 +00:00
|
|
|
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
|
2008-05-28 14:19:27 +00:00
|
|
|
*/
|
|
|
|
|
2008-06-17 12:45:39 +00:00
|
|
|
#include "libbb.h"
|
2008-05-28 14:19:27 +00:00
|
|
|
|
2008-06-17 12:11:34 +00:00
|
|
|
/*
|
|
|
|
* The strrstr() function finds the last occurrence of the substring needle
|
|
|
|
* in the string haystack. The terminating nul characters are not compared.
|
|
|
|
*/
|
2008-06-27 02:52:20 +00:00
|
|
|
char* FAST_FUNC strrstr(const char *haystack, const char *needle)
|
2008-05-28 14:19:27 +00:00
|
|
|
{
|
2008-06-17 12:11:34 +00:00
|
|
|
char *r = NULL;
|
2008-06-18 19:49:46 +00:00
|
|
|
|
|
|
|
if (!needle[0])
|
2008-06-18 20:01:12 +00:00
|
|
|
return (char*)haystack + strlen(haystack);
|
2008-06-18 19:49:46 +00:00
|
|
|
while (1) {
|
2008-06-18 08:32:25 +00:00
|
|
|
char *p = strstr(haystack, needle);
|
2008-06-18 19:49:46 +00:00
|
|
|
if (!p)
|
|
|
|
return r;
|
|
|
|
r = p;
|
|
|
|
haystack = p + 1;
|
|
|
|
}
|
2008-05-28 14:19:27 +00:00
|
|
|
}
|
|
|
|
|
2014-06-22 14:30:41 +00:00
|
|
|
#if ENABLE_UNIT_TEST
|
|
|
|
|
|
|
|
BBUNIT_DEFINE_TEST(strrstr)
|
2008-06-17 12:11:34 +00:00
|
|
|
{
|
2008-06-18 19:49:46 +00:00
|
|
|
static const struct {
|
|
|
|
const char *h, *n;
|
|
|
|
int pos;
|
|
|
|
} test_array[] = {
|
|
|
|
/* 0123456789 */
|
|
|
|
{ "baaabaaab", "aaa", 5 },
|
|
|
|
{ "baaabaaaab", "aaa", 6 },
|
|
|
|
{ "baaabaab", "aaa", 1 },
|
|
|
|
{ "aaa", "aaa", 0 },
|
|
|
|
{ "aaa", "a", 2 },
|
|
|
|
{ "aaa", "bbb", -1 },
|
|
|
|
{ "a", "aaa", -1 },
|
|
|
|
{ "aaa", "", 3 },
|
|
|
|
{ "", "aaa", -1 },
|
|
|
|
{ "", "", 0 },
|
|
|
|
};
|
2008-06-17 12:11:34 +00:00
|
|
|
|
2008-06-18 19:49:46 +00:00
|
|
|
int i;
|
2008-06-17 12:11:34 +00:00
|
|
|
|
2008-06-18 19:49:46 +00:00
|
|
|
i = 0;
|
|
|
|
while (i < sizeof(test_array) / sizeof(test_array[0])) {
|
|
|
|
const char *r = strrstr(test_array[i].h, test_array[i].n);
|
|
|
|
if (r == NULL)
|
|
|
|
r = test_array[i].h - 1;
|
2014-06-22 14:30:41 +00:00
|
|
|
BBUNIT_ASSERT_EQ(r, test_array[i].h + test_array[i].pos);
|
2008-06-18 19:49:46 +00:00
|
|
|
i++;
|
|
|
|
}
|
2008-06-17 12:11:34 +00:00
|
|
|
|
2014-06-22 14:30:41 +00:00
|
|
|
BBUNIT_ENDTEST;
|
2008-06-17 12:11:34 +00:00
|
|
|
}
|
2014-06-22 14:30:41 +00:00
|
|
|
|
|
|
|
#endif /* ENABLE_UNIT_TEST */
|