2008-05-28 19:49:27 +05:30
|
|
|
/* vi: set sw=4 ts=4: */
|
|
|
|
/*
|
|
|
|
* Utility routines.
|
|
|
|
*
|
2008-09-25 17:43:34 +05:30
|
|
|
* Copyright (C) 2008 Bernhard Reutner-Fischer
|
2008-05-28 19:49:27 +05:30
|
|
|
*
|
2010-08-16 23:44:46 +05:30
|
|
|
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
|
2008-05-28 19:49:27 +05:30
|
|
|
*/
|
|
|
|
|
2008-06-17 18:15:39 +05:30
|
|
|
#include "libbb.h"
|
2008-05-28 19:49:27 +05:30
|
|
|
|
2008-06-17 17:41:34 +05:30
|
|
|
/*
|
|
|
|
* 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 08:22:20 +05:30
|
|
|
char* FAST_FUNC strrstr(const char *haystack, const char *needle)
|
2008-05-28 19:49:27 +05:30
|
|
|
{
|
2008-06-17 17:41:34 +05:30
|
|
|
char *r = NULL;
|
2008-06-19 01:19:46 +05:30
|
|
|
|
|
|
|
if (!needle[0])
|
2008-06-19 01:31:12 +05:30
|
|
|
return (char*)haystack + strlen(haystack);
|
2008-06-19 01:19:46 +05:30
|
|
|
while (1) {
|
2008-06-18 14:02:25 +05:30
|
|
|
char *p = strstr(haystack, needle);
|
2008-06-19 01:19:46 +05:30
|
|
|
if (!p)
|
|
|
|
return r;
|
|
|
|
r = p;
|
|
|
|
haystack = p + 1;
|
|
|
|
}
|
2008-05-28 19:49:27 +05:30
|
|
|
}
|
|
|
|
|
2014-06-22 20:00:41 +05:30
|
|
|
#if ENABLE_UNIT_TEST
|
|
|
|
|
|
|
|
BBUNIT_DEFINE_TEST(strrstr)
|
2008-06-17 17:41:34 +05:30
|
|
|
{
|
2008-06-19 01:19:46 +05:30
|
|
|
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 17:41:34 +05:30
|
|
|
|
2008-06-19 01:19:46 +05:30
|
|
|
int i;
|
2008-06-17 17:41:34 +05:30
|
|
|
|
2008-06-19 01:19:46 +05:30
|
|
|
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 20:00:41 +05:30
|
|
|
BBUNIT_ASSERT_EQ(r, test_array[i].h + test_array[i].pos);
|
2008-06-19 01:19:46 +05:30
|
|
|
i++;
|
|
|
|
}
|
2008-06-17 17:41:34 +05:30
|
|
|
|
2014-06-22 20:00:41 +05:30
|
|
|
BBUNIT_ENDTEST;
|
2008-06-17 17:41:34 +05:30
|
|
|
}
|
2014-06-22 20:00:41 +05:30
|
|
|
|
|
|
|
#endif /* ENABLE_UNIT_TEST */
|