From 6f8bfd7d11e322cd53358be35e10ba7d02d0a680 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20M=C3=A4kel=C3=A4?= Date: Wed, 13 Mar 2019 09:27:50 +0200 Subject: [PATCH] MXS-2313: Add enum to value conversion function The helper function makes it easier to convert enum values at runtime to their integer representation. Also changed the configuration processing code to use the new function. --- server/core/config.cc | 41 +++++++++++++++++++--------------- server/core/internal/config.hh | 13 +++++++++++ 2 files changed, 36 insertions(+), 18 deletions(-) diff --git a/server/core/config.cc b/server/core/config.cc index 0db1cece4..4f254f9f0 100644 --- a/server/core/config.cc +++ b/server/core/config.cc @@ -1688,30 +1688,22 @@ MXS_CONFIG_PARAMETER::get_duration(const std::string& key, int64_t MXS_CONFIG_PARAMETER::get_enum(const std::string& key, const MXS_ENUM_VALUE* enum_mapping) const { - string param_value = get_string(key); - char tmp_val[param_value.length() + 1]; - strcpy(tmp_val, param_value.c_str()); + int64_t rv = 0; - int rv = 0; - bool found = false; - char* endptr; - const char* delim = ", \t"; - char* tok = strtok_r(tmp_val, delim, &endptr); - - while (tok) + for (const auto& tok : mxs::strtok(get_string(key), ", \t")) { - for (int i = 0; enum_mapping[i].name; i++) + auto value = config_enum_to_value(tok, enum_mapping); + + if (value == MXS_UNKNOWN_ENUM_VALUE) { - if (strcmp(enum_mapping[i].name, tok) == 0) - { - found = true; - rv |= enum_mapping[i].enum_value; - } + rv = MXS_UNKNOWN_ENUM_VALUE; + break; } - tok = strtok_r(NULL, delim, &endptr); + + rv |= value; } - return found ? rv : -1; + return rv; } SERVICE* MXS_CONFIG_PARAMETER::get_service(const std::string& key) const @@ -5017,3 +5009,16 @@ bool config_is_valid_name(const char* zName, std::string* pReason) return is_valid; } + +int64_t config_enum_to_value(const std::string& value, const MXS_ENUM_VALUE* values) +{ + for (auto v = values; v->name; ++v) + { + if (value == v->name) + { + return v->enum_value; + } + } + + return MXS_UNKNOWN_ENUM_VALUE; +} diff --git a/server/core/internal/config.hh b/server/core/internal/config.hh index 4e5aa568c..06e8062f1 100644 --- a/server/core/internal/config.hh +++ b/server/core/internal/config.hh @@ -255,3 +255,16 @@ std::string generate_config_string(const std::string& instance_name, const MXS_C * @return True if the parameter can be modified at runtime */ bool config_can_modify_at_runtime(const char* name); + +// Value returned for unknown enumeration values +constexpr int64_t MXS_UNKNOWN_ENUM_VALUE {-1}; + +/** + * Convert enum name to integer value + * + * @param key The enum name to convert + * @param values The list of enum values + * + * @return The enum value or MXS_UNKNOWN_ENUM_VALUE on unknown value + */ +int64_t config_enum_to_value(const std::string& key, const MXS_ENUM_VALUE* values);