From 023bae737c7dcfda2fa4efac04d969d7c4366b41 Mon Sep 17 00:00:00 2001 From: Anna Schumaker Date: Thu, 24 Sep 2015 13:57:42 -0400 Subject: [PATCH] core/string: Add a function for comparing strings And switch over the GenericTag to using it. Signed-off-by: Anna Schumaker --- core/string.c | 12 ++++++++++++ core/tags/generic.cpp | 6 +----- include/core/string.h | 9 +++++++++ tests/core/string.c | 12 ++++++++++++ 4 files changed, 34 insertions(+), 5 deletions(-) diff --git a/core/string.c b/core/string.c index dfa1a43d..be6ad6ba 100644 --- a/core/string.c +++ b/core/string.c @@ -64,3 +64,15 @@ gchar *string_lowercase(const gchar *str) return res; } + +int string_compare(const gchar *lhs, const gchar *rhs) +{ + if (strlen(lhs) == 0) { + if (strlen(rhs) == 0) + return 0; + return 1; + } + if (strlen(rhs) == 0) + return -1; + return g_strcmp0(lhs, rhs); +} diff --git a/core/tags/generic.cpp b/core/tags/generic.cpp index e446ed48..650449b0 100644 --- a/core/tags/generic.cpp +++ b/core/tags/generic.cpp @@ -53,9 +53,5 @@ const std::string &GenericTag :: lowercase() int GenericTag :: compare(const GenericTag *rhs) { - if (_lower.size() == 0) - return 1; - if (rhs->_lower.size() == 0) - return -1; - return _lower.compare(rhs->_lower); + return string_compare(_lower.c_str(), rhs->_lower.c_str()); } diff --git a/include/core/string.h b/include/core/string.h index 7b6ed084..f97828d3 100644 --- a/include/core/string.h +++ b/include/core/string.h @@ -20,4 +20,13 @@ gchar *string_sec2str_long(unsigned int); /* Convert the input string to lowercase, dropping special characters. */ gchar *string_lowercase(const gchar *); +/* + * Compare two strings. + * + * if ret < 0: lhs < rhs, or rhs is empty. + * if ret = 0: lhs == rhs. + * if ret > 0: lhs > rhs, or lhs is empty. + */ +int string_compare(const gchar *, const gchar *); + #endif /* OCARINA_CORE_STRING_H */ diff --git a/tests/core/string.c b/tests/core/string.c index 9cb33ea4..fef40770 100644 --- a/tests/core/string.c +++ b/tests/core/string.c @@ -69,11 +69,23 @@ void test_lowercase() test_equal(swap(string_lowercase("! __test(TEXT) + __test(\"TEXT\")")), "test text test text"); test_equal(swap(string_lowercase("Test~tEXt\\123")), "test text 123"); +} +void test_compare() +{ + test_equal(string_compare("A", "A"), 0); + test_equal(string_compare("a", "a"), 0); + test_equal(string_compare("A", "B"), -1); + test_equal(string_compare("B", "A"), 1); + + test_equal(string_compare("", ""), 0); + test_equal(string_compare("", "A"), 1); + test_equal(string_compare("A", ""), -1); } DECLARE_UNIT_TESTS( UNIT_TEST("Seconds to String", test_sec2str), UNIT_TEST("Seconds to String (Long)", test_sec2str_long), UNIT_TEST("String Lowercase", test_lowercase), + UNIT_TEST("String Comparison", test_compare), );