From: Florian Forster Date: Mon, 18 Dec 2023 10:26:48 +0000 (+0100) Subject: common: Add `string_has_suffix`. X-Git-Tag: 6.0.0-rc0~32^2~4 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=f1447f9aaf4e523df7f87a1a0f7d3df8e97c39d5;p=thirdparty%2Fcollectd.git common: Add `string_has_suffix`. --- diff --git a/src/utils/common/common.c b/src/utils/common/common.c index 34258f09e..ad72e93ff 100644 --- a/src/utils/common/common.c +++ b/src/utils/common/common.c @@ -423,6 +423,21 @@ int strjoin(char *buffer, size_t buffer_size, char **fields, size_t fields_num, return (int)buffer_req; } +bool string_has_suffix(char const *s, char const *suffix) { + if (s == NULL || suffix == NULL) { + return false; + } + + size_t s_len = strlen(s); + size_t suffix_len = strlen(suffix); + if (s_len < suffix_len) { + return false; + } + + s += (s_len - suffix_len); + return strcmp(s, suffix) == 0; +} + int escape_string(char *buffer, size_t buffer_size) { char *temp; size_t j; diff --git a/src/utils/common/common.h b/src/utils/common/common.h index 51b4032c0..dd8007aef 100644 --- a/src/utils/common/common.h +++ b/src/utils/common/common.h @@ -179,6 +179,11 @@ int strsplit(char *string, char **fields, size_t size); int strjoin(char *dst, size_t dst_len, char **fields, size_t fields_num, const char *sep); + +/* string_has_suffix returns true if s ends with suffix. If either s or suffix + * are NULL, false is returned. */ +bool string_has_suffix(char const *s, char const *suffix); + /* * NAME * escape_slashes diff --git a/src/utils/common/common_test.c b/src/utils/common/common_test.c index d4a667d4c..76ff77d51 100644 --- a/src/utils/common/common_test.c +++ b/src/utils/common/common_test.c @@ -361,6 +361,27 @@ DEF_TEST(format_values) { return 0; } +DEF_TEST(string_has_suffix) { + struct { + char const *s; + char const *suffix; + bool want; + } cases[] = { + {"foo.bar", "bar", true}, + {"foo.qux", "bar", false}, + {"foo.Bar", "bar", false}, + {"foo", "foo", true}, + {"foo", "foo.bar", false}, + {"foo", NULL, false}, + {NULL, "foo", false}, + }; + for (size_t i = 0; i < STATIC_ARRAY_SIZE(cases); i++) { + EXPECT_EQ_INT(cases[i].want, string_has_suffix(cases[i].s, cases[i].suffix)); + } + + return 0; +} + int main(void) { RUN_TEST(sstrncpy); RUN_TEST(sstrdup); @@ -371,6 +392,7 @@ int main(void) { RUN_TEST(strunescape); RUN_TEST(value_to_rate); RUN_TEST(format_values); + RUN_TEST(string_has_suffix); END_TEST; }