From 98faba93d1587a696aeadc75cc3d2527ad02f576 Mon Sep 17 00:00:00 2001 From: Anna Schumaker Date: Tue, 29 Mar 2016 08:11:49 -0400 Subject: [PATCH] core/string: Add a string_length() function This is a wrapper around strlen(), but checks for a NULL pointer first. Signed-off-by: Anna Schumaker --- include/core/string.h | 6 ++++++ tests/core/string.c | 9 +++++++++ 2 files changed, 15 insertions(+) diff --git a/include/core/string.h b/include/core/string.h index 7c3f6ef6..0ae8daec 100644 --- a/include/core/string.h +++ b/include/core/string.h @@ -32,4 +32,10 @@ gchar *string_lowercase(const gchar *); */ int string_compare(const gchar *, const gchar *); +/* Return the length of the string, with NULL checks */ +static inline int string_length(const gchar *str) +{ + return str ? strlen(str) : 0; +} + #endif /* OCARINA_CORE_STRING_H */ diff --git a/tests/core/string.c b/tests/core/string.c index 11ee5d24..edf62b67 100644 --- a/tests/core/string.c +++ b/tests/core/string.c @@ -101,10 +101,19 @@ void test_compare() test_equal(string_compare("A", ""), -1); } +void test_length() +{ + test_equal(string_length(NULL), 0); + test_equal(string_length(""), 0); + test_equal(string_length("a"), 1); + test_equal(string_length("abcdefghijklmnopqrstuvwxyz"), 26); +} + DECLARE_UNIT_TESTS( UNIT_TEST("Seconds to String", test_sec2str), UNIT_TEST("Seconds to String (Long)", test_sec2str_long), UNIT_TEST("Date to String", test_date), UNIT_TEST("String Lowercase", test_lowercase), UNIT_TEST("String Comparison", test_compare), + UNIT_TEST("String Length", test_length), );