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.
This commit is contained in:
Peter Hutterer 2021-05-18 11:00:25 +10:00
parent 9bbe5c7517
commit d8a9534a9a
2 changed files with 39 additions and 0 deletions

View file

@ -32,6 +32,28 @@ extern "C" {
#include <stdbool.h>
#include <errno.h>
#include <spa/utils/defs.h>
/**
* \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.

View file

@ -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;
}