From d8a9534a9afc09afbb387eb28b01b01f32d5ffe4 Mon Sep 17 00:00:00 2001 From: Peter Hutterer Date: Tue, 18 May 2021 11:00:25 +1000 Subject: [PATCH] spa/string: add spa_streq() and spa_strneq() for string equality Easier to use than strcmp() since their return value matches expectations. And they do what is expected with NULL strings, two NULL pointers are equal, one NULL pointer is not equal. --- spa/include/spa/utils/string.h | 22 ++++++++++++++++++++++ spa/tests/test-utils.c | 17 +++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/spa/include/spa/utils/string.h b/spa/include/spa/utils/string.h index eddffe948..31b3a5c8a 100644 --- a/spa/include/spa/utils/string.h +++ b/spa/include/spa/utils/string.h @@ -32,6 +32,28 @@ extern "C" { #include #include +#include + +/** + * \return true if the two strings are equal, false otherwise + * + * If both \a a and \a b are NULL, the two are considered equal. + */ +static inline bool spa_streq(const char *s1, const char *s2) +{ + return SPA_LIKELY(s1 && s2) ? strcmp(s1, s2) == 0 : s1 == s2; +} + +/** + * \return true if the two strings are equal, false otherwise + * + * If both \a a and \a b are NULL, the two are considered equal. + */ +static inline bool spa_strneq(const char *s1, const char *s2, size_t len) +{ + return SPA_LIKELY(s1 && s2) ? strncmp(s1, s2, len) == 0 : s1 == s2; +} + /** * Convert \a str to an int32_t with the given \a base and store the * result in \a val. diff --git a/spa/tests/test-utils.c b/spa/tests/test-utils.c index fdf75e678..7f55ab817 100644 --- a/spa/tests/test-utils.c +++ b/spa/tests/test-utils.c @@ -477,6 +477,22 @@ static void test_strtol(void) spa_assert(!spa_atoi32(NULL, &v, 16) && v == 0xabcd); } +static void test_streq(void) +{ + spa_assert(spa_streq(NULL, NULL)); + spa_assert(spa_streq("", "")); + spa_assert(spa_streq("a", "a")); + spa_assert(spa_streq("abc", "abc")); + spa_assert(!spa_streq(NULL, "abc")); + spa_assert(!spa_streq("abc", NULL)); + + spa_assert(spa_strneq("abc", "aaa", 1)); + spa_assert(spa_strneq("abc", "abc", 7)); + spa_assert(!spa_strneq("abc", "aaa", 2)); + spa_assert(!spa_strneq("abc", NULL, 7)); + spa_assert(!spa_strneq(NULL, "abc", 7)); +} + int main(int argc, char *argv[]) { test_abi(); @@ -487,5 +503,6 @@ int main(int argc, char *argv[]) test_hook(); test_ringbuffer(); test_strtol(); + test_streq(); return 0; }