refactor: Return std::optional from ParseDouble

This commit is contained in:
MarcoFalke
2026-03-27 14:28:53 +01:00
parent fa0a09441d
commit fabab69e9e

View File

@@ -7,6 +7,7 @@
#include <cstring>
#include <locale>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <string>
@@ -25,18 +26,20 @@ static bool ParsePrechecks(const std::string& str)
return true;
}
bool ParseDouble(const std::string& str, double *out)
std::optional<double> ParseDouble(const std::string& str)
{
if (!ParsePrechecks(str))
return false;
return std::nullopt;
if (str.size() >= 2 && str[0] == '0' && str[1] == 'x') // No hexadecimal floats allowed
return false;
return std::nullopt;
std::istringstream text(str);
text.imbue(std::locale::classic());
double result;
text >> result;
if(out) *out = result;
return text.eof() && !text.fail();
if (!text.eof() || text.fail()) {
return std::nullopt;
}
return result;
}
}
@@ -68,10 +71,10 @@ const std::string& UniValue::get_str() const
double UniValue::get_real() const
{
checkType(VNUM);
double retval;
if (!ParseDouble(getValStr(), &retval))
throw std::runtime_error("JSON double out of range");
return retval;
if (const auto retval{ParseDouble(getValStr())}) {
return *retval;
}
throw std::runtime_error("JSON double out of range");
}
const UniValue& UniValue::get_obj() const