Skip to content

Commit

Permalink
fix:fix GetValueFromConfig for bool type (#39526)
Browse files Browse the repository at this point in the history
#39525

Signed-off-by: luzhang <[email protected]>
Co-authored-by: luzhang <[email protected]>
  • Loading branch information
zhagnlu and luzhang authored Jan 24, 2025
1 parent 6d8441a commit 8117d59
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 5 deletions.
20 changes: 15 additions & 5 deletions internal/core/src/index/Utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,23 @@ void inline CheckParameter(Config& conf,
template <typename T>
inline std::optional<T>
GetValueFromConfig(const Config& cfg, const std::string& key) {
// cfg value are all string type
if (cfg.contains(key)) {
if constexpr (std::is_same_v<T, bool>) {
return boost::algorithm::to_lower_copy(
cfg.at(key).get<std::string>()) == "true";
try {
// compatibility for boolean string
if constexpr (std::is_same_v<T, bool>) {
if (cfg.at(key).is_boolean()) {
return cfg.at(key).get<bool>();
}
return boost::algorithm::to_lower_copy(
cfg.at(key).get<std::string>()) == "true";
}
return cfg.at(key).get<T>();
} catch (std::exception& e) {
PanicInfo(ErrorCode::UnexpectedError,
"get value from config for key {} failed, error: {}",
key,
e.what());
}
return cfg.at(key).get<T>();
}
return std::nullopt;
}
Expand Down
25 changes: 25 additions & 0 deletions internal/core/unittest/test_c_api.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4469,3 +4469,28 @@ TEST(CApiTest, SearchIdTest) {
TEST(CApiTest, IsLoadWithDisk) {
ASSERT_TRUE(IsLoadWithDisk(INVERTED_INDEX_TYPE, 0));
}

TEST(CApiTest, TestGetValueFromConfig) {
nlohmann::json cfg = nlohmann::json::parse(
R"({"a" : 100, "b" : true, "c" : "true", "d" : 1.234})");
auto a_value = GetValueFromConfig<int64_t>(cfg, "a");
ASSERT_EQ(a_value.value(), 100);

auto b_value = GetValueFromConfig<bool>(cfg, "b");
ASSERT_TRUE(b_value.value());

auto c_value = GetValueFromConfig<bool>(cfg, "c");
ASSERT_TRUE(c_value.value());

auto d_value = GetValueFromConfig<double>(cfg, "d");
ASSERT_NEAR(d_value.value(), 1.234, 0.001);

try {
GetValueFromConfig<std::string>(cfg, "d");
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
ASSERT_EQ(std::string(e.what()).find("get value from config for key") !=
std::string::npos,
true);
}
}

0 comments on commit 8117d59

Please sign in to comment.