string-util: add strrstr() helper

This commit is contained in:
Lennart Poettering
2024-01-03 18:38:46 +01:00
parent cb599f881a
commit 63566c6b6f
3 changed files with 48 additions and 0 deletions
+23
View File
@@ -1519,3 +1519,26 @@ ssize_t strlevenshtein(const char *x, const char *y) {
return t1[yl];
}
char *strrstr(const char *haystack, const char *needle) {
const char *f = NULL;
size_t l;
/* Like strstr() but returns the last rather than the first occurence of "needle" in "haystack". */
if (!haystack || !needle)
return NULL;
l = strlen(needle);
/* Special case: for the empty string we return the very last possible occurence, i.e. *after* the
* last char, not before. */
if (l == 0)
return strchr(haystack, 0);
for (const char *p = haystack; *p; p++)
if (strncmp(p, needle, l) == 0)
f = p;
return (char*) f;
}
+2
View File
@@ -322,3 +322,5 @@ static inline int strdup_or_null(const char *s, char **ret) {
*ret = c;
return 1;
}
char *strrstr(const char *haystack, const char *needle);
+23
View File
@@ -1324,4 +1324,27 @@ TEST(strlevenshtein) {
assert_se(strlevenshtein("sunday", "saturday") == 3);
}
TEST(strrstr) {
assert_se(!strrstr(NULL, NULL));
assert_se(!strrstr("foo", NULL));
assert_se(!strrstr(NULL, "foo"));
const char *p = "foo";
assert_se(strrstr(p, "foo") == p);
assert_se(strrstr(p, "fo") == p);
assert_se(strrstr(p, "f") == p);
assert_se(strrstr(p, "oo") == p + 1);
assert_se(strrstr(p, "o") == p + 2);
assert_se(strrstr(p, "") == p + strlen(p));
assert_se(!strrstr(p, "bar"));
p = "xoxoxox";
assert_se(strrstr(p, "") == p + strlen(p));
assert_se(strrstr(p, "x") == p + 6);
assert_se(strrstr(p, "ox") == p + 5);
assert_se(strrstr(p, "xo") == p + 4);
assert_se(strrstr(p, "xox") == p + 4);
assert_se(!strrstr(p, "xx"));
}
DEFINE_TEST_MAIN(LOG_DEBUG);