9 #ifndef BITCOIN_UTIL_STRENCODINGS_H 10 #define BITCOIN_UTIL_STRENCODINGS_H 25 #include <string_view> 26 #include <system_error> 27 #include <type_traits> 52 t = 1'000
'000'000
'000ULL, 63 std::string SanitizeString(std::string_view str, int rule = SAFE_CHARS_DEFAULT); 65 template <typename Byte = std::byte> 66 std::optional<std::vector<Byte>> TryParseHex(std::string_view str); 68 template <typename Byte = uint8_t> 69 std::vector<Byte> ParseHex(std::string_view hex_str) 71 return TryParseHex<Byte>(hex_str).value_or(std::vector<Byte>{}); 73 /* Returns true if each character in str is a hex character, and has an even 74 * number of hex digits.*/ 75 bool IsHex(std::string_view str); 76 std::optional<std::vector<unsigned char>> DecodeBase64(std::string_view str); 77 std::string EncodeBase64(std::span<const unsigned char> input); 78 inline std::string EncodeBase64(std::span<const std::byte> input) { return EncodeBase64(MakeUCharSpan(input)); } 79 inline std::string EncodeBase64(std::string_view str) { return EncodeBase64(MakeUCharSpan(str)); } 80 std::optional<std::vector<unsigned char>> DecodeBase32(std::string_view str); 87 std::string EncodeBase32(std::span<const unsigned char> input, bool pad = true); 94 std::string EncodeBase32(std::string_view str, bool pad = true); 105 bool SplitHostPort(std::string_view in, uint16_t& portOut, std::string& hostOut); 107 // LocaleIndependentAtoi is provided for backwards compatibility reasons. 109 // New code should use ToIntegral. 111 // The goal of LocaleIndependentAtoi is to replicate the defined behaviour of 112 // std::atoi as it behaves under the "C" locale, and remove some undefined 113 // behavior. If the parsed value is bigger than the integer type's maximum
117 template <
typename T>
120 static_assert(std::is_integral_v<T>);
124 if (!
s.empty() &&
s[0] ==
'+') {
125 if (
s.length() >= 2 &&
s[1] ==
'-') {
130 auto [
_, error_condition] = std::from_chars(
s.data(),
s.data() +
s.size(),
result);
131 if (error_condition == std::errc::result_out_of_range) {
132 if (
s.length() >= 1 &&
s[0] ==
'-') {
134 return std::numeric_limits<T>::min();
137 return std::numeric_limits<T>::max();
139 }
else if (error_condition != std::errc{}) {
152 return c >=
'0' && c <=
'9';
166 constexpr
inline bool IsSpace(
char c) noexcept {
167 return c ==
' ' || c ==
'\f' || c ==
'\n' || c ==
'\r' || c ==
'\t' || c ==
'\v';
179 template <
typename T>
180 std::optional<T>
ToIntegral(std::string_view str,
size_t base = 10)
182 static_assert(std::is_integral_v<T>);
184 const auto [first_nonmatching, error_condition] = std::from_chars(str.data(), str.data() + str.size(),
result, base);
185 if (first_nonmatching != str.data() + str.size() || error_condition != std::errc{}) {
195 std::string
FormatParagraph(std::string_view in,
size_t width = 79,
size_t indent = 0);
202 template <
typename T>
205 if (b.size() == 0)
return a.size() == 0;
206 size_t accumulator = a.size() ^ b.size();
207 for (
size_t i = 0; i < a.size(); i++)
208 accumulator |=
size_t(a[i] ^ b[i%b.size()]);
209 return accumulator == 0;
216 [[nodiscard]]
bool ParseFixedPoint(std::string_view,
int decimals, int64_t *amount_out);
222 [[maybe_unused]]
int operator()(
int x)
const {
return x; }
228 template<
int frombits,
int tobits,
bool pad,
typename O,
typename It,
typename I = IntIdentity>
232 constexpr
size_t maxv = (1 << tobits) - 1;
233 constexpr
size_t max_acc = (1 << (frombits + tobits - 1)) - 1;
236 if (v < 0)
return false;
237 acc = ((acc << frombits) | v) & max_acc;
239 while (bits >= tobits) {
241 outfn((acc >> bits) & maxv);
246 if (bits) outfn((acc << (tobits - bits)) & maxv);
247 }
else if (bits >= frombits || ((acc << (tobits - bits)) & maxv)) {
265 return (c >=
'A' && c <=
'Z' ? (c -
'A') +
'a' : c);
277 std::string
ToLower(std::string_view str);
291 return (c >=
'a' && c <=
'z' ? (c -
'a') +
'A' : c);
303 std::string
ToUpper(std::string_view str);
333 if (c >=
'0' && c <=
'9')
return c -
'0';
334 if (c >=
'a' && c <=
'f')
return c -
'a' + 0xa;
336 throw "Only lowercase hex digits are allowed, for consistency";
342 std::array<std::byte, N / 2> bytes{};
343 consteval
Hex(
const char (&hex_str)[N])
347 if (hex_str[N - 1])
throw "null terminator required";
348 for (std::size_t i = 0; i < bytes.size(); ++i) {
349 bytes[i] =
static_cast<std::byte
>(
358 bool operator()(std::string_view s1, std::string_view s2)
const 367 return std::hash<std::string>{}(
ToLower(
s));
400 inline namespace hex_literals {
402 template <util::detail::Hex str>
403 constexpr
auto operator""_hex() {
return str.bytes; }
405 template <util::detail::Hex str>
406 constexpr
auto operator""_hex_u8() {
return std::bit_cast<std::array<uint8_t, str.bytes.size()>>(str.bytes); }
408 template <util::detail::Hex str>
409 constexpr
auto operator""_hex_v() {
return std::vector<std::byte>{str.bytes.begin(), str.bytes.end()}; }
411 template <util::detail::Hex str>
412 inline auto operator""_hex_v_u8() {
return std::vector<uint8_t>{
UCharCast(str.bytes.data()),
UCharCast(str.bytes.data() + str.bytes.size())}; }
417 #endif // BITCOIN_UTIL_STRENCODINGS_H bool TimingResistantEqual(const T &a, const T &b)
Timing-attack-resistant comparison.
The full set of allowed chars.
constexpr char ToUpper(char c)
Converts the given character to its uppercase equivalent.
T LocaleIndependentAtoi(std::string_view str)
bool operator()(std::string_view s1, std::string_view s2) const
std::optional< uint64_t > ParseByteUnits(std::string_view str, ByteUnit default_multiplier)
Parse a string with suffix unit [k|K|m|M|g|G|t|T].
bool ParseFixedPoint(std::string_view, int decimals, int64_t *amount_out)
Parse number as fixed point according to JSON number syntax.
constexpr bool IsDigit(char c)
Tests if the given character is a decimal digit.
consteval auto _(util::TranslatedLiteral str)
std::string_view TrimStringView(std::string_view str, std::string_view pattern=" \\\)
consteval uint8_t ConstevalHexDigit(const char c)
consteval version of HexDigit() without the lookup table.
SafeChars
Utilities for converting data from/to strings.
std::string Capitalize(std::string str)
Capitalizes the first character of the given string.
ByteUnit
Used by ParseByteUnits() Lowercase base 1000 Uppercase base 1024.
Chars allowed in filenames.
constexpr bool IsSpace(char c) noexcept
Tests if the given character is a whitespace character.
std::optional< T > ToIntegral(std::string_view str, size_t base=10)
Convert string to integral type T.
unsigned char * UCharCast(char *c)
constexpr char ToLower(char c)
Converts the given character to its lowercase equivalent.
bool ConvertBits(O outfn, It it, It end, I infn={})
Convert from one power-of-2 number base to another.
Chars allowed in URIs (RFC 3986)
std::string FormatParagraph(std::string_view in, size_t width=79, size_t indent=0)
Format a paragraph of text to a fixed width, adding spaces for indentation to any added line...
size_t operator()(std::string_view s) const