diff --git a/include/re_fmt.h b/include/re_fmt.h index 0660ad960..bb08344dd 100644 --- a/include/re_fmt.h +++ b/include/re_fmt.h @@ -105,6 +105,7 @@ uint8_t ch_hex(char ch); /* String functions */ +int str_bool(bool *val, const char *str); int str_hex(uint8_t *hex, size_t len, const char *str); void str_ncpy(char *dst, const char *src, size_t n); int str_dup(char **dst, const char *src); diff --git a/src/fmt/str.c b/src/fmt/str.c index 37981af36..228f020c5 100644 --- a/src/fmt/str.c +++ b/src/fmt/str.c @@ -140,3 +140,56 @@ size_t str_len(const char *s) { return s ? strlen(s) : 0; } + + +/** + * Convert various possible boolean strings to a bool + * + * @param val Pointer to bool for returned value + * @param str String to be converted + * + * @return int 0 if success, otherwise errorcode + */ +int str_bool(bool *val, const char *str) +{ + int err = 0; + + if (!val || !str_isset(str)) + return EINVAL; + + if (!str_cmp(str, "0")) { + *val = false; + } + else if (!str_cmp(str, "1")) { + *val = true; + } + else if (!str_cmp(str, "false")) { + *val = false; + } + else if (!str_cmp(str, "true")) { + *val = true; + } + else if (!str_cmp(str, "disable")) { + *val = false; + } + else if (!str_cmp(str, "enable")) { + *val = true; + } + else if (!str_cmp(str, "off")) { + *val = false; + } + else if (!str_cmp(str, "on")) { + *val = true; + } + else if (!str_cmp(str, "no")) { + *val = false; + } + else if (!str_cmp(str, "yes")) { + *val = true; + } + else { + err = EINVAL; + } + + return err; +}