From c12ab785ce1982f82594aff03b3104c598186ddd Mon Sep 17 00:00:00 2001 From: Eduard Tykhoniuk <50710486+MAKMED1337@users.noreply.github.com> Date: Sun, 1 Sep 2024 12:57:32 +0200 Subject: [PATCH] config: fix parsing invalid hex (#53) Instead of crashing on an invalid hex, return an error. --- src/config.cpp | 8 ++++++-- tests/config/error2.conf | 5 +++++ tests/parse/main.cpp | 11 +++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 tests/config/error2.conf mode change 100644 => 100755 tests/parse/main.cpp diff --git a/src/config.cpp b/src/config.cpp index a1952ca..62efa97 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -162,8 +162,12 @@ void CConfig::commence() { static std::expected configStringToInt(const std::string& VALUE) { if (VALUE.starts_with("0x")) { // Values with 0x are hex - const auto VALUEWITHOUTHEX = VALUE.substr(2); - return stoll(VALUEWITHOUTHEX, nullptr, 16); + size_t position; + auto result = stoll(VALUE, &position, 16); + if (position == VALUE.size()) + return result; + + return std::unexpected("invalid hex " + VALUE); } else if (VALUE.starts_with("rgba(") && VALUE.ends_with(')')) { const auto VALUEWITHOUTFUNC = trim(VALUE.substr(5, VALUE.length() - 6)); diff --git a/tests/config/error2.conf b/tests/config/error2.conf new file mode 100644 index 0000000..f41910a --- /dev/null +++ b/tests/config/error2.conf @@ -0,0 +1,5 @@ +# This config houses two errors + +invalidHex = 0xQQ +emptyHex = 0x + diff --git a/tests/parse/main.cpp b/tests/parse/main.cpp old mode 100644 new mode 100755 index 0fdb916..0c28d17 --- a/tests/parse/main.cpp +++ b/tests/parse/main.cpp @@ -279,6 +279,17 @@ int main(int argc, char** argv, char** envp) { const auto ERRORSTR = std::string{ERRORS.getError()}; EXPECT(std::count(ERRORSTR.begin(), ERRORSTR.end(), '\n'), 1); + std::cout << " → Testing error2.conf\n"; + Hyprlang::CConfig errorConfig2("./config/error2.conf", {.throwAllErrors = true}); + errorConfig2.addConfigValue("invalidHex", (Hyprlang::INT)0); + errorConfig2.addConfigValue("emptyHex", (Hyprlang::INT)0); + + errorConfig2.commence(); + const auto ERRORS2 = errorConfig2.parse(); + + EXPECT(ERRORS2.error, true); + const auto ERRORSTR2 = std::string{ERRORS2.getError()}; + EXPECT(std::count(ERRORSTR2.begin(), ERRORSTR2.end(), '\n'), 1); } catch (const char* e) { std::cout << Colors::RED << "Error: " << Colors::RESET << e << "\n"; return 1;