util: make ParseMoney return a std::optional<CAmount>

This commit is contained in:
fanquake
2021-06-11 12:33:20 +08:00
parent 3308c61091
commit 5ef2738089
9 changed files with 119 additions and 140 deletions

View File

@@ -5,10 +5,13 @@
#include <util/moneystr.h>
#include <amount.h>
#include <tinyformat.h>
#include <util/strencodings.h>
#include <util/string.h>
#include <optional>
std::string FormatMoney(const CAmount n)
{
// Note: not using straight sprintf here because we do NOT want
@@ -35,14 +38,14 @@ std::string FormatMoney(const CAmount n)
}
bool ParseMoney(const std::string& money_string, CAmount& nRet)
std::optional<CAmount> ParseMoney(const std::string& money_string)
{
if (!ValidAsCString(money_string)) {
return false;
return std::nullopt;
}
const std::string str = TrimString(money_string);
if (str.empty()) {
return false;
return std::nullopt;
}
std::string strWhole;
@@ -62,21 +65,21 @@ bool ParseMoney(const std::string& money_string, CAmount& nRet)
break;
}
if (IsSpace(*p))
return false;
return std::nullopt;
if (!IsDigit(*p))
return false;
return std::nullopt;
strWhole.insert(strWhole.end(), *p);
}
if (*p) {
return false;
return std::nullopt;
}
if (strWhole.size() > 10) // guard against 63 bit overflow
return false;
return std::nullopt;
if (nUnits < 0 || nUnits > COIN)
return false;
return std::nullopt;
int64_t nWhole = atoi64(strWhole);
CAmount nValue = nWhole*COIN + nUnits;
nRet = nValue;
return true;
CAmount value = nWhole * COIN + nUnits;
return value;
}

View File

@@ -12,6 +12,7 @@
#include <amount.h>
#include <attributes.h>
#include <optional>
#include <string>
/* Do not use these functions to represent or parse monetary amounts to or from
@@ -19,6 +20,6 @@
*/
std::string FormatMoney(const CAmount n);
/** Parse an amount denoted in full coins. E.g. "0.0034" supplied on the command line. **/
[[nodiscard]] bool ParseMoney(const std::string& str, CAmount& nRet);
std::optional<CAmount> ParseMoney(const std::string& str);
#endif // BITCOIN_UTIL_MONEYSTR_H