Skip to content

Commit

Permalink
fmt: add string to bool function
Browse files Browse the repository at this point in the history
  • Loading branch information
cHuberCoffee authored and cspiel1 committed Jun 18, 2021
1 parent 90a8b65 commit 5fd77b2
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
1 change: 1 addition & 0 deletions include/re_fmt.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
53 changes: 53 additions & 0 deletions src/fmt/str.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

0 comments on commit 5fd77b2

Please sign in to comment.