| 1 | // Copyright 2008 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "Common/StringUtil.h" |
| 5 | |
| 6 | #include <algorithm> |
| 7 | #include <array> |
| 8 | #include <cassert> |
| 9 | #include <cstdarg> |
| 10 | #include <cstddef> |
| 11 | #include <cstdio> |
| 12 | #include <cstdlib> |
| 13 | #include <cstring> |
| 14 | #include <iomanip> |
| 15 | #include <iterator> |
| 16 | #include <sstream> |
| 17 | #include <string> |
| 18 | #include <vector> |
| 19 | |
| 20 | #include <fmt/format.h> |
| 21 | #include <fmt/ranges.h> |
| 22 | |
| 23 | #include "Common/CommonFuncs.h" |
| 24 | #include "Common/CommonTypes.h" |
| 25 | #include "Common/Logging/Log.h" |
| 26 | |
| 27 | #ifdef _WIN32 |
| 28 | #include <Windows.h> |
| 29 | #include <shellapi.h> |
| 30 | constexpr u32 CODEPAGE_SHIFT_JIS = 932; |
| 31 | constexpr u32 CODEPAGE_WINDOWS_1252 = 1252; |
| 32 | |
| 33 | #include "Common/Swap.h" |
| 34 | #else |
| 35 | #include <cerrno> |
| 36 | #include <iconv.h> |
| 37 | #include <locale.h> |
| 38 | #endif |
| 39 | |
| 40 | #if !defined(_WIN32) && !defined(ANDROID) && !defined(__HAIKU__) && !defined(__OpenBSD__) && \ |
| 41 | !defined(__NetBSD__) |
| 42 | static locale_t GetCLocale() |
| 43 | { |
| 44 | static locale_t c_locale = newlocale(LC_ALL_MASK, "C", nullptr); |
| 45 | return c_locale; |
| 46 | } |
| 47 | #endif |
| 48 | |
| 49 | std::string HexDump(const u8* data, size_t size) |
| 50 | { |
| 51 | constexpr size_t BYTES_PER_LINE = 16; |
| 52 | |
| 53 | std::string out; |
| 54 | for (size_t row_start = 0; row_start < size; row_start += BYTES_PER_LINE) |
| 55 | { |
| 56 | out += fmt::format("{:06x}: ", row_start); |
| 57 | for (size_t i = 0; i < BYTES_PER_LINE; ++i) |
| 58 | { |
| 59 | if (row_start + i < size) |
| 60 | { |
| 61 | out += fmt::format("{:02x} ", data[row_start + i]); |
| 62 | } |
| 63 | else |
| 64 | { |
| 65 | out += " "; |
| 66 | } |
| 67 | } |
| 68 | out += " "; |
| 69 | for (size_t i = 0; i < BYTES_PER_LINE; ++i) |
| 70 | { |
| 71 | if (row_start + i < size) |
| 72 | { |
| 73 | char c = static_cast<char>(data[row_start + i]); |
| 74 | out += Common::IsPrintableCharacter(c) ? c : '.'; |
| 75 | } |
| 76 | } |
| 77 | out += "\n"; |
| 78 | } |
| 79 | return out; |
| 80 | } |
| 81 | |
| 82 | bool CharArrayFromFormatV(char* out, int outsize, const char* format, va_list args) |
| 83 | { |
| 84 | #ifdef _WIN32 |
| 85 | // You would think *printf are simple, right? Iterate on each character, |
| 86 | // if it's a format specifier handle it properly, etc. |
| 87 | // |
| 88 | // Nooooo. Not according to the C standard. |
| 89 | // |
| 90 | // According to the C99 standard (7.19.6.1 "The fprintf function") |
| 91 | // The format shall be a multibyte character sequence |
| 92 | // |
| 93 | // Because some character encodings might have '%' signs in the middle of |
| 94 | // a multibyte sequence (SJIS for example only specifies that the first |
| 95 | // byte of a 2 byte sequence is "high", the second byte can be anything), |
| 96 | // printf functions have to decode the multibyte sequences and try their |
| 97 | // best to not screw up. |
| 98 | // |
| 99 | // Unfortunately, on Windows, the locale for most languages is not UTF-8 |
| 100 | // as we would need. Notably, for zh_TW, Windows chooses EUC-CN as the |
| 101 | // locale, and completely fails when trying to decode UTF-8 as EUC-CN. |
| 102 | // |
| 103 | // On the other hand, the fix is simple: because we use UTF-8, no such |
| 104 | // multibyte handling is required as we can simply assume that no '%' char |
| 105 | // will be present in the middle of a multibyte sequence. |
| 106 | // |
| 107 | // This is why we look up the default C locale here and use _vsnprintf_l. |
| 108 | static _locale_t c_locale = nullptr; |
| 109 | if (!c_locale) |
| 110 | c_locale = _create_locale(LC_ALL, "C"); |
| 111 | const int written_count = _vsnprintf_l(out, outsize, format, c_locale, args); |
| 112 | #else |
| 113 | #if !defined(ANDROID) && !defined(__HAIKU__) && !defined(__OpenBSD__) && !defined(__NetBSD__) |
| 114 | locale_t previousLocale = uselocale(GetCLocale()); |
| 115 | #endif |
| 116 | const int written_count = vsnprintf(out, outsize, format, args); |
| 117 | #if !defined(ANDROID) && !defined(__HAIKU__) && !defined(__OpenBSD__) && !defined(__NetBSD__) |
| 118 | uselocale(previousLocale); |
| 119 | #endif |
| 120 | #endif |
| 121 | |
| 122 | if (written_count > 0 && written_count < outsize) |
| 123 | { |
| 124 | out[written_count] = '\0'; |
| 125 | return true; |
| 126 | } |
| 127 | |
| 128 | out[outsize - 1] = '\0'; |
| 129 | return false; |
| 130 | } |
| 131 | |
| 132 | std::string StringFromFormat(const char* format, ...) |
| 133 | { |
| 134 | va_list args; |
| 135 | va_start(args, format); |
| 136 | std::string res = StringFromFormatV(format, args); |
| 137 | va_end(args); |
| 138 | return res; |
| 139 | } |
| 140 | |
| 141 | std::string StringFromFormatV(const char* format, va_list args) |
| 142 | { |
| 143 | char* buf = nullptr; |
| 144 | #ifdef _WIN32 |
| 145 | int required = _vscprintf(format, args); |
| 146 | buf = new char[required + 1]; |
| 147 | CharArrayFromFormatV(buf, required + 1, format, args); |
| 148 | |
| 149 | std::string temp = buf; |
| 150 | delete[] buf; |
| 151 | #else |
| 152 | #if !defined(ANDROID) && !defined(__HAIKU__) && !defined(__OpenBSD__) && !defined(__NetBSD__) |
| 153 | locale_t previousLocale = uselocale(GetCLocale()); |
| 154 | #endif |
| 155 | if (vasprintf(&buf, format, args) < 0) |
| 156 | { |
| 157 | ERROR_LOG_FMT(COMMON, "Unable to allocate memory for string"); |
| 158 | buf = nullptr; |
| 159 | } |
| 160 | |
| 161 | #if !defined(ANDROID) && !defined(__HAIKU__) && !defined(__OpenBSD__) && !defined(__NetBSD__) |
| 162 | uselocale(previousLocale); |
| 163 | #endif |
| 164 | |
| 165 | std::string temp = buf; |
| 166 | free(buf); |
| 167 | #endif |
| 168 | return temp; |
| 169 | } |
| 170 | |
| 171 | // For Debugging. Read out an u8 array. |
| 172 | std::string ArrayToString(const u8* data, u32 size, int line_len, bool spaces) |
| 173 | { |
| 174 | std::ostringstream oss; |
| 175 | oss << std::setfill('0') << std::hex; |
| 176 | |
| 177 | for (int line = 0; size != 0; ++data, --size) |
| 178 | { |
| 179 | oss << std::setw(2) << static_cast<int>(*data); |
| 180 | |
| 181 | if (line_len == ++line) |
| 182 | { |
| 183 | oss << '\n'; |
| 184 | line = 0; |
| 185 | } |
| 186 | else if (spaces) |
| 187 | oss << ' '; |
| 188 | } |
| 189 | |
| 190 | return oss.str(); |
| 191 | } |
| 192 | |
| 193 | template <typename T> |
| 194 | static std::string_view StripEnclosingChars(std::string_view str, T chars) |
| 195 | { |
| 196 | const size_t s = str.find_first_not_of(chars); |
| 197 | |
| 198 | if (str.npos != s) |
| 199 | return str.substr(s, str.find_last_not_of(chars) - s + 1); |
| 200 | |
| 201 | return ""; |
| 202 | } |
| 203 | |
| 204 | // Turns "\n\r\t hello " into "hello" (trims at the start and end but not inside). |
| 205 | std::string_view StripWhitespace(std::string_view str) |
| 206 | { |
| 207 | return StripEnclosingChars(str, " \t\r\n"); |
| 208 | } |
| 209 | |
| 210 | std::string_view StripSpaces(std::string_view str) |
| 211 | { |
| 212 | return StripEnclosingChars(str, ' '); |
| 213 | } |
| 214 | |
| 215 | // "\"hello\"" is turned to "hello" |
| 216 | // This one assumes that the string has already been space stripped in both |
| 217 | // ends, as done by StripWhitespace above, for example. |
| 218 | std::string_view StripQuotes(std::string_view s) |
| 219 | { |
| 220 | if (!s.empty() && '\"' == s[0] && '\"' == *s.rbegin()) |
| 221 | return s.substr(1, s.size() - 2); |
| 222 | |
| 223 | return s; |
| 224 | } |
| 225 | |
| 226 | // Turns "\n\rhello" into " hello". |
| 227 | void ReplaceBreaksWithSpaces(std::string& str) |
| 228 | { |
| 229 | std::ranges::replace(str, '\r', ' '); |
| 230 | std::ranges::replace(str, '\n', ' '); |
| 231 | } |
| 232 | |
| 233 | void TruncateToCString(std::string* s) |
| 234 | { |
| 235 | const size_t terminator = s->find_first_of('\0'); |
| 236 | if (terminator != s->npos) |
| 237 | s->resize(terminator); |
| 238 | } |
| 239 | |
| 240 | bool TryParse(const std::string& str, bool* const output) |
| 241 | { |
| 242 | float value; |
| 243 | const bool is_valid_float = TryParse(str, &value); |
| 244 | if ((is_valid_float && value == 1) || !strcasecmp("true", str.c_str())) |
| 245 | *output = true; |
| 246 | else if ((is_valid_float && value == 0) || !strcasecmp("false", str.c_str())) |
| 247 | *output = false; |
| 248 | else |
| 249 | return false; |
| 250 | |
| 251 | return true; |
| 252 | } |
| 253 | |
| 254 | std::string ValueToString(u16 value) |
| 255 | { |
| 256 | return fmt::format("0x{:04x}", value); |
| 257 | } |
| 258 | |
| 259 | std::string ValueToString(u32 value) |
| 260 | { |
| 261 | return fmt::format("0x{:08x}", value); |
| 262 | } |
| 263 | |
| 264 | std::string ValueToString(u64 value) |
| 265 | { |
| 266 | return fmt::format("0x{:016x}", value); |
| 267 | } |
| 268 | |
| 269 | std::string ValueToString(float value) |
| 270 | { |
| 271 | return fmt::format("{:#}", value); |
| 272 | } |
| 273 | |
| 274 | std::string ValueToString(double value) |
| 275 | { |
| 276 | return fmt::format("{:#}", value); |
| 277 | } |
| 278 | |
| 279 | std::string ValueToString(int value) |
| 280 | { |
| 281 | return std::to_string(value); |
| 282 | } |
| 283 | |
| 284 | std::string ValueToString(s64 value) |
| 285 | { |
| 286 | return std::to_string(value); |
| 287 | } |
| 288 | |
| 289 | std::string ValueToString(bool value) |
| 290 | { |
| 291 | return value ? "True" : "False"; |
| 292 | } |
| 293 | |
| 294 | bool SplitPath(std::string_view full_path, std::string* path, std::string* filename, |
| 295 | std::string* extension) |
| 296 | { |
| 297 | if (full_path.empty()) |
| 298 | return false; |
| 299 | |
| 300 | size_t dir_end = full_path.find_last_of( |
| 301 | // Windows needs the : included for something like just "C:" to be considered a directory |
| 302 | #ifdef _WIN32 |
| 303 | "/:" |
| 304 | #else |
| 305 | '/' |
| 306 | #endif |
| 307 | ); |
| 308 | if (std::string::npos == dir_end) |
| 309 | dir_end = 0; |
| 310 | else |
| 311 | dir_end += 1; |
| 312 | |
| 313 | size_t fname_end = full_path.rfind('.'); |
| 314 | if (fname_end < dir_end || std::string::npos == fname_end) |
| 315 | fname_end = full_path.size(); |
| 316 | |
| 317 | if (path) |
| 318 | *path = full_path.substr(0, dir_end); |
| 319 | |
| 320 | if (filename) |
| 321 | *filename = full_path.substr(dir_end, fname_end - dir_end); |
| 322 | |
| 323 | if (extension) |
| 324 | *extension = full_path.substr(fname_end); |
| 325 | |
| 326 | return true; |
| 327 | } |
| 328 | |
| 329 | void UnifyPathSeparators(std::string& path) |
| 330 | { |
| 331 | #ifdef _WIN32 |
| 332 | for (char& c : path) |
| 333 | { |
| 334 | if (c == '\\') |
| 335 | c = '/'; |
| 336 | } |
| 337 | #endif |
| 338 | } |
| 339 | |
| 340 | std::string WithUnifiedPathSeparators(std::string path) |
| 341 | { |
| 342 | UnifyPathSeparators(path); |
| 343 | return path; |
| 344 | } |
| 345 | |
| 346 | std::string PathToFileName(std::string_view path) |
| 347 | { |
| 348 | std::string file_name; |
| 349 | std::string extension; |
| 350 | SplitPath(path, nullptr, &file_name, &extension); |
| 351 | return file_name + extension; |
| 352 | } |
| 353 | |
| 354 | std::vector<std::string> SplitString(const std::string& str, const char delim) |
| 355 | { |
| 356 | std::istringstream iss(str); |
| 357 | std::vector<std::string> output(1); |
| 358 | |
| 359 | while (std::getline(iss, *output.rbegin(), delim)) |
| 360 | output.push_back(""); |
| 361 | |
| 362 | output.pop_back(); |
| 363 | return output; |
| 364 | } |
| 365 | |
| 366 | std::string ReplaceAll(std::string result, std::string_view src, std::string_view dest) |
| 367 | { |
| 368 | size_t pos = 0; |
| 369 | |
| 370 | if (src == dest) |
| 371 | return result; |
| 372 | |
| 373 | while ((pos = result.find(src, pos)) != std::string::npos) |
| 374 | { |
| 375 | result.replace(pos, src.size(), dest); |
| 376 | pos += dest.length(); |
| 377 | } |
| 378 | |
| 379 | return result; |
| 380 | } |
| 381 | |
| 382 | void StringPopBackIf(std::string* s, char c) |
| 383 | { |
| 384 | if (!s->empty() && s->back() == c) |
| 385 | s->pop_back(); |
| 386 | } |
| 387 | |
| 388 | size_t StringUTF8CodePointCount(std::string_view str) |
| 389 | { |
| 390 | return str.size() - std::ranges::count_if(str, [](char c) -> bool { return (c & 0xC0) == 0x80; }); |
| 391 | } |
| 392 | |
| 393 | constexpr char32_t UNICODE_REPLACEMENT_CHARACTER = 0xfffd; |
| 394 | constexpr char32_t UNICODE_LAST_CODE_POINT = 0x10ffff; |
| 395 | |
| 396 | constexpr u16 UNICODE_HIGH_SURROGATE = 0xd800; |
| 397 | constexpr u16 UNICODE_LOW_SURROGATE = 0xdc00; |
| 398 | |
| 399 | constexpr u16 SURROGATE_VALUE_MASK = 0x3ffu; |
| 400 | |
| 401 | static constexpr bool IsSurrogateCodePoint(char32_t code_point) |
| 402 | { |
| 403 | return (code_point & 0xf800u) == UNICODE_HIGH_SURROGATE; |
| 404 | } |
| 405 | |
| 406 | template <std::integral CharType> |
| 407 | requires(sizeof(CharType) == 1) |
| 408 | class UTF8Decoder |
| 409 | { |
| 410 | public: |
| 411 | constexpr explicit UTF8Decoder(std::span<const CharType> chars) |
| 412 | : m_ptr{chars.data()}, m_end_ptr{m_ptr + chars.size()} |
| 413 | { |
| 414 | } |
| 415 | |
| 416 | auto RemainingCodeUnits() const { return m_end_ptr - m_ptr; } |
| 417 | |
| 418 | constexpr char32_t operator()() |
| 419 | { |
| 420 | assert(RemainingCodeUnits() > 0); |
| 421 | |
| 422 | const u8 first_code_unit = *m_ptr; |
| 423 | ++m_ptr; |
| 424 | |
| 425 | switch (std::countl_one(first_code_unit)) |
| 426 | { |
| 427 | case 0: // ASCII. |
| 428 | return first_code_unit; |
| 429 | case 2: |
| 430 | return FinishReadingSequence<2, 0x80>(first_code_unit); |
| 431 | case 3: |
| 432 | { |
| 433 | const u32 code_point = FinishReadingSequence<3, 0x800>(first_code_unit); |
| 434 | if (!IsSurrogateCodePoint(code_point)) |
| 435 | return code_point; |
| 436 | break; |
| 437 | } |
| 438 | case 4: |
| 439 | { |
| 440 | const u32 code_point = FinishReadingSequence<4, 0x10000>(first_code_unit); |
| 441 | if (code_point <= UNICODE_LAST_CODE_POINT) |
| 442 | return code_point; |
| 443 | break; |
| 444 | } |
| 445 | default: |
| 446 | break; |
| 447 | } |
| 448 | |
| 449 | return UNICODE_REPLACEMENT_CHARACTER; |
| 450 | } |
| 451 | |
| 452 | private: |
| 453 | template <u32 ByteCount, u32 FirstValidCodePoint> |
| 454 | constexpr u32 FinishReadingSequence(u8 first_code_unit) |
| 455 | { |
| 456 | // Remove the leading one bits. |
| 457 | u32 code_point = first_code_unit & (0x7fu >> ByteCount); |
| 458 | |
| 459 | for (u32 byte_count = ByteCount - 1; byte_count != 0; --byte_count) |
| 460 | { |
| 461 | if (RemainingCodeUnits() == 0) |
| 462 | return UNICODE_REPLACEMENT_CHARACTER; |
| 463 | |
| 464 | const auto code_unit = u8(*m_ptr); |
| 465 | |
| 466 | if (!IsContinuationByte(code_unit)) |
| 467 | return UNICODE_REPLACEMENT_CHARACTER; |
| 468 | |
| 469 | ++m_ptr; |
| 470 | |
| 471 | code_point = (code_point << 6u) | (code_unit & 0x3fu); |
| 472 | } |
| 473 | |
| 474 | // Overlong encoding. |
| 475 | if (code_point < FirstValidCodePoint) |
| 476 | return UNICODE_REPLACEMENT_CHARACTER; |
| 477 | |
| 478 | return code_point; |
| 479 | } |
| 480 | |
| 481 | static constexpr bool IsContinuationByte(u8 code_unit) { return std::countl_one(code_unit) == 1; } |
| 482 | |
| 483 | const CharType* m_ptr; |
| 484 | const CharType* const m_end_ptr; |
| 485 | }; |
| 486 | |
| 487 | class UTF8Encoder |
| 488 | { |
| 489 | public: |
| 490 | static constexpr u32 GetMaxUnitsPerCodePoint() { return 4; } |
| 491 | |
| 492 | // `ptr` should point to at least 4 bytes. |
| 493 | // Returns the number of written code units (bytes). |
| 494 | template <std::integral CharType> |
| 495 | requires(sizeof(CharType) == 1) |
| 496 | constexpr u32 operator()(char32_t code_point, CharType* ptr) |
| 497 | { |
| 498 | // ASCII. |
| 499 | if (code_point < 0x80u) |
| 500 | { |
| 501 | *ptr = u8(code_point); |
| 502 | return 1; |
| 503 | } |
| 504 | |
| 505 | if (code_point < 0x800u) |
| 506 | return WriteSequence<2>(code_point, ptr); |
| 507 | |
| 508 | if (code_point < 0x10000u) |
| 509 | return WriteSequence<3>(code_point, ptr); |
| 510 | |
| 511 | if (code_point <= UNICODE_LAST_CODE_POINT) |
| 512 | return WriteSequence<4>(code_point, ptr); |
| 513 | |
| 514 | return (*this)(UNICODE_REPLACEMENT_CHARACTER, ptr); |
| 515 | } |
| 516 | |
| 517 | private: |
| 518 | template <u32 ByteCount> |
| 519 | static constexpr u32 WriteSequence(u32 code_point, auto* ptr) |
| 520 | { |
| 521 | *ptr = u8((0xf0u << (4 - ByteCount)) | (code_point >> (6 * (ByteCount - 1)))); |
| 522 | |
| 523 | for (u32 i = ByteCount - 1; i != 0; --i) |
| 524 | { |
| 525 | ptr[i] = u8(0x80u | (code_point & 0x3fu)); |
| 526 | code_point >>= 6; |
| 527 | } |
| 528 | |
| 529 | return ByteCount; |
| 530 | } |
| 531 | }; |
| 532 | |
| 533 | template <std::integral CharType> |
| 534 | requires(sizeof(CharType) == 2) |
| 535 | class UTF16Decoder |
| 536 | { |
| 537 | public: |
| 538 | constexpr explicit UTF16Decoder(std::span<const CharType> chars) |
| 539 | : m_ptr{chars.data()}, m_end_ptr{m_ptr + chars.size()} |
| 540 | { |
| 541 | } |
| 542 | |
| 543 | auto RemainingCodeUnits() const { return m_end_ptr - m_ptr; } |
| 544 | |
| 545 | constexpr char32_t operator()() |
| 546 | { |
| 547 | assert(RemainingCodeUnits() > 0); |
| 548 | |
| 549 | const u16 first_code_unit = *m_ptr; |
| 550 | ++m_ptr; |
| 551 | |
| 552 | // Single code unit. |
| 553 | if (!IsSurrogateCodePoint(first_code_unit)) |
| 554 | return first_code_unit; |
| 555 | |
| 556 | // Unexpected low surrogate. |
| 557 | if (first_code_unit >= UNICODE_LOW_SURROGATE) |
| 558 | return UNICODE_REPLACEMENT_CHARACTER; |
| 559 | |
| 560 | // High surrogate at end of data. |
| 561 | if (RemainingCodeUnits() == 0) |
| 562 | return UNICODE_REPLACEMENT_CHARACTER; |
| 563 | |
| 564 | const u16 second_code_unit = *m_ptr; |
| 565 | |
| 566 | // High surrogate not followed by low surrogate. |
| 567 | if ((second_code_unit & u16(~SURROGATE_VALUE_MASK)) != UNICODE_LOW_SURROGATE) |
| 568 | return UNICODE_REPLACEMENT_CHARACTER; |
| 569 | |
| 570 | ++m_ptr; |
| 571 | |
| 572 | // We have a surrogate pair. |
| 573 | return (u32(first_code_unit & SURROGATE_VALUE_MASK) << 10u) + |
| 574 | u32(second_code_unit & SURROGATE_VALUE_MASK) + 0x10000u; |
| 575 | } |
| 576 | |
| 577 | private: |
| 578 | const CharType* m_ptr; |
| 579 | const CharType* const m_end_ptr; |
| 580 | }; |
| 581 | |
| 582 | class UTF16Encoder |
| 583 | { |
| 584 | public: |
| 585 | static constexpr u32 GetMaxUnitsPerCodePoint() { return 2; } |
| 586 | |
| 587 | // `ptr` should point to at least 2 code units. |
| 588 | // Returns the number of written code units. |
| 589 | template <std::integral CharType> |
| 590 | requires(sizeof(CharType) == 2) |
| 591 | constexpr u32 operator()(char32_t code_point, CharType* ptr) |
| 592 | { |
| 593 | if (code_point < 0x10000u) |
| 594 | { |
| 595 | *ptr = u16(code_point); |
| 596 | return 1; |
| 597 | } |
| 598 | |
| 599 | if (code_point > UNICODE_LAST_CODE_POINT) |
| 600 | return (*this)(UNICODE_REPLACEMENT_CHARACTER, ptr); |
| 601 | |
| 602 | // Create surrogate pair. |
| 603 | const u32 value = code_point - 0x10000; |
| 604 | ptr[0] = u16(((value >> 10u) & SURROGATE_VALUE_MASK) | UNICODE_HIGH_SURROGATE); |
| 605 | ptr[1] = u16((value & SURROGATE_VALUE_MASK) | UNICODE_LOW_SURROGATE); |
| 606 | return 2; |
| 607 | } |
| 608 | }; |
| 609 | |
| 610 | template <typename Decoder, typename Encoder, typename ResultCharType, typename InputCharType> |
| 611 | static constexpr std::basic_string<ResultCharType> |
| 612 | ReEncodeString(std::basic_string_view<InputCharType> input) |
| 613 | { |
| 614 | Encoder encoder; |
| 615 | |
| 616 | const auto buffer_size = input.size() * encoder.GetMaxUnitsPerCodePoint(); |
| 617 | |
| 618 | // Handle the unlikely case of integer overflow in the buffer size. |
| 619 | const auto input_size = buffer_size / encoder.GetMaxUnitsPerCodePoint(); |
| 620 | |
| 621 | Decoder decoder{std::span{input}.first(input_size)}; |
| 622 | |
| 623 | std::basic_string<ResultCharType> result; |
| 624 | result.resize_and_overwrite(buffer_size, [&](ResultCharType* buf, std::size_t) { |
| 625 | auto* position = buf; |
| 626 | |
| 627 | while (decoder.RemainingCodeUnits() != 0) |
| 628 | position += encoder(decoder(), position); |
| 629 | |
| 630 | return position - buf; |
| 631 | }); |
| 632 | |
| 633 | return result; |
| 634 | } |
| 635 | |
| 636 | #ifdef _WIN32 |
| 637 | |
| 638 | static std::wstring CPToUTF16(u32 code_page, std::string_view input) |
| 639 | { |
| 640 | auto const size = |
| 641 | MultiByteToWideChar(code_page, 0, input.data(), static_cast<int>(input.size()), nullptr, 0); |
| 642 | |
| 643 | std::wstring output; |
| 644 | output.resize(size); |
| 645 | |
| 646 | if (size == 0 || |
| 647 | size != MultiByteToWideChar(code_page, 0, input.data(), static_cast<int>(input.size()), |
| 648 | &output[0], static_cast<int>(output.size()))) |
| 649 | { |
| 650 | output.clear(); |
| 651 | } |
| 652 | |
| 653 | return output; |
| 654 | } |
| 655 | |
| 656 | static std::string UTF16ToCP(u32 code_page, std::wstring_view input) |
| 657 | { |
| 658 | if (input.empty()) |
| 659 | return {}; |
| 660 | |
| 661 | // "If cchWideChar [input buffer size] is set to 0, the function fails." -MSDN |
| 662 | auto const size = WideCharToMultiByte(code_page, 0, input.data(), static_cast<int>(input.size()), |
| 663 | nullptr, 0, nullptr, nullptr); |
| 664 | |
| 665 | std::string output(size, '\0'); |
| 666 | |
| 667 | if (size != WideCharToMultiByte(code_page, 0, input.data(), static_cast<int>(input.size()), |
| 668 | output.data(), static_cast<int>(output.size()), nullptr, nullptr)) |
| 669 | { |
| 670 | const DWORD error_code = GetLastError(); |
| 671 | ERROR_LOG_FMT(COMMON, "WideCharToMultiByte Error in String '{}': {}", WStringToUTF8(input), |
| 672 | error_code); |
| 673 | return {}; |
| 674 | } |
| 675 | |
| 676 | return output; |
| 677 | } |
| 678 | |
| 679 | std::wstring UTF8ToWString(std::string_view input) |
| 680 | { |
| 681 | return CPToUTF16(CP_UTF8, input); |
| 682 | } |
| 683 | |
| 684 | std::string WStringToUTF8(std::wstring_view input) |
| 685 | { |
| 686 | return UTF16ToCP(CP_UTF8, input); |
| 687 | } |
| 688 | |
| 689 | std::string SHIFTJISToUTF8(std::string_view input) |
| 690 | { |
| 691 | return WStringToUTF8(CPToUTF16(CODEPAGE_SHIFT_JIS, input)); |
| 692 | } |
| 693 | |
| 694 | std::string UTF8ToSHIFTJIS(std::string_view input) |
| 695 | { |
| 696 | return UTF16ToCP(CODEPAGE_SHIFT_JIS, UTF8ToWString(input)); |
| 697 | } |
| 698 | |
| 699 | std::string CP1252ToUTF8(std::string_view input) |
| 700 | { |
| 701 | return WStringToUTF8(CPToUTF16(CODEPAGE_WINDOWS_1252, input)); |
| 702 | } |
| 703 | |
| 704 | std::string UTF16BEToUTF8(const char16_t* str, size_t max_size) |
| 705 | { |
| 706 | const char16_t* str_end = std::find(str, str + max_size, '\0'); |
| 707 | std::wstring result(static_cast<size_t>(str_end - str), '\0'); |
| 708 | std::transform(str, str_end, result.begin(), static_cast<u16 (&)(u16)>(Common::swap16)); |
| 709 | return WStringToUTF8(result); |
| 710 | } |
| 711 | |
| 712 | #else |
| 713 | |
| 714 | template <typename T> |
| 715 | static std::string CodeTo(const char* tocode, const char* fromcode, std::basic_string_view<T> input) |
| 716 | { |
| 717 | std::string result; |
| 718 | |
| 719 | auto* const conv_desc = iconv_open(tocode, fromcode); |
| 720 | if ((iconv_t)-1 == conv_desc) |
| 721 | { |
| 722 | ERROR_LOG_FMT(COMMON, "Iconv initialization failure [{}]: {}", fromcode, |
| 723 | Common::LastStrerrorString()); |
| 724 | } |
| 725 | else |
| 726 | { |
| 727 | size_t const in_bytes = sizeof(T) * input.size(); |
| 728 | size_t const out_buffer_size = 4 * in_bytes; |
| 729 | |
| 730 | std::string out_buffer; |
| 731 | out_buffer.resize(out_buffer_size); |
| 732 | |
| 733 | auto* src_buffer = input.data(); |
| 734 | size_t src_bytes = in_bytes; |
| 735 | auto* dst_buffer = out_buffer.data(); |
| 736 | size_t dst_bytes = out_buffer.size(); |
| 737 | |
| 738 | while (src_bytes != 0) |
| 739 | { |
| 740 | size_t const iconv_result = |
| 741 | iconv(conv_desc, const_cast<char**>(reinterpret_cast<const char**>(&src_buffer)), |
| 742 | &src_bytes, &dst_buffer, &dst_bytes); |
| 743 | if ((size_t)-1 == iconv_result) |
| 744 | { |
| 745 | if (EILSEQ == errno || EINVAL == errno) |
| 746 | { |
| 747 | // Try to skip the bad character |
| 748 | if (src_bytes != 0) |
| 749 | { |
| 750 | --src_bytes; |
| 751 | ++src_buffer; |
| 752 | } |
| 753 | } |
| 754 | else |
| 755 | { |
| 756 | ERROR_LOG_FMT(COMMON, "iconv failure [{}]: {}", fromcode, Common::LastStrerrorString()); |
| 757 | break; |
| 758 | } |
| 759 | } |
| 760 | } |
| 761 | |
| 762 | out_buffer.resize(out_buffer_size - dst_bytes); |
| 763 | out_buffer.swap(result); |
| 764 | |
| 765 | iconv_close(conv_desc); |
| 766 | } |
| 767 | |
| 768 | return result; |
| 769 | } |
| 770 | |
| 771 | template <typename T> |
| 772 | static std::string CodeToUTF8(const char* fromcode, std::basic_string_view<T> input) |
| 773 | { |
| 774 | return CodeTo("UTF-8", fromcode, input); |
| 775 | } |
| 776 | |
| 777 | std::string CP1252ToUTF8(std::string_view input) |
| 778 | { |
| 779 | // return CodeToUTF8("CP1252//TRANSLIT", input); |
| 780 | // return CodeToUTF8("CP1252//IGNORE", input); |
| 781 | return CodeToUTF8("CP1252", input); |
| 782 | } |
| 783 | |
| 784 | std::string SHIFTJISToUTF8(std::string_view input) |
| 785 | { |
| 786 | // return CodeToUTF8("CP932", input); |
| 787 | return CodeToUTF8("SJIS", input); |
| 788 | } |
| 789 | |
| 790 | std::string UTF8ToSHIFTJIS(std::string_view input) |
| 791 | { |
| 792 | return CodeTo("SJIS", "UTF-8", input); |
| 793 | } |
| 794 | |
| 795 | std::string WStringToUTF8(std::wstring_view input) |
| 796 | { |
| 797 | // Note: Without LE iconv expects a BOM. |
| 798 | // The "WCHAR_T" code would be appropriate, but it's apparently not in every iconv implementation. |
| 799 | return CodeToUTF8((sizeof(wchar_t) == 2) ? "UTF-16LE" : "UTF-32LE", input); |
| 800 | } |
| 801 | |
| 802 | std::string UTF16BEToUTF8(const char16_t* str, size_t max_size) |
| 803 | { |
| 804 | const char16_t* str_end = std::find(str, str + max_size, '\0'); |
| 805 | return CodeToUTF8("UTF-16BE", std::u16string_view(str, static_cast<size_t>(str_end - str))); |
| 806 | } |
| 807 | |
| 808 | #endif |
| 809 | |
| 810 | std::string UTF16ToUTF8(std::u16string_view input) |
| 811 | { |
| 812 | return ReEncodeString<UTF16Decoder<char16_t>, UTF8Encoder, char>(input); |
| 813 | } |
| 814 | |
| 815 | std::u16string UTF8ToUTF16(std::string_view input) |
| 816 | { |
| 817 | return ReEncodeString<UTF8Decoder<char>, UTF16Encoder, char16_t>(input); |
| 818 | } |
| 819 | |
| 820 | // This is a replacement for path::u8path, which is deprecated starting with C++20. |
| 821 | std::filesystem::path StringToPath(std::string_view path) |
| 822 | { |
| 823 | #ifdef _MSC_VER |
| 824 | return std::filesystem::path(UTF8ToWString(path)); |
| 825 | #else |
| 826 | return std::filesystem::path(path); |
| 827 | #endif |
| 828 | } |
| 829 | |
| 830 | // This is a replacement for path::u8string that always has the return type std::string. |
| 831 | // path::u8string returns std::u8string starting with C++20, which is annoying to convert. |
| 832 | std::string PathToString(const std::filesystem::path& path) |
| 833 | { |
| 834 | #ifdef _MSC_VER |
| 835 | return WStringToUTF8(path.native()); |
| 836 | #else |
| 837 | return path.native(); |
| 838 | #endif |
| 839 | } |
| 840 | |
| 841 | namespace Common |
| 842 | { |
| 843 | #ifdef _WIN32 |
| 844 | std::vector<std::string> CommandLineToUtf8Argv(const wchar_t* command_line) |
| 845 | { |
| 846 | int nargs; |
| 847 | LPWSTR* tokenized = CommandLineToArgvW(command_line, &nargs); |
| 848 | if (!tokenized) |
| 849 | return {}; |
| 850 | |
| 851 | std::vector<std::string> argv(nargs); |
| 852 | for (size_t i = 0; i < nargs; ++i) |
| 853 | { |
| 854 | argv[i] = WStringToUTF8(tokenized[i]); |
| 855 | } |
| 856 | |
| 857 | LocalFree(tokenized); |
| 858 | return argv; |
| 859 | } |
| 860 | #endif |
| 861 | |
| 862 | std::string GetEscapedHtml(std::string html) |
| 863 | { |
| 864 | static constexpr std::array<std::array<const char*, 2>, 5> replacements{{ |
| 865 | // Escape ampersand first to avoid escaping the ampersands in other replacements |
| 866 | {{"&", "&"}}, |
| 867 | {{"<", "<"}}, |
| 868 | {{">", ">"}}, |
| 869 | {{"\"", """}}, |
| 870 | {{"'", "'"}}, |
| 871 | }}; |
| 872 | |
| 873 | for (const auto& [unescaped, escaped] : replacements) |
| 874 | { |
| 875 | html = ReplaceAll(html, unescaped, escaped); |
| 876 | } |
| 877 | return html; |
| 878 | } |
| 879 | |
| 880 | void ToLower(std::string* str) |
| 881 | { |
| 882 | std::ranges::transform(*str, str->begin(), static_cast<char (&)(char)>(Common::ToLower)); |
| 883 | } |
| 884 | |
| 885 | void ToUpper(std::string* str) |
| 886 | { |
| 887 | std::ranges::transform(*str, str->begin(), static_cast<char (&)(char)>(Common::ToUpper)); |
| 888 | } |
| 889 | |
| 890 | bool CaseInsensitiveEquals(std::string_view a, std::string_view b) |
| 891 | { |
| 892 | return std::ranges::equal( |
| 893 | a, b, [](char ca, char cb) { return Common::ToLower(ca) == Common::ToLower(cb); }); |
| 894 | } |
| 895 | |
| 896 | bool CaseInsensitiveContains(std::string_view haystack, std::string_view needle) |
| 897 | { |
| 898 | if (needle.empty()) |
| 899 | return true; |
| 900 | |
| 901 | for (size_t i = 0; i + needle.size() <= haystack.size(); ++i) |
| 902 | { |
| 903 | if (std::ranges::equal(needle, haystack.substr(i, needle.size()), |
| 904 | [](char a, char b) { return Common::ToLower(a) == Common::ToLower(b); })) |
| 905 | { |
| 906 | return true; |
| 907 | } |
| 908 | } |
| 909 | return false; |
| 910 | } |
| 911 | |
| 912 | bool CaseInsensitiveLess::operator()(std::string_view a, std::string_view b) const |
| 913 | { |
| 914 | return std::ranges::lexicographical_compare( |
| 915 | a, b, [](char ca, char cb) { return Common::ToLower(ca) < Common::ToLower(cb); }); |
| 916 | } |
| 917 | |
| 918 | std::string BytesToHexString(std::span<const u8> bytes) |
| 919 | { |
| 920 | return fmt::format("{:02x}", fmt::join(bytes, "")); |
| 921 | } |
| 922 | } // namespace Common |