From 008b956ba609bf30d8c6f44c36d9f11cdc493bc2 Mon Sep 17 00:00:00 2001 From: "Rafael G. Martins" Date: Wed, 25 Jul 2018 20:34:58 +0200 Subject: common: added bc_str_to_bool --- src/common/utils.c | 26 ++++++++++++++++++++++++++ src/common/utils.h | 1 + tests/common/check_utils.c | 26 ++++++++++++++++++++++++++ 3 files changed, 53 insertions(+) diff --git a/src/common/utils.c b/src/common/utils.c index 563d8ab..7065047 100644 --- a/src/common/utils.c +++ b/src/common/utils.c @@ -9,6 +9,7 @@ #define BC_STRING_CHUNK_SIZE 128 #include +#include #include #include #include @@ -302,6 +303,31 @@ bc_str_find(const char *str, char c) } +bool +bc_str_to_bool(const char *str) +{ + if (str == NULL) + return false; + + if (0 == strcmp(str, "1")) + return true; + + if (0 == strcasecmp(str, "y")) + return true; + + if (0 == strcasecmp(str, "yes")) + return true; + + if (0 == strcasecmp(str, "true")) + return true; + + if (0 == strcasecmp(str, "on")) + return true; + + return false; +} + + void bc_strv_free(char **strv) { diff --git a/src/common/utils.h b/src/common/utils.h index 0f05c96..101a4b3 100644 --- a/src/common/utils.h +++ b/src/common/utils.h @@ -50,6 +50,7 @@ char* bc_str_strip(char *str); char** bc_str_split(const char *str, char c, size_t max_pieces); char* bc_str_replace(const char *str, const char search, const char *replace); char* bc_str_find(const char *str, char c); +bool bc_str_to_bool(const char *str); void bc_strv_free(char **strv); char* bc_strv_join(char **strv, const char *separator); size_t bc_strv_length(char **strv); diff --git a/tests/common/check_utils.c b/tests/common/check_utils.c index 12ef921..90af37b 100644 --- a/tests/common/check_utils.c +++ b/tests/common/check_utils.c @@ -267,6 +267,31 @@ test_str_find(void **state) } +static void +test_str_to_bool(void **state) +{ + assert_false(bc_str_to_bool(NULL)); + assert_true(bc_str_to_bool("1")); + assert_true(bc_str_to_bool("y")); + assert_true(bc_str_to_bool("Y")); + assert_true(bc_str_to_bool("yes")); + assert_true(bc_str_to_bool("YES")); + assert_true(bc_str_to_bool("true")); + assert_true(bc_str_to_bool("TRUE")); + assert_true(bc_str_to_bool("on")); + assert_true(bc_str_to_bool("ON")); + assert_false(bc_str_to_bool("0")); + assert_false(bc_str_to_bool("n")); + assert_false(bc_str_to_bool("N")); + assert_false(bc_str_to_bool("no")); + assert_false(bc_str_to_bool("NO")); + assert_false(bc_str_to_bool("false")); + assert_false(bc_str_to_bool("FALSE")); + assert_false(bc_str_to_bool("off")); + assert_false(bc_str_to_bool("OFF")); +} + + static void test_strv_join(void **state) { @@ -1039,6 +1064,7 @@ main(void) unit_test(test_str_split), unit_test(test_str_replace), unit_test(test_str_find), + unit_test(test_str_to_bool), unit_test(test_strv_join), unit_test(test_strv_length), -- cgit v1.2.3-18-g5258