Skip to content

Commit

Permalink
made string helpers NULL-safe
Browse files Browse the repository at this point in the history
  • Loading branch information
256dpi committed Oct 22, 2017
1 parent b65dd59 commit e028438
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 6 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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})
Expand Down
27 changes: 21 additions & 6 deletions src/string.c
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,36 @@
#include <lwmqtt.h>

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);
}
36 changes: 36 additions & 0 deletions tests/string.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#include <gtest/gtest.h>

extern "C" {
#include <lwmqtt.h>
}

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

0 comments on commit e028438

Please sign in to comment.