From e028438a8b80b08471d76df3ae6b2973f23eb230 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=ABl=20G=C3=A4hwiler?= Date: Sun, 22 Oct 2017 18:59:06 +0300 Subject: [PATCH] made string helpers NULL-safe --- CMakeLists.txt | 1 + src/string.c | 27 +++++++++++++++++++++------ tests/string.cpp | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 6 deletions(-) create mode 100644 tests/string.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 2138597..6810db1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -40,6 +40,7 @@ set(TEST_FILES tests/client.cpp tests/helpers.cpp tests/packet.cpp + tests/string.cpp tests/tests.cpp) add_executable(tests ${TEST_FILES}) diff --git a/src/string.c b/src/string.c index fe32bab..9117c00 100644 --- a/src/string.c +++ b/src/string.c @@ -3,21 +3,36 @@ #include lwmqtt_string_t lwmqtt_string(const char *str) { + // check for null + if (str == NULL) { + return (lwmqtt_string_t){0, NULL}; + } + // get length uint16_t len = (uint16_t)strlen(str); + // check zero length + if (len == 0) { + return (lwmqtt_string_t){0, NULL}; + } + return (lwmqtt_string_t){len, (char *)str}; } int lwmqtt_strcmp(lwmqtt_string_t a, const char *b) { - // get length of b - size_t len = strlen(b); + // get string of b + lwmqtt_string_t b_str = lwmqtt_string(b); + + // return if both are zero length + if (a.len == 0 && b_str.len == 0) { + return 0; + } - // otherwise check if length matches - if (len != a.len) { + // return if lengths are different + if (a.len != b_str.len) { return -1; } - // compare memory - return strncmp(a.data, b, len); + // compare memory of same length + return strncmp(a.data, b_str.data, a.len); } diff --git a/tests/string.cpp b/tests/string.cpp new file mode 100644 index 0000000..66c6310 --- /dev/null +++ b/tests/string.cpp @@ -0,0 +1,36 @@ +#include + +extern "C" { +#include +} + +TEST(StringConstructor, Valid) { + lwmqtt_string_t null_str = lwmqtt_string(nullptr); + EXPECT_EQ(null_str.len, 0); + EXPECT_TRUE(null_str.data == nullptr); + + lwmqtt_string_t empty_str = lwmqtt_string(""); + EXPECT_EQ(empty_str.len, 0); + EXPECT_TRUE(empty_str.data == nullptr); + + lwmqtt_string_t hello_str = lwmqtt_string("hello"); + EXPECT_EQ(hello_str.len, 5); + EXPECT_TRUE(hello_str.data != nullptr); +} + +TEST(StringCompare, Valid) { + lwmqtt_string_t null_str = lwmqtt_string(nullptr); + EXPECT_TRUE(lwmqtt_strcmp(null_str, nullptr) == 0); + EXPECT_TRUE(lwmqtt_strcmp(null_str, "") == 0); + EXPECT_TRUE(lwmqtt_strcmp(null_str, "hello") != 0); + + lwmqtt_string_t empty_str = lwmqtt_string(""); + EXPECT_TRUE(lwmqtt_strcmp(empty_str, nullptr) == 0); + EXPECT_TRUE(lwmqtt_strcmp(empty_str, "") == 0); + EXPECT_TRUE(lwmqtt_strcmp(empty_str, "hello") != 0); + + lwmqtt_string_t hello_str = lwmqtt_string("hello"); + EXPECT_TRUE(lwmqtt_strcmp(hello_str, nullptr) != 0); + EXPECT_TRUE(lwmqtt_strcmp(hello_str, "") != 0); + EXPECT_TRUE(lwmqtt_strcmp(hello_str, "hello") == 0); +}