aboutsummaryrefslogtreecommitdiff
path: root/src/util/strencodings.h
diff options
context:
space:
mode:
authorpracticalswift <practicalswift@users.noreply.github.com>2021-09-18 04:30:30 +0000
committerpracticalswift <practicalswift@users.noreply.github.com>2021-09-18 04:31:24 +0000
commit4747db876154ddd828c03d9eda10ecf8b25d8dc8 (patch)
tree7b9b6ebad2043653c550fb1adc2be76742804711 /src/util/strencodings.h
parente69cbac628bfdca4a8e4ead821190eaf5b6b3d07 (diff)
downloadbitcoin-4747db876154ddd828c03d9eda10ecf8b25d8dc8.tar.xz
util: Introduce ToIntegral<T>(const std::string&) for locale independent parsing using std::from_chars(…) (C++17)
util: Avoid locale dependent functions strtol/strtoll/strtoul/strtoull in ParseInt32/ParseInt64/ParseUInt32/ParseUInt64 fuzz: Assert equivalence between new and old Parse{Int,Uint}{8,32,64} functions test: Add unit tests for ToIntegral<T>(const std::string&)
Diffstat (limited to 'src/util/strencodings.h')
-rw-r--r--src/util/strencodings.h20
1 files changed, 20 insertions, 0 deletions
diff --git a/src/util/strencodings.h b/src/util/strencodings.h
index 26dc0a0ce3..1217572c45 100644
--- a/src/util/strencodings.h
+++ b/src/util/strencodings.h
@@ -12,8 +12,10 @@
#include <attributes.h>
#include <span.h>
+#include <charconv>
#include <cstdint>
#include <iterator>
+#include <optional>
#include <string>
#include <vector>
@@ -95,6 +97,24 @@ constexpr inline bool IsSpace(char c) noexcept {
}
/**
+ * Convert string to integral type T.
+ *
+ * @returns std::nullopt if the entire string could not be parsed, or if the
+ * parsed value is not in the range representable by the type T.
+ */
+template <typename T>
+std::optional<T> ToIntegral(const std::string& str)
+{
+ static_assert(std::is_integral<T>::value);
+ T result;
+ const auto [first_nonmatching, error_condition] = std::from_chars(str.data(), str.data() + str.size(), result);
+ if (first_nonmatching != str.data() + str.size() || error_condition != std::errc{}) {
+ return std::nullopt;
+ }
+ return {result};
+}
+
+/**
* Convert string to signed 32-bit integer with strict parse error feedback.
* @returns true if the entire string could be parsed as valid integer,
* false if not the entire string could be parsed or when overflow or underflow occurred.