Bitcoin ABC 0.34.2
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 <crypto/hex_base.h> // IWYU pragma: export
13#include <span.h>
14#include <util/string.h>
15
16#include <charconv>
17#include <cstdint>
18#include <iterator>
19#include <optional>
20#include <string>
21#include <vector>
22
33};
34
43std::string SanitizeString(std::string_view str, int rule = SAFE_CHARS_DEFAULT);
48template <typename Byte = std::byte>
49std::optional<std::vector<Byte>> TryParseHex(std::string_view str);
52template <typename Byte = uint8_t>
53std::vector<Byte> ParseHex(std::string_view hex_str) {
54 return TryParseHex<Byte>(hex_str).value_or(std::vector<Byte>{});
55}
60bool IsHex(std::string_view str);
61std::optional<std::vector<uint8_t>> DecodeBase64(std::string_view str);
62std::string EncodeBase64(Span<const uint8_t> input);
63inline std::string EncodeBase64(Span<const std::byte> input) {
64 return EncodeBase64(MakeUCharSpan(input));
65}
66inline std::string EncodeBase64(std::string_view str) {
67 return EncodeBase64(MakeUCharSpan(str));
68}
69std::optional<std::vector<uint8_t>> DecodeBase32(std::string_view str);
70
76std::string EncodeBase32(Span<const uint8_t> input, bool pad = true);
77
83std::string EncodeBase32(std::string_view str, bool pad = true);
84
95bool SplitHostPort(std::string_view in, uint16_t &portOut,
96 std::string &hostOut);
97
98// LocaleIndependentAtoi is provided for backwards compatibility reasons.
99//
100// New code should use ToIntegral or the ParseInt* functions which provide parse
101// error feedback.
102//
103// The goal of LocaleIndependentAtoi is to replicate the exact defined behaviour
104// of atoi and atoi64 as they behave under the "C" locale.
105template <typename T> T LocaleIndependentAtoi(const std::string &str) {
106 static_assert(std::is_integral<T>::value);
107 T result;
108 // Emulate atoi(...) handling of white space and leading +/-.
109 std::string s = util::TrimString(str);
110 if (!s.empty() && s[0] == '+') {
111 if (s.length() >= 2 && s[1] == '-') {
112 return 0;
113 }
114 s = s.substr(1);
115 }
116 auto [_, error_condition] =
117 std::from_chars(s.data(), s.data() + s.size(), result);
118 if (error_condition != std::errc{}) {
119 return 0;
120 }
121 return result;
122}
123
129constexpr bool IsDigit(char c) {
130 return c >= '0' && c <= '9';
131}
132
145constexpr inline bool IsSpace(char c) noexcept {
146 return c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' ||
147 c == '\v';
148}
149
158template <typename T> std::optional<T> ToIntegral(std::string_view str) {
159 static_assert(std::is_integral<T>::value);
160 T result;
161 const auto [first_nonmatching, error_condition] =
162 std::from_chars(str.data(), str.data() + str.size(), result);
163 if (first_nonmatching != str.data() + str.size() ||
164 error_condition != std::errc{}) {
165 return std::nullopt;
166 }
167 return result;
168}
169
175[[nodiscard]] bool ParseInt32(std::string_view str, int32_t *out);
176
182[[nodiscard]] bool ParseInt64(std::string_view str, int64_t *out);
183
191[[nodiscard]] bool ParseUInt8(std::string_view str, uint8_t *out);
192
200[[nodiscard]] bool ParseUInt16(std::string_view str, uint16_t *out);
201
208[[nodiscard]] bool ParseUInt32(std::string_view str, uint32_t *out);
209
216[[nodiscard]] bool ParseUInt64(std::string_view str, uint64_t *out);
217
222std::string FormatParagraph(std::string_view in, size_t width = 79,
223 size_t indent = 0);
224
229template <typename T> bool TimingResistantEqual(const T &a, const T &b) {
230 if (b.size() == 0) {
231 return a.size() == 0;
232 }
233 size_t accumulator = a.size() ^ b.size();
234 for (size_t i = 0; i < a.size(); i++) {
235 accumulator |= size_t(a[i] ^ b[i % b.size()]);
236 }
237 return accumulator == 0;
238}
239
247[[nodiscard]] bool ParseFixedPoint(std::string_view, int decimals,
248 int64_t *amount_out);
249
250namespace {
255struct IntIdentity {
256 [[maybe_unused]] int operator()(int x) const { return x; }
257};
258
259} // namespace
260
267template <int frombits, int tobits, bool pad, typename O, typename It,
268 typename I = IntIdentity>
269bool ConvertBits(O outfn, It it, It end, I infn = {}) {
270 size_t acc = 0;
271 size_t bits = 0;
272 constexpr size_t maxv = (1 << tobits) - 1;
273 constexpr size_t max_acc = (1 << (frombits + tobits - 1)) - 1;
274 while (it != end) {
275 int v = infn(*it);
276 if (v < 0) {
277 return false;
278 }
279 acc = ((acc << frombits) | v) & max_acc;
280 bits += frombits;
281 while (bits >= tobits) {
282 bits -= tobits;
283 outfn((acc >> bits) & maxv);
284 }
285 ++it;
286 }
287
288 if (pad) {
289 if (bits) {
290 outfn((acc << (tobits - bits)) & maxv);
291 }
292 } else if (bits >= frombits || ((acc << (tobits - bits)) & maxv)) {
293 return false;
294 }
295
296 return true;
297}
298
309constexpr char ToLower(char c) {
310 return (c >= 'A' && c <= 'Z' ? (c - 'A') + 'a' : c);
311}
312
322std::string ToLower(std::string_view str);
323
334constexpr char ToUpper(char c) {
335 return (c >= 'a' && c <= 'z' ? (c - 'a') + 'A' : c);
336}
337
347std::string ToUpper(std::string_view str);
348
358std::string Capitalize(std::string str);
359
360#endif // BITCOIN_UTIL_STRENCODINGS_H
std::string TrimString(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
Definition: string.h:84
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 ParseInt32(std::string_view str, int32_t *out)
Convert string to signed 32-bit integer with strict parse error feedback.
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:309
constexpr bool IsDigit(char c)
Tests if the given character is a decimal digit.
Definition: strencodings.h:129
constexpr char ToUpper(char c)
Converts the given character to its uppercase equivalent.
Definition: strencodings.h:334
T LocaleIndependentAtoi(const std::string &str)
Definition: strencodings.h:105
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:229
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:53
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:145
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:158
std::optional< std::vector< uint8_t > > DecodeBase64(std::string_view str)
bool SplitHostPort(std::string_view in, uint16_t &portOut, std::string &hostOut)
Splits socket address string into host string and port value.
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:269
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:24
@ SAFE_CHARS_DEFAULT
The full set of allowed chars.
Definition: strencodings.h:26
@ SAFE_CHARS_UA_COMMENT
BIP-0014 subset.
Definition: strencodings.h:28
@ SAFE_CHARS_URI
Chars allowed in URIs (RFC 3986)
Definition: strencodings.h:32
@ SAFE_CHARS_FILENAME
Chars allowed in filenames.
Definition: strencodings.h:30
std::optional< std::vector< uint8_t > > DecodeBase32(std::string_view str)
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:68