diff --git a/core/string.c b/core/string.c index 286a4576..0bef7953 100644 --- a/core/string.c +++ b/core/string.c @@ -94,3 +94,27 @@ int string_compare(const gchar *lhs, const gchar *rhs) return -1; return g_utf8_collate(lhs, rhs); } + +int string_compare_tokens(gchar **lhs, gchar **rhs) +{ + unsigned int i, cmp; + + if (!lhs[0] && rhs[0]) + return 1; + if (lhs[0] && !rhs[0]) + return -1; + + for (i = 0; lhs[i]; i++) { + if (!rhs[i]) + break; + cmp = g_utf8_collate(lhs[i], rhs[i]); + if (cmp != 0) + return cmp; + } + + if (lhs[i]) + return 1; + if (rhs[i]) + return -1; + return 0; +} diff --git a/include/core/string.h b/include/core/string.h index 8f2e7814..4f154448 100644 --- a/include/core/string.h +++ b/include/core/string.h @@ -32,6 +32,7 @@ gchar *string_lowercase(const gchar *); * if ret > 0: lhs > rhs, or lhs is empty. */ int string_compare(const gchar *, const gchar *); +int string_compare_tokens(gchar **, gchar **); /* Returns True if the two strings match. */ static inline bool string_match(const gchar *a, const gchar *b) diff --git a/tests/core/string.c b/tests/core/string.c index f378b1dd..727f8ed6 100644 --- a/tests/core/string.c +++ b/tests/core/string.c @@ -101,6 +101,32 @@ void test_compare() test_equal(string_compare("A", ""), -1); } +void test_compare_tokens() +{ + gchar *a[2] = { "a", NULL }; + gchar *A[2] = { "A", NULL }; + gchar *B[2] = { "B", NULL }; + gchar *aa[3] = { "a", "a", NULL }; + gchar *ab[3] = { "a", "b", NULL }; + gchar *ba[3] = { "b", "a", NULL }; + gchar *null[1] = { NULL }; + + test_equal(string_compare_tokens(A, A), 0); + test_equal(string_compare_tokens(a, a), 0); + test_equal(string_compare_tokens(A, B), -1); + test_equal(string_compare_tokens(B, A), 1); + + test_equal(string_compare_tokens(null, null), 0); + test_equal(string_compare_tokens(null, A), 1); + test_equal(string_compare_tokens(A, null), -1); + + test_equal(string_compare_tokens(aa, aa), 0); + test_equal(string_compare_tokens(a, aa), -1); + test_equal(string_compare_tokens(aa, a), 1); + test_equal(string_compare_tokens(ab, ba), -1); + test_equal(string_compare_tokens(ba, ab), 1); +} + void test_match() { test_equal(string_match(NULL, NULL), (bool)false); @@ -124,6 +150,7 @@ DECLARE_UNIT_TESTS( UNIT_TEST("Date to String", test_date), UNIT_TEST("String Lowercase", test_lowercase), UNIT_TEST("String Comparison", test_compare), + UNIT_TEST("String Comparison (Tokens)", test_compare_tokens), UNIT_TEST("String Match", test_match), UNIT_TEST("String Length", test_length), );