Bitcoin ABC 0.32.4
P2P Digital Currency
strencodings.h
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2016 The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
9#ifndef BITCOIN_UTIL_STRENCODINGS_H
10#define BITCOIN_UTIL_STRENCODINGS_H
11
12#include <span.h>
13#include <util/string.h>
14
15#include <charconv>
16#include <cstdint>
17#include <iterator>
18#include <optional>
19#include <string>
20#include <vector>
21
32};
33
42std::string SanitizeString(std::string_view str, int rule = SAFE_CHARS_DEFAULT);
47template <typename Byte = std::byte>
48std::optional<std::vector<Byte>> TryParseHex(std::string_view str);
51template <typename Byte = uint8_t>
52std::vector<Byte> ParseHex(std::string_view hex_str) {
53 return TryParseHex<Byte>(hex_str).value_or(std::vector<Byte>{});
54}
55signed char HexDigit(char c);
60bool IsHex(std::string_view str);
64bool IsHexNumber(std::string_view str);
65std::optional<std::vector<uint8_t>> DecodeBase64(std::string_view str);
66std::string EncodeBase64(Span<const uint8_t> input);
67inline std::string EncodeBase64(Span<const std::byte> input) {
68 return EncodeBase64(MakeUCharSpan(input));
69}
70inline std::string EncodeBase64(std::string_view str) {
71 return EncodeBase64(MakeUCharSpan(str));
72}
73std::optional<std::vector<uint8_t>> DecodeBase32(std::string_view str);
74
80std::string EncodeBase32(Span<const uint8_t> input, bool pad = true);
81
87std::string EncodeBase32(std::string_view str, bool pad = true);
88
89void SplitHostPort(std::string_view in, uint16_t &portOut,
90 std::string &hostOut);
91
92// LocaleIndependentAtoi is provided for backwards compatibility reasons.
93//
94// New code should use ToIntegral or the ParseInt* functions which provide parse
95// error feedback.
96//
97// The goal of LocaleIndependentAtoi is to replicate the exact defined behaviour
98// of atoi and atoi64 as they behave under the "C" locale.
99template <typename T> T LocaleIndependentAtoi(const std::string &str) {
100 static_assert(std::is_integral<T>::value);
101 T result;
102 // Emulate atoi(...) handling of white space and leading +/-.
103 std::string s = TrimString(str);
104 if (!s.empty() && s[0] == '+') {
105 if (s.length() >= 2 && s[1] == '-') {
106 return 0;
107 }
108 s = s.substr(1);
109 }
110 auto [_, error_condition] =
111 std::from_chars(s.data(), s.data() + s.size(), result);
112 if (error_condition != std::errc{}) {
113 return 0;
114 }
115 return result;
116}
117
123constexpr bool IsDigit(char c) {
124 return c >= '0' && c <= '9';
125}
126
139constexpr inline bool IsSpace(char c) noexcept {
140 return c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' ||
141 c == '\v';
142}
143
152template <typename T> std::optional<T> ToIntegral(std::string_view str) {
153 static_assert(std::is_integral<T>::value);
154 T result;
155 const auto [first_nonmatching, error_condition] =
156 std::from_chars(str.data(), str.data() + str.size(), result);
157 if (first_nonmatching != str.data() + str.size() ||
158 error_condition != std::errc{}) {
159 return std::nullopt;
160 }
161 return result;
162}
163
169[[nodiscard]] bool ParseInt32(std::string_view str, int32_t *out);
170
176[[nodiscard]] bool ParseInt64(std::string_view str, int64_t *out);
177
185[[nodiscard]] bool ParseUInt8(std::string_view str, uint8_t *out);
186
194[[nodiscard]] bool ParseUInt16(std::string_view str, uint16_t *out);
195
202[[nodiscard]] bool ParseUInt32(std::string_view str, uint32_t *out);
203
210[[nodiscard]] bool ParseUInt64(std::string_view str, uint64_t *out);
211
215std::string HexStr(const Span<const uint8_t> s);
216inline std::string HexStr(const Span<const char> s) {
217 return HexStr(MakeUCharSpan(s));
218}
219inline std::string HexStr(const Span<const std::byte> s) {
220 return HexStr(MakeUCharSpan(s));
221}
222
227std::string FormatParagraph(std::string_view in, size_t width = 79,
228 size_t indent = 0);
229
234template <typename T> bool TimingResistantEqual(const T &a, const T &b) {
235 if (b.size() == 0) {
236 return a.size() == 0;
237 }
238 size_t accumulator = a.size() ^ b.size();
239 for (size_t i = 0; i < a.size(); i++) {
240 accumulator |= size_t(a[i] ^ b[i % b.size()]);
241 }
242 return accumulator == 0;
243}
244
252[[nodiscard]] bool ParseFixedPoint(std::string_view, int decimals,
253 int64_t *amount_out);
254
255namespace {
260struct IntIdentity {
261 [[maybe_unused]] int operator()(int x) const { return x; }
262};
263
264} // namespace
265
272template <int frombits, int tobits, bool pad, typename O, typename It,
273 typename I = IntIdentity>
274bool ConvertBits(O outfn, It it, It end, I infn = {}) {
275 size_t acc = 0;
276 size_t bits = 0;
277 constexpr size_t maxv = (1 << tobits) - 1;
278 constexpr size_t max_acc = (1 << (frombits + tobits - 1)) - 1;
279 while (it != end) {
280 int v = infn(*it);
281 if (v < 0) {
282 return false;
283 }
284 acc = ((acc << frombits) | v) & max_acc;
285 bits += frombits;
286 while (bits >= tobits) {
287 bits -= tobits;
288 outfn((acc >> bits) & maxv);
289 }
290 ++it;
291 }
292
293 if (pad) {
294 if (bits) {
295 outfn((acc << (tobits - bits)) & maxv);
296 }
297 } else if (bits >= frombits || ((acc << (tobits - bits)) & maxv)) {
298 return false;
299 }
300
301 return true;
302}
303
314constexpr char ToLower(char c) {
315 return (c >= 'A' && c <= 'Z' ? (c - 'A') + 'a' : c);
316}
317
327std::string ToLower(std::string_view str);
328
339constexpr char ToUpper(char c) {
340 return (c >= 'a' && c <= 'z' ? (c - 'a') + 'A' : c);
341}
342
352std::string ToUpper(std::string_view str);
353
363std::string Capitalize(std::string str);
364
365#endif // BITCOIN_UTIL_STRENCODINGS_H
constexpr auto MakeUCharSpan(V &&v) -> decltype(UCharSpanCast(Span{std::forward< V >(v)}))
Like the Span constructor, but for (const) uint8_t member types only.
Definition: span.h:350
std::string Capitalize(std::string str)
Capitalizes the first character of the given string.
bool IsHexNumber(std::string_view str)
Return true if the string is a hex number, optionally prefixed with "0x".
bool ParseInt32(std::string_view str, int32_t *out)
Convert string to signed 32-bit integer with strict parse error feedback.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::string EncodeBase64(Span< const uint8_t > input)
std::string EncodeBase32(Span< const uint8_t > input, bool pad=true)
Base32 encode.
bool ParseUInt16(std::string_view str, uint16_t *out)
Convert decimal string to unsigned 16-bit integer with strict parse error feedback.
constexpr char ToLower(char c)
Converts the given character to its lowercase equivalent.
Definition: strencodings.h:314
constexpr bool IsDigit(char c)
Tests if the given character is a decimal digit.
Definition: strencodings.h:123
constexpr char ToUpper(char c)
Converts the given character to its uppercase equivalent.
Definition: strencodings.h:339
T LocaleIndependentAtoi(const std::string &str)
Definition: strencodings.h:99
bool ParseInt64(std::string_view str, int64_t *out)
Convert string to signed 64-bit integer with strict parse error feedback.
bool TimingResistantEqual(const T &a, const T &b)
Timing-attack-resistant comparison.
Definition: strencodings.h:234
bool ParseUInt8(std::string_view str, uint8_t *out)
Convert decimal string to unsigned 8-bit integer with strict parse error feedback.
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
Definition: strencodings.h:52
bool ParseFixedPoint(std::string_view, int decimals, int64_t *amount_out)
Parse number as fixed point according to JSON number syntax.
bool ParseUInt64(std::string_view str, uint64_t *out)
Convert decimal string to unsigned 64-bit integer with strict parse error feedback.
constexpr bool IsSpace(char c) noexcept
Tests if the given character is a whitespace character.
Definition: strencodings.h:139
signed char HexDigit(char c)
bool IsHex(std::string_view str)
Returns true if each character in str is a hex character, and has an even number of hex digits.
std::optional< T > ToIntegral(std::string_view str)
Convert string to integral type T.
Definition: strencodings.h:152
std::optional< std::vector< uint8_t > > DecodeBase64(std::string_view str)
bool ParseUInt32(std::string_view str, uint32_t *out)
Convert decimal string to unsigned 32-bit integer with strict parse error feedback.
bool ConvertBits(O outfn, It it, It end, I infn={})
Convert from one power-of-2 number base to another.
Definition: strencodings.h:274
void SplitHostPort(std::string_view in, uint16_t &portOut, std::string &hostOut)
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.
std::string SanitizeString(std::string_view str, int rule=SAFE_CHARS_DEFAULT)
Remove unsafe chars.
std::optional< std::vector< Byte > > TryParseHex(std::string_view str)
Parse the hex string into bytes (uint8_t or std::byte).
SafeChars
Utilities for converting data from/to strings.
Definition: strencodings.h:23
@ SAFE_CHARS_DEFAULT
The full set of allowed chars.
Definition: strencodings.h:25
@ SAFE_CHARS_UA_COMMENT
BIP-0014 subset.
Definition: strencodings.h:27
@ SAFE_CHARS_URI
Chars allowed in URIs (RFC 3986)
Definition: strencodings.h:31
@ SAFE_CHARS_FILENAME
Chars allowed in filenames.
Definition: strencodings.h:29
std::optional< std::vector< uint8_t > > DecodeBase32(std::string_view str)
std::string TrimString(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
Definition: string.h:38
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:68