From e7ce54188b71aedfc40ab204941f4d1e8d10a550 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Sun, 19 Apr 2026 18:44:59 +0800 Subject: [PATCH] [Refactor] Enhance Config class with type-safe get method and value reading --- includes/JuiceAgent/Config.hpp | 50 ++++++++++++++++++++++++++++++++++ src/libagent/libagent.cpp | 1 - 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/includes/JuiceAgent/Config.hpp b/includes/JuiceAgent/Config.hpp index 081cdf4..ab3be60 100644 --- a/includes/JuiceAgent/Config.hpp +++ b/includes/JuiceAgent/Config.hpp @@ -14,6 +14,22 @@ private: toml::value _config; bool _valid = false; +private: + template + static T _read_value(const toml::value& v) { + if constexpr (std::is_same_v) { + return v.as_string(); + } else if constexpr (std::is_same_v) { + return v.as_boolean(); + } else if constexpr (std::is_integral_v && !std::is_same_v) { + return static_cast(v.as_integer()); + } else if constexpr (std::is_floating_point_v) { + return static_cast(v.as_floating()); + } else { + static_assert(sizeof(T) == 0, "Unsupported config type"); + } + } + public: explicit Config(const std::filesystem::path& runtime_dir = {}) { @@ -46,6 +62,40 @@ public: const std::filesystem::path& runtime_dir() const noexcept { return _runtime_dir; } + + template + T get(const std::string& path, const T& default_value) const { + if (!_valid) { + return default_value; + } + + try { + const toml::value* current = &_config; + std::size_t start = 0; + + while (start < path.size()) { + const std::size_t end = path.find('.', start); + const std::string key = path.substr( + start, + end == std::string::npos ? std::string::npos : end - start + ); + + current = ¤t->at(key); + + if (end == std::string::npos) { + break; + } + + start = end + 1; + } + + return _read_value(*current); + } + catch (const std::exception& e) { + PLOGW << "Config get failed: " << path << ", using default value"; + return default_value; + } + } }; namespace Utils { diff --git a/src/libagent/libagent.cpp b/src/libagent/libagent.cpp index b958860..5fb8d3d 100644 --- a/src/libagent/libagent.cpp +++ b/src/libagent/libagent.cpp @@ -39,7 +39,6 @@ namespace JuiceAgent { set_jvmti(jvmti); set_config(cfg); PLOGD << "env: " << env << ", jvmti: " << jvmti; - PLOGD << "config: " << &cfg.get_config(); // PreLoad Event