From 7bd0da2120a8174344da0acae4a9539dbdc70b74 Mon Sep 17 00:00:00 2001 From: Radoslaw Zarzynski Date: Wed, 24 Jun 2020 12:28:43 +0000 Subject: [PATCH] config: make the Option::TYPE_BOOL interpreter reusable. Let's allow custom validators to not duplicate the code. Signed-off-by: Radoslaw Zarzynski --- src/common/options.cc | 13 ++++--------- src/common/strtol.cc | 13 +++++++++++++ src/common/strtol.h | 2 ++ 3 files changed, 19 insertions(+), 9 deletions(-) diff --git a/src/common/options.cc b/src/common/options.cc index 5f25c043505..e4b58f6b1e8 100644 --- a/src/common/options.cc +++ b/src/common/options.cc @@ -166,16 +166,11 @@ int Option::parse_value( *out = f; } } else if (type == Option::TYPE_BOOL) { - if (strcasecmp(val.c_str(), "false") == 0) { - *out = false; - } else if (strcasecmp(val.c_str(), "true") == 0) { - *out = true; + bool b = strict_strtob(val.c_str(), error_message); + if (!error_message->empty()) { + return -EINVAL; } else { - int b = strict_strtol(val.c_str(), 10, error_message); - if (!error_message->empty()) { - return -EINVAL; - } - *out = (bool)!!b; + *out = b; } } else if (type == Option::TYPE_ADDR) { entity_addr_t addr; diff --git a/src/common/strtol.cc b/src/common/strtol.cc index 76d2a85b74c..11b90035296 100644 --- a/src/common/strtol.cc +++ b/src/common/strtol.cc @@ -19,10 +19,23 @@ #include #include #include +#include #include using std::ostringstream; +bool strict_strtob(const char* str, std::string *err) +{ + if (strcasecmp(str, "false") == 0) { + return false; + } else if (strcasecmp(str, "true") == 0) { + return true; + } else { + int b = strict_strtol(str, 10, err); + return (bool)!!b; + } +} + long long strict_strtoll(std::string_view str, int base, std::string *err) { char *endptr; diff --git a/src/common/strtol.h b/src/common/strtol.h index 6d722269320..7cf3895133f 100644 --- a/src/common/strtol.h +++ b/src/common/strtol.h @@ -20,6 +20,8 @@ extern "C" { #include } +bool strict_strtob(const char* str, std::string *err); + long long strict_strtoll(const char *str, int base, std::string *err); int strict_strtol(const char *str, int base, std::string *err); -- 2.39.5