config: fix parsing invalid hex (#53)

Instead of crashing on an invalid hex, return an error.
This commit is contained in:
Eduard Tykhoniuk 2024-09-01 12:57:32 +02:00 committed by GitHub
parent 16e5c9465f
commit c12ab785ce
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 22 additions and 2 deletions

View File

@ -162,8 +162,12 @@ void CConfig::commence() {
static std::expected<int64_t, std::string> configStringToInt(const std::string& VALUE) { static std::expected<int64_t, std::string> configStringToInt(const std::string& VALUE) {
if (VALUE.starts_with("0x")) { if (VALUE.starts_with("0x")) {
// Values with 0x are hex // Values with 0x are hex
const auto VALUEWITHOUTHEX = VALUE.substr(2); size_t position;
return stoll(VALUEWITHOUTHEX, nullptr, 16); 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(')')) { } else if (VALUE.starts_with("rgba(") && VALUE.ends_with(')')) {
const auto VALUEWITHOUTFUNC = trim(VALUE.substr(5, VALUE.length() - 6)); const auto VALUEWITHOUTFUNC = trim(VALUE.substr(5, VALUE.length() - 6));

5
tests/config/error2.conf Normal file
View File

@ -0,0 +1,5 @@
# This config houses two errors
invalidHex = 0xQQ
emptyHex = 0x

11
tests/parse/main.cpp Normal file → Executable file
View File

@ -279,6 +279,17 @@ int main(int argc, char** argv, char** envp) {
const auto ERRORSTR = std::string{ERRORS.getError()}; const auto ERRORSTR = std::string{ERRORS.getError()};
EXPECT(std::count(ERRORSTR.begin(), ERRORSTR.end(), '\n'), 1); 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) { } catch (const char* e) {
std::cout << Colors::RED << "Error: " << Colors::RESET << e << "\n"; std::cout << Colors::RED << "Error: " << Colors::RESET << e << "\n";
return 1; return 1;