Bitcoin ABC 0.30.5
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
14#include <charconv>
15#include <cstdint>
16#include <iterator>
17#include <optional>
18#include <string>
19#include <vector>
20
31};
32
41std::string SanitizeString(std::string_view str, int rule = SAFE_CHARS_DEFAULT);
46template <typename Byte = std::byte>
47std::optional<std::vector<Byte>> TryParseHex(std::string_view str);
50template <typename Byte = uint8_t>
51std::vector<Byte> ParseHex(std::string_view hex_str) {
52 return TryParseHex<Byte>(hex_str).value_or(std::vector<Byte>{});
53}
54signed char HexDigit(char c);
59bool IsHex(std::string_view str);
63bool IsHexNumber(std::string_view str);
64std::optional<std::vector<uint8_t>> DecodeBase64(std::string_view str);
65std::string EncodeBase64(Span<const uint8_t> input);
66inline std::string EncodeBase64(Span<const std::byte> input) {
67 return EncodeBase64(MakeUCharSpan(input));
68}
69inline std::string EncodeBase64(std::string_view str) {
70 return EncodeBase64(MakeUCharSpan(str));
71}
72std::optional<std::vector<uint8_t>> DecodeBase32(std::string_view str);
73
79std::string EncodeBase32(Span<const uint8_t> input, bool pad = true);
80
86std::string EncodeBase32(std::string_view str, bool pad = true);
87
88void SplitHostPort(std::string_view in, uint16_t &portOut,
89 std::string &hostOut);
90int64_t atoi64(const std::string &str);
91int atoi(const std::string &str);
92
98constexpr bool IsDigit(char c) {
99 return c >= '0' && c <= '9';
100}
101
114constexpr inline bool IsSpace(char c) noexcept {
115 return c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' ||
116 c == '\v';
117}
118
127template <typename T> std::optional<T> ToIntegral(std::string_view str) {
128 static_assert(std::is_integral<T>::value);
129 T result;
130 const auto [first_nonmatching, error_condition] =
131 std::from_chars(str.data(), str.data() + str.size(), result);
132 if (first_nonmatching != str.data() + str.size() ||
133 error_condition != std::errc{}) {
134 return std::nullopt;
135 }
136 return result;
137}
138
144[[nodiscard]] bool ParseInt32(std::string_view str, int32_t *out);
145
151[[nodiscard]] bool ParseInt64(std::string_view str, int64_t *out);
152
160[[nodiscard]] bool ParseUInt8(std::string_view str, uint8_t *out);
161
169[[nodiscard]] bool ParseUInt16(std::string_view str, uint16_t *out);
170
177[[nodiscard]] bool ParseUInt32(std::string_view str, uint32_t *out);
178
185[[nodiscard]] bool ParseUInt64(std::string_view str, uint64_t *out);
186
190std::string HexStr(const Span<const uint8_t> s);
191inline std::string HexStr(const Span<const char> s) {
192 return HexStr(MakeUCharSpan(s));
193}
194inline std::string HexStr(const Span<const std::byte> s) {
195 return HexStr(MakeUCharSpan(s));
196}
197
202std::string FormatParagraph(std::string_view in, size_t width = 79,
203 size_t indent = 0);
204
209template <typename T> bool TimingResistantEqual(const T &a, const T &b) {
210 if (b.size() == 0) {
211 return a.size() == 0;
212 }
213 size_t accumulator = a.size() ^ b.size();
214 for (size_t i = 0; i < a.size(); i++) {
215 accumulator |= size_t(a[i] ^ b[i % b.size()]);
216 }
217 return accumulator == 0;
218}
219
227[[nodiscard]] bool ParseFixedPoint(std::string_view, int decimals,
228 int64_t *amount_out);
229
230namespace {
235struct IntIdentity {
236 [[maybe_unused]] int operator()(int x) const { return x; }
237};
238
239} // namespace
240
247template <int frombits, int tobits, bool pad, typename O, typename It,
248 typename I = IntIdentity>
249bool ConvertBits(O outfn, It it, It end, I infn = {}) {
250 size_t acc = 0;
251 size_t bits = 0;
252 constexpr size_t maxv = (1 << tobits) - 1;
253 constexpr size_t max_acc = (1 << (frombits + tobits - 1)) - 1;
254 while (it != end) {
255 int v = infn(*it);
256 if (v < 0) {
257 return false;
258 }
259 acc = ((acc << frombits) | v) & max_acc;
260 bits += frombits;
261 while (bits >= tobits) {
262 bits -= tobits;
263 outfn((acc >> bits) & maxv);
264 }
265 ++it;
266 }
267
268 if (pad) {
269 if (bits) {
270 outfn((acc << (tobits - bits)) & maxv);
271 }
272 } else if (bits >= frombits || ((acc << (tobits - bits)) & maxv)) {
273 return false;
274 }
275
276 return true;
277}
278
289constexpr char ToLower(char c) {
290 return (c >= 'A' && c <= 'Z' ? (c - 'A') + 'a' : c);
291}
292
302std::string ToLower(std::string_view str);
303
314constexpr char ToUpper(char c) {
315 return (c >= 'a' && c <= 'z' ? (c - 'a') + 'A' : c);
316}
317
327std::string ToUpper(std::string_view str);
328
338std::string Capitalize(std::string str);
339
340#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:337
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:289
constexpr bool IsDigit(char c)
Tests if the given character is a decimal digit.
Definition: strencodings.h:98
constexpr char ToUpper(char c)
Converts the given character to its uppercase equivalent.
Definition: strencodings.h:314
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:209
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:51
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:114
signed char HexDigit(char c)
int atoi(const std::string &str)
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.
int64_t atoi64(const std::string &str)
std::optional< T > ToIntegral(std::string_view str)
Convert string to integral type T.
Definition: strencodings.h:127
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:249
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:22
@ SAFE_CHARS_DEFAULT
The full set of allowed chars.
Definition: strencodings.h:24
@ SAFE_CHARS_UA_COMMENT
BIP-0014 subset.
Definition: strencodings.h:26
@ SAFE_CHARS_URI
Chars allowed in URIs (RFC 3986)
Definition: strencodings.h:30
@ SAFE_CHARS_FILENAME
Chars allowed in filenames.
Definition: strencodings.h:28
std::optional< std::vector< uint8_t > > DecodeBase32(std::string_view str)