aboutsummaryrefslogtreecommitdiff
path: root/src/util/strencodings.h
diff options
context:
space:
mode:
authorW. J. van der Laan <laanwj@protonmail.com>2021-10-04 12:49:04 +0200
committerW. J. van der Laan <laanwj@protonmail.com>2021-10-04 12:59:28 +0200
commitcdb4dfcbf1c82ef4c4eb7bb982b35219d5dbf827 (patch)
treea89fc72c12ef05a3c880e7268fd26962e5a50816 /src/util/strencodings.h
parentc6f710ec985518ccff6dd69426625f2ed0d102f8 (diff)
parent4343f114cc661cf031ec915538c11b9b030e2e15 (diff)
downloadbitcoin-cdb4dfcbf1c82ef4c4eb7bb982b35219d5dbf827.tar.xz
Merge bitcoin/bitcoin#20452: util: Replace use of locale dependent atoi(…) with locale-independent std::from_chars(…) (C++17)
4343f114cc661cf031ec915538c11b9b030e2e15 Replace use of locale dependent atoi(…) with locale-independent std::from_chars(…) (C++17) (practicalswift) Pull request description: Replace use of locale dependent `atoi(…)` with locale-independent `std::from_chars(…)` (C++17). ACKs for top commit: laanwj: Code review ACK 4343f114cc661cf031ec915538c11b9b030e2e15 jonatack: Code review ACK 4343f114cc661cf031ec915538c11b9b030e2e15 Tree-SHA512: e4909da282b6cefc5ca34e13b02cc489af56cab339a77ae5c35ac9ef355d9b941b129a2bfddc1b37426b11c79a21c8b729fbb5255e6d9eaa344406b18b825494
Diffstat (limited to 'src/util/strencodings.h')
-rw-r--r--src/util/strencodings.h30
1 files changed, 28 insertions, 2 deletions
diff --git a/src/util/strencodings.h b/src/util/strencodings.h
index 1217572c45..166352c42f 100644
--- a/src/util/strencodings.h
+++ b/src/util/strencodings.h
@@ -11,6 +11,7 @@
#include <attributes.h>
#include <span.h>
+#include <util/string.h>
#include <charconv>
#include <cstdint>
@@ -68,8 +69,33 @@ std::string EncodeBase32(Span<const unsigned char> input, bool pad = true);
std::string EncodeBase32(const std::string& str, bool pad = true);
void SplitHostPort(std::string in, uint16_t& portOut, std::string& hostOut);
-int64_t atoi64(const std::string& str);
-int atoi(const std::string& str);
+
+// LocaleIndependentAtoi is provided for backwards compatibility reasons.
+//
+// New code should use the ParseInt64/ParseUInt64/ParseInt32/ParseUInt32 functions
+// which provide parse error feedback.
+//
+// The goal of LocaleIndependentAtoi is to replicate the exact defined behaviour
+// of atoi and atoi64 as they behave under the "C" locale.
+template <typename T>
+T LocaleIndependentAtoi(const std::string& str)
+{
+ static_assert(std::is_integral<T>::value);
+ T result;
+ // Emulate atoi(...) handling of white space and leading +/-.
+ std::string s = TrimString(str);
+ if (!s.empty() && s[0] == '+') {
+ if (s.length() >= 2 && s[1] == '-') {
+ return 0;
+ }
+ s = s.substr(1);
+ }
+ auto [_, error_condition] = std::from_chars(s.data(), s.data() + s.size(), result);
+ if (error_condition != std::errc{}) {
+ return 0;
+ }
+ return result;
+}
/**
* Tests if the given character is a decimal digit.