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 /*
12  * The strrstr() function finds the last occurrence of the substring needle
13  * in the string haystack. The terminating nul characters are not compared.
14  */
strrstr(const char * haystack,const char * needle)15 char* FAST_FUNC strrstr(const char *haystack, const char *needle)
16 {
17 	char *r = NULL;
18 
19 	if (!needle[0])
20 		return (char*)haystack + strlen(haystack);
21 	while (1) {
22 		char *p = strstr(haystack, needle);
23 		if (!p)
24 			return r;
25 		r = p;
26 		haystack = p + 1;
27 	}
28 }
29 
30 #if ENABLE_UNIT_TEST
31 
BBUNIT_DEFINE_TEST(strrstr)32 BBUNIT_DEFINE_TEST(strrstr)
33 {
34 	static const struct {
35 		const char *h, *n;
36 		int pos;
37 	} test_array[] = {
38 		/* 0123456789 */
39 		{ "baaabaaab",  "aaa", 5  },
40 		{ "baaabaaaab", "aaa", 6  },
41 		{ "baaabaab",   "aaa", 1  },
42 		{ "aaa",        "aaa", 0  },
43 		{ "aaa",        "a",   2  },
44 		{ "aaa",        "bbb", -1 },
45 		{ "a",          "aaa", -1 },
46 		{ "aaa",        "",    3  },
47 		{ "",           "aaa", -1 },
48 		{ "",           "",    0  },
49 	};
50 
51 	int i;
52 
53 	i = 0;
54 	while (i < sizeof(test_array) / sizeof(test_array[0])) {
55 		const char *r = strrstr(test_array[i].h, test_array[i].n);
56 		if (r == NULL)
57 			r = test_array[i].h - 1;
58 		BBUNIT_ASSERT_EQ(r, test_array[i].h + test_array[i].pos);
59 		i++;
60 	}
61 
62 	BBUNIT_ENDTEST;
63 }
64 
65 #endif /* ENABLE_UNIT_TEST */
66