Debian Codegraph @

Source/Core/Common/StringUtil.h

raw symbols SCIP
1 // Copyright 2008 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #pragma once
5
6 #include <charconv>
7 #include <concepts>
8 #include <cstdarg>
9 #include <cstddef>
10 #include <cstdlib>
11 #include <filesystem>
12 #include <iomanip>
13 #include <limits>
14 #include <locale>
15 #include <ranges>
16 #include <span>
17 #include <sstream>
18 #include <string>
19 #include <type_traits>
20 #include <utility>
21 #include <vector>
22
23 #include "Common/CommonTypes.h"
24 #include "Common/TypeUtils.h"
25
26 std::string StringFromFormatV(const char* format, va_list args);
27
28 std::string StringFromFormat(const char* format, ...)
29 #if !defined _WIN32
30 // On compilers that support function attributes, this gives StringFromFormat
31 // the same errors and warnings that printf would give.
32 __attribute__((__format__(printf, 1, 2)))
33 #endif
34 ;
35
36 // Cheap!
37 bool CharArrayFromFormatV(char* out, int outsize, const char* format, va_list args);
38
39 template <size_t Count>
40 inline void CharArrayFromFormat(char (&out)[Count], const char* format, ...)
41 {
42 va_list args;
43 va_start(args, format);
44 CharArrayFromFormatV(out, Count, format, args);
45 va_end(args);
46 }
47
48 // Good
49 std::string ArrayToString(const u8* data, u32 size, int line_len = 20, bool spaces = true);
50
51 std::string_view StripWhitespace(std::string_view s);
52 std::string_view StripSpaces(std::string_view s);
53 std::string_view StripQuotes(std::string_view s);
54
55 std::string ReplaceAll(std::string result, std::string_view src, std::string_view dest);
56
57 void ReplaceBreaksWithSpaces(std::string& str);
58
59 void TruncateToCString(std::string* s);
60
61 bool TryParse(const std::string& str, bool* output);
62
63 template <typename T>
64 requires(std::is_integral_v<T> || (std::is_enum_v<T> && !Common::BooleanEnum<T>))
65 bool TryParse(const std::string& str, T* output, int base = 0)
66 {
67 char* end_ptr = nullptr;
68
69 // Set errno to a clean slate.
70 errno = 0;
71
72 // Read a u64 for unsigned types and s64 otherwise.
73 using ReadType = std::conditional_t<std::is_unsigned_v<T>, u64, s64>;
74 ReadType value;
75
76 if constexpr (std::is_unsigned_v<T>)
77 value = std::strtoull(str.c_str(), &end_ptr, base);
78 else
79 value = std::strtoll(str.c_str(), &end_ptr, base);
80
81 // Fail if the end of the string wasn't reached.
82 if (end_ptr == nullptr || *end_ptr != '\0')
83 return false;
84
85 // Fail if the value was out of 64-bit range.
86 if (errno == ERANGE)
87 return false;
88
89 using LimitsType = typename std::conditional_t<std::is_enum_v<T>, std::underlying_type<T>,
90 std::common_type<T>>::type;
91 // Fail if outside numeric limits.
92 if (value < std::numeric_limits<LimitsType>::min() ||
93 value > std::numeric_limits<LimitsType>::max())
94 {
95 return false;
96 }
97
98 *output = static_cast<T>(value);
99 return true;
100 }
101
102 template <Common::BooleanEnum T>
103 bool TryParse(const std::string& str, T* output)
104 {
105 bool value;
106 if (!TryParse(str, &value))
107 return false;
108
109 *output = static_cast<T>(value);
110 return true;
111 }
112
113 template <std::floating_point T>
114 bool TryParse(std::string str, T* const output)
115 {
116 // Replace commas with dots.
117 std::istringstream iss(ReplaceAll(std::move(str), ",", "."));
118
119 // Use "classic" locale to force a "dot" decimal separator.
120 iss.imbue(std::locale::classic());
121
122 T tmp;
123
124 // Succeed if a value was read and the entire string was used.
125 if (iss >> tmp && iss.eof())
126 {
127 *output = tmp;
128 return true;
129 }
130
131 return false;
132 }
133
134 template <typename N>
135 bool TryParseVector(const std::string& str, std::vector<N>* output, const char delimiter = ',')
136 {
137 output->clear();
138 std::istringstream buffer(str);
139 std::string variable;
140
141 while (std::getline(buffer, variable, delimiter))
142 {
143 N tmp = 0;
144 if (!TryParse(variable, &tmp))
145 return false;
146 output->push_back(tmp);
147 }
148 return true;
149 }
150
151 std::string ValueToString(u16 value);
152 std::string ValueToString(u32 value);
153 std::string ValueToString(u64 value);
154 std::string ValueToString(float value);
155 std::string ValueToString(double value);
156 std::string ValueToString(int value);
157 std::string ValueToString(s64 value);
158 std::string ValueToString(bool value);
159 std::string ValueToString(Common::Enum auto value)
160 {
161 return ValueToString(std::to_underlying(value));
162 }
163
164 // Generates an hexdump-like representation of a binary data blob.
165 std::string HexDump(const u8* data, size_t size);
166
167 inline auto HexDump(std::span<const u8> data)
168 {
169 return HexDump(data.data(), data.size());
170 }
171
172 namespace Common
173 {
174 std::from_chars_result FromChars(std::string_view sv, std::integral auto& value, int base = 10)
175 {
176 const char* const first = sv.data();
177 const char* const last = first + sv.size();
178 return std::from_chars(first, last, value, base);
179 }
180 std::from_chars_result FromChars(std::string_view sv, std::floating_point auto& value,
181 std::chars_format fmt = std::chars_format::general)
182 {
183 const char* const first = sv.data();
184 const char* const last = first + sv.size();
185 return std::from_chars(first, last, value, fmt);
186 }
187 } // namespace Common
188
189 std::vector<std::string> SplitString(const std::string& str, char delim);
190
191 // Returns `nullopt` if subject does not contain exactly (Count - 1) delim.
192 template <std::size_t Count>
193 requires(Count > 1)
194 std::optional<std::array<std::string_view, Count>> SplitStringIntoArray(std::string_view subject,
195 char delim)
196 {
197 std::optional<std::array<std::string_view, Count>> result;
198 result.emplace();
199
200 std::size_t index = 0;
201 for (auto&& item : subject | std::views::split(delim))
202 {
203 // Too many delim.
204 if (index == Count)
205 return std::nullopt;
206
207 (*result)[index++] = std::string_view{item};
208 }
209
210 // Too few delim.
211 if (index != Count)
212 return std::nullopt;
213
214 return result;
215 }
216
217 // "C:/Windows/winhelp.exe" to "C:/Windows/", "winhelp", ".exe"
218 // This requires forward slashes to be used for the path separators, even on Windows.
219 bool SplitPath(std::string_view full_path, std::string* path, std::string* filename,
220 std::string* extension);
221
222 // Converts the path separators of a path into forward slashes on Windows, which is assumed to be
223 // true for paths at various places in the codebase.
224 void UnifyPathSeparators(std::string& path);
225 std::string WithUnifiedPathSeparators(std::string path);
226
227 // Extracts just the filename (including extension) from a full path.
228 // This requires forward slashes to be used for the path separators, even on Windows.
229 std::string PathToFileName(std::string_view path);
230
231 void StringPopBackIf(std::string* s, char c);
232 size_t StringUTF8CodePointCount(std::string_view str);
233
234 std::string CP1252ToUTF8(std::string_view input);
235 std::string SHIFTJISToUTF8(std::string_view input);
236 std::string UTF8ToSHIFTJIS(std::string_view input);
237 std::string WStringToUTF8(std::wstring_view input);
238 std::string UTF16BEToUTF8(const char16_t* str, size_t max_size); // Stops at \0
239 std::string UTF16ToUTF8(std::u16string_view input);
240 std::u16string UTF8ToUTF16(std::string_view input);
241
242 #ifdef _WIN32
243
244 std::wstring UTF8ToWString(std::string_view str);
245
246 #ifdef _UNICODE
247 inline std::string TStrToUTF8(std::wstring_view str)
248 {
249 return WStringToUTF8(str);
250 }
251
252 inline std::wstring UTF8ToTStr(std::string_view str)
253 {
254 return UTF8ToWString(str);
255 }
256 #else
257 inline std::string TStrToUTF8(std::string_view str)
258 {
259 return str;
260 }
261
262 inline std::string UTF8ToTStr(std::string_view str)
263 {
264 return str;
265 }
266 #endif
267
268 #endif
269
270 std::filesystem::path StringToPath(std::string_view path);
271 std::string PathToString(const std::filesystem::path& path);
272
273 namespace Common
274 {
275 /// Returns whether a character is printable, i.e. whether 0x20 <= c <= 0x7e is true.
276 /// Use this instead of calling std::isprint directly to ensure
277 /// the C locale is being used and to avoid possibly undefined behaviour.
278 inline bool IsPrintableCharacter(char c)
279 {
280 return std::isprint(c, std::locale::classic());
281 }
282
283 /// Returns whether a character is a letter, i.e. whether 'a' <= c <= 'z' || 'A' <= c <= 'Z'
284 /// is true. Use this instead of calling std::isalpha directly to ensure
285 /// the C locale is being used and to avoid possibly undefined behaviour.
286 inline bool IsAlpha(char c)
287 {
288 return std::isalpha(c, std::locale::classic());
289 }
290
291 inline bool IsAlnum(char c)
292 {
293 return std::isalnum(c, std::locale::classic());
294 }
295
296 inline bool IsUpper(char c)
297 {
298 return std::isupper(c, std::locale::classic());
299 }
300
301 inline bool IsXDigit(char c)
302 {
303 return std::isxdigit(c /* no locale needed */) != 0;
304 }
305
306 inline char ToLower(char ch)
307 {
308 return std::tolower(ch, std::locale::classic());
309 }
310
311 inline char ToUpper(char ch)
312 {
313 return std::toupper(ch, std::locale::classic());
314 }
315
316 // Thousand separator. Turns 12345678 into 12,345,678
317 template <typename I>
318 std::string ThousandSeparate(I value, int spaces = 0)
319 {
320 #ifdef _WIN32
321 std::wostringstream stream;
322 #else
323 std::ostringstream stream;
324 #endif
325
326 stream << std::setw(spaces) << value;
327
328 #ifdef _WIN32
329 return WStringToUTF8(stream.str());
330 #else
331 return stream.str();
332 #endif
333 }
334
335 #ifdef _WIN32
336 std::vector<std::string> CommandLineToUtf8Argv(const wchar_t* command_line);
337 #endif
338
339 std::string GetEscapedHtml(std::string html);
340
341 void ToLower(std::string* str);
342 void ToUpper(std::string* str);
343 bool CaseInsensitiveEquals(std::string_view a, std::string_view b);
344 bool CaseInsensitiveContains(std::string_view haystack, std::string_view needle);
345
346 // 'std::less'-like comparison function object type for case-insensitive strings.
347 struct CaseInsensitiveLess
348 {
349 using is_transparent = void; // Allow heterogeneous lookup.
350 bool operator()(std::string_view a, std::string_view b) const;
351 };
352
353 std::string BytesToHexString(std::span<const u8> bytes);
354 } // namespace Common