Branch data Line data Source code
1 : : // Copyright (c) 2019-present The Bitcoin Core developers
2 : : // Distributed under the MIT software license, see the accompanying
3 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 : :
5 : : #ifndef BITCOIN_UTIL_STRING_H
6 : : #define BITCOIN_UTIL_STRING_H
7 : :
8 : : #include <algorithm>
9 : : #include <array>
10 : : #include <cstddef>
11 : : #include <cstdint>
12 : : #include <initializer_list>
13 : : #include <locale>
14 : : #include <optional>
15 : : #include <span>
16 : : #include <sstream>
17 : : #include <string>
18 : : #include <string_view>
19 : : #include <vector>
20 : :
21 : : #include <attributes.h>
22 : :
23 : : namespace util {
24 : : namespace detail {
25 : : template <unsigned num_params>
26 : : constexpr void CheckNumFormatSpecifiers(const char* str)
27 : : {
28 : : unsigned count_normal{0}; // Number of "normal" specifiers, like %s
29 : : unsigned count_pos{0}; // Max number in positional specifier, like %8$s
30 : : for (auto it{str}; *it != '\0'; ++it) {
31 : : if (*it != '%' || *++it == '%') continue; // Skip escaped %%
32 : :
33 : : auto add_arg = [&] {
34 : : unsigned maybe_num{0};
35 : : while ('0' <= *it && *it <= '9') {
36 : : maybe_num *= 10;
37 : : maybe_num += *it - '0';
38 : : ++it;
39 : : }
40 : :
41 : : if (*it == '$') {
42 : : ++it;
43 : : // Positional specifier, like %8$s
44 : : if (maybe_num == 0) throw "Positional format specifier must have position of at least 1";
45 : : count_pos = std::max(count_pos, maybe_num);
46 : : } else {
47 : : // Non-positional specifier, like %s
48 : : ++count_normal;
49 : : }
50 : : };
51 : :
52 : : // Increase argument count and consume positional specifier, if present.
53 : : add_arg();
54 : :
55 : : // Consume flags.
56 : : while (*it == '#' || *it == '0' || *it == '-' || *it == ' ' || *it == '+') ++it;
57 : :
58 : : auto parse_size = [&] {
59 : : if (*it == '*') {
60 : : ++it;
61 : : add_arg();
62 : : } else {
63 : : while ('0' <= *it && *it <= '9') ++it;
64 : : }
65 : : };
66 : :
67 : : // Consume dynamic or static width value.
68 : : parse_size();
69 : :
70 : : // Consume dynamic or static precision value.
71 : : if (*it == '.') {
72 : : ++it;
73 : : parse_size();
74 : : }
75 : :
76 : : if (*it == '\0') throw "Format specifier incorrectly terminated by end of string";
77 : :
78 : : // Length and type in "[flags][width][.precision][length]type"
79 : : // is not checked. Parsing continues with the next '%'.
80 : : }
81 : : if (count_normal && count_pos) throw "Format specifiers must be all positional or all non-positional!";
82 : : unsigned count{count_normal | count_pos};
83 : : if (num_params != count) throw "Format specifier count must match the argument count!";
84 : : }
85 : : } // namespace detail
86 : :
87 : : /**
88 : : * @brief A wrapper for a compile-time partially validated format string
89 : : *
90 : : * This struct can be used to enforce partial compile-time validation of format
91 : : * strings, to reduce the likelihood of tinyformat throwing exceptions at
92 : : * run-time. Validation is partial to try and prevent the most common errors
93 : : * while avoiding re-implementing the entire parsing logic.
94 : : */
95 : : template <unsigned num_params>
96 : : struct ConstevalFormatString {
97 : : const char* const fmt;
98 : : consteval ConstevalFormatString(const char* str) : fmt{str} { detail::CheckNumFormatSpecifiers<num_params>(fmt); }
99 : : };
100 : :
101 : : /// Replace every non-overlapping occurrence of `search` with `substitute`, treating both literally; the replacement text is not searched again.
102 : : void ReplaceAll(std::string& in_out, std::string_view search, std::string_view substitute);
103 : :
104 : : /** Split a string on any char found in separators, returning a vector.
105 : : *
106 : : * If sep does not occur in sp, a singleton with the entirety of sp is returned.
107 : : *
108 : : * @param[in] include_sep Whether to include the separator at the end of the left side of the splits.
109 : : *
110 : : * Note that this function does not care about braces, so splitting
111 : : * "foo(bar(1),2),3) on ',' will return {"foo(bar(1)", "2)", "3)"}.
112 : : *
113 : : * If include_sep == true, splitting "foo(bar(1),2),3) on ','
114 : : * will return:
115 : : * - foo(bar(1),
116 : : * - 2),
117 : : * - 3)
118 : : */
119 : : template <typename T = std::span<const char>>
120 : 943248 : std::vector<T> Split(const std::span<const char>& sp, std::string_view separators, bool include_sep = false)
121 : : {
122 : 943248 : std::vector<T> ret;
123 : 943248 : auto it = sp.begin();
124 : 943248 : auto start = it;
125 [ + + ]: 139992231 : while (it != sp.end()) {
126 [ + + ]: 139048983 : if (separators.find(*it) != std::string::npos) {
127 [ + + ]: 711468 : if (include_sep) {
128 [ + - ]: 15346 : ret.emplace_back(start, it + 1);
129 : : } else {
130 [ + - ]: 696122 : ret.emplace_back(start, it);
131 : : }
132 : 711468 : start = it + 1;
133 : : }
134 : 139048983 : ++it;
135 : : }
136 [ + - ]: 943248 : ret.emplace_back(start, it);
137 : 943248 : return ret;
138 : 0 : }
139 : :
140 : : /** Split a string on every instance of sep, returning a vector.
141 : : *
142 : : * If sep does not occur in sp, a singleton with the entirety of sp is returned.
143 : : *
144 : : * Note that this function does not care about braces, so splitting
145 : : * "foo(bar(1),2),3) on ',' will return {"foo(bar(1)", "2)", "3)"}.
146 : : */
147 : : template <typename T = std::span<const char>>
148 : 934553 : std::vector<T> Split(const std::span<const char>& sp, char sep, bool include_sep = false)
149 : : {
150 : 934553 : return Split<T>(sp, std::string_view{&sep, 1}, include_sep);
151 : : }
152 : :
153 : 49822 : [[nodiscard]] inline std::vector<std::string> SplitString(std::string_view str, char sep)
154 : : {
155 [ + - ]: 49822 : return Split<std::string>(str, sep);
[ + - - - ]
[ - - - -
+ - + - ]
[ # # # #
# # # # #
# ]
156 : : }
157 : :
158 : 1060 : [[nodiscard]] inline std::vector<std::string> SplitString(std::string_view str, std::string_view separators)
159 : : {
160 [ + - ]: 1060 : return Split<std::string>(str, separators);
161 : : }
162 : :
163 : 47656 : [[nodiscard]] inline std::string_view TrimStringView(std::string_view str, std::string_view pattern = " \f\n\r\t\v")
164 : : {
165 : 47656 : std::string::size_type front = str.find_first_not_of(pattern);
166 [ + + ]: 47656 : if (front == std::string::npos) {
167 : 1671 : return {};
168 : : }
169 : 45985 : std::string::size_type end = str.find_last_not_of(pattern);
170 : 45985 : return str.substr(front, end - front + 1);
171 : : }
172 : :
173 : 7909 : [[nodiscard]] inline std::string TrimString(std::string_view str, std::string_view pattern = " \f\n\r\t\v")
174 : : {
175 : 7909 : return std::string(TrimStringView(str, pattern));
176 : : }
177 : :
178 : 0 : [[nodiscard]] inline std::string_view RemoveSuffixView(std::string_view str, std::string_view suffix)
179 : : {
180 [ # # ]: 0 : if (str.ends_with(suffix)) {
181 : 0 : return str.substr(0, str.size() - suffix.size());
182 : : }
183 : 0 : return str;
184 : : }
185 : :
186 : 4555770 : [[nodiscard]] inline std::string_view RemovePrefixView(std::string_view str, std::string_view prefix)
187 : : {
188 [ + + ]: 4555770 : if (str.starts_with(prefix)) {
189 : 4555403 : return str.substr(prefix.size());
190 : : }
191 : 367 : return str;
192 : : }
193 : :
194 : 882 : [[nodiscard]] inline std::string RemovePrefix(std::string_view str, std::string_view prefix)
195 : : {
196 : 882 : return std::string(RemovePrefixView(str, prefix));
197 : : }
198 : :
199 : : /**
200 : : * Join all container items. Typically used to concatenate strings but accepts
201 : : * containers with elements of any type.
202 : : *
203 : : * @param container The items to join
204 : : * @param separator The separator
205 : : * @param unary_op Apply this operator to each item
206 : : */
207 : : template <typename C, typename S, typename UnaryOp>
208 : : // NOLINTNEXTLINE(misc-no-recursion)
209 : 367092 : auto Join(const C& container, const S& separator, UnaryOp unary_op)
210 : : {
211 : 367092 : decltype(unary_op(*container.begin())) ret;
212 : 367092 : bool first{true};
213 [ + + ][ # # ]: 568616 : for (const auto& item : container) {
214 [ + + ]: 292445 : if (!first) ret += separator;
[ + + - + ]
[ + + + - ]
[ # # # # ]
215 [ - + ][ + - ]: 313188 : ret += unary_op(item);
[ + - - + ]
216 : 201524 : first = false;
217 : : }
218 : 367092 : return ret;
219 : 0 : }
220 : :
221 : : template <typename C, typename S>
222 : 358541 : auto Join(const C& container, const S& separator)
223 : : {
224 [ - - ]: 538261 : return Join(container, separator, [](const auto& i) { return i; });
[ - + - + ]
225 : : }
226 : :
227 : : /**
228 : : * Create an unordered multi-line list of items.
229 : : */
230 : 80 : inline std::string MakeUnorderedList(const std::vector<std::string>& items)
231 : : {
232 [ + - + - ]: 560 : return Join(items, "\n", [](const std::string& item) { return "- " + item; });
233 : : }
234 : :
235 : : /**
236 : : * Check if a string contains any embedded NUL (\0) characters
237 : : */
238 : 971499 : [[nodiscard]] inline bool ContainsNUL(std::string_view str) noexcept
239 : : {
240 [ + + ]: 59748783 : for (auto c : str) {
[ + + + + ]
[ + + + +
+ + + + +
+ ]
241 [ + + ]: 58947035 : if (c == 0) return true;
[ + + + + ]
[ + + + +
+ + + + +
- ]
242 : : }
243 : : return false;
244 : : }
245 : :
246 : : /**
247 : : * Locale-independent version of std::to_string
248 : : */
249 : : template <typename T>
250 : 104121 : std::string ToString(const T& t)
251 : : {
252 : 104121 : std::ostringstream oss;
253 [ + - + - ]: 104121 : oss.imbue(std::locale::classic());
254 [ + - ]: 104121 : oss << t;
[ + - + - ]
255 : 104121 : return oss.str();
256 : 104121 : }
257 : :
258 : : /**
259 : : * Check whether a container begins with the given prefix.
260 : : */
261 : : template <typename T1, size_t PREFIX_LEN>
262 [ + + ][ + - ]: 777929689 : [[nodiscard]] inline bool HasPrefix(const T1& obj,
263 : : const std::array<uint8_t, PREFIX_LEN>& prefix)
264 : : {
265 [ + - + + ]: 1554324050 : return obj.size() >= PREFIX_LEN &&
[ + - + + ]
266 [ + + ][ + + ]: 777929689 : std::equal(std::begin(prefix), std::end(prefix), std::begin(obj));
267 : : }
268 : :
269 : : class LineReader
270 : : {
271 : : const std::string_view m_str;
272 : : const size_t m_max_line_length;
273 : : std::string_view::iterator m_it;
274 : :
275 : : public:
276 : : explicit LineReader(std::string_view str, size_t max_line_length);
277 : :
278 : : /**
279 : : * Returns a string from current iterator position up to (but not including) next \n
280 : : * and advances iterator to the character following the \n on success.
281 : : * Will not return a line longer than max_line_length.
282 : : * @returns the next string from the buffer.
283 : : * std::nullopt if end of buffer is reached without finding a \n.
284 : : * @throws a std::runtime_error if max_line_length + 1 bytes are read without finding \n.
285 : : */
286 : : std::optional<std::string_view> ReadLine() LIFETIMEBOUND;
287 : :
288 : : /**
289 : : * Returns string from current iterator position of specified length
290 : : * if possible and advances iterator on success.
291 : : * May exceed max_line_length but will not read past end of buffer.
292 : : * @param[in] len The number of bytes to read from the buffer
293 : : * @returns a string of the expected length.
294 : : * @throws a std::runtime_error if there is not enough data in the buffer.
295 : : */
296 : : std::string_view ReadLength(size_t len) LIFETIMEBOUND;
297 : :
298 : : /**
299 : : * Returns remaining size of bytes in buffer
300 : : */
301 : : size_t Remaining() const;
302 : :
303 : : /**
304 : : * Returns number of bytes already read from buffer
305 : : */
306 : : size_t Consumed() const;
307 : : };
308 : : } // namespace util
309 : :
310 : : #endif // BITCOIN_UTIL_STRING_H
|