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