refactor: Return std::optional from ParseDouble
What changed, and why it matters
This commit is a straightforward internal code cleanup: it changes the ParseDouble helper function to return a C++ std::optional<double> instead of writing a result through a pointer and returning a boolean success flag. The behavior of parsing JSON numbers remains the same, and no security issue is present.
No action required; this is a safe refactoring commit.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The patch refactors ParseDouble in src/univalue/lib/univalue_get.cpp to use std::optional
Changed components
src/univalue/lib/univalue_get.cppInspect captured patch +12 / −9
diff --git a/src/univalue/lib/univalue_get.cpp b/src/univalue/lib/univalue_get.cpp
index 146cc421..e82ac4cb 100644
--- a/src/univalue/lib/univalue_get.cpp
+++ b/src/univalue/lib/univalue_get.cpp
@@ -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
Why this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.