string_util.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. // Copyright 2013 Dolphin Emulator Project / 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <cctype>
  5. #include <cerrno>
  6. #include <cstdio>
  7. #include <cstdlib>
  8. #include <cstring>
  9. #include <boost/range/algorithm/transform.hpp>
  10. #include "common/common_paths.h"
  11. #include "common/logging/log.h"
  12. #include "common/string_util.h"
  13. #ifdef _WIN32
  14. #include <codecvt>
  15. #include <windows.h>
  16. #include "common/common_funcs.h"
  17. #else
  18. #include <iconv.h>
  19. #endif
  20. namespace Common {
  21. /// Make a string lowercase
  22. std::string ToLower(std::string str) {
  23. boost::transform(str, str.begin(), ::tolower);
  24. return str;
  25. }
  26. /// Make a string uppercase
  27. std::string ToUpper(std::string str) {
  28. boost::transform(str, str.begin(), ::toupper);
  29. return str;
  30. }
  31. // faster than sscanf
  32. bool AsciiToHex(const char* _szValue, u32& result) {
  33. char* endptr = nullptr;
  34. const u32 value = strtoul(_szValue, &endptr, 16);
  35. if (!endptr || *endptr)
  36. return false;
  37. result = value;
  38. return true;
  39. }
  40. bool CharArrayFromFormatV(char* out, int outsize, const char* format, va_list args) {
  41. int writtenCount;
  42. #ifdef _MSC_VER
  43. // You would think *printf are simple, right? Iterate on each character,
  44. // if it's a format specifier handle it properly, etc.
  45. //
  46. // Nooooo. Not according to the C standard.
  47. //
  48. // According to the C99 standard (7.19.6.1 "The fprintf function")
  49. // The format shall be a multibyte character sequence
  50. //
  51. // Because some character encodings might have '%' signs in the middle of
  52. // a multibyte sequence (SJIS for example only specifies that the first
  53. // byte of a 2 byte sequence is "high", the second byte can be anything),
  54. // printf functions have to decode the multibyte sequences and try their
  55. // best to not screw up.
  56. //
  57. // Unfortunately, on Windows, the locale for most languages is not UTF-8
  58. // as we would need. Notably, for zh_TW, Windows chooses EUC-CN as the
  59. // locale, and completely fails when trying to decode UTF-8 as EUC-CN.
  60. //
  61. // On the other hand, the fix is simple: because we use UTF-8, no such
  62. // multibyte handling is required as we can simply assume that no '%' char
  63. // will be present in the middle of a multibyte sequence.
  64. //
  65. // This is why we lookup an ANSI (cp1252) locale here and use _vsnprintf_l.
  66. static locale_t c_locale = nullptr;
  67. if (!c_locale)
  68. c_locale = _create_locale(LC_ALL, ".1252");
  69. writtenCount = _vsnprintf_l(out, outsize, format, c_locale, args);
  70. #else
  71. writtenCount = vsnprintf(out, outsize, format, args);
  72. #endif
  73. if (writtenCount > 0 && writtenCount < outsize) {
  74. out[writtenCount] = '\0';
  75. return true;
  76. } else {
  77. out[outsize - 1] = '\0';
  78. return false;
  79. }
  80. }
  81. std::string StringFromFormat(const char* format, ...) {
  82. va_list args;
  83. char* buf = nullptr;
  84. #ifdef _WIN32
  85. int required = 0;
  86. va_start(args, format);
  87. required = _vscprintf(format, args);
  88. buf = new char[required + 1];
  89. CharArrayFromFormatV(buf, required + 1, format, args);
  90. va_end(args);
  91. std::string temp = buf;
  92. delete[] buf;
  93. #else
  94. va_start(args, format);
  95. if (vasprintf(&buf, format, args) < 0)
  96. LOG_ERROR(Common, "Unable to allocate memory for string");
  97. va_end(args);
  98. std::string temp = buf;
  99. free(buf);
  100. #endif
  101. return temp;
  102. }
  103. // For Debugging. Read out an u8 array.
  104. std::string ArrayToString(const u8* data, size_t size, int line_len, bool spaces) {
  105. std::ostringstream oss;
  106. oss << std::setfill('0') << std::hex;
  107. for (int line = 0; size; ++data, --size) {
  108. oss << std::setw(2) << (int)*data;
  109. if (line_len == ++line) {
  110. oss << '\n';
  111. line = 0;
  112. } else if (spaces)
  113. oss << ' ';
  114. }
  115. return oss.str();
  116. }
  117. // Turns " hej " into "hej". Also handles tabs.
  118. std::string StripSpaces(const std::string& str) {
  119. const size_t s = str.find_first_not_of(" \t\r\n");
  120. if (str.npos != s)
  121. return str.substr(s, str.find_last_not_of(" \t\r\n") - s + 1);
  122. else
  123. return "";
  124. }
  125. // "\"hello\"" is turned to "hello"
  126. // This one assumes that the string has already been space stripped in both
  127. // ends, as done by StripSpaces above, for example.
  128. std::string StripQuotes(const std::string& s) {
  129. if (s.size() && '\"' == s[0] && '\"' == *s.rbegin())
  130. return s.substr(1, s.size() - 2);
  131. else
  132. return s;
  133. }
  134. bool TryParse(const std::string& str, u32* const output) {
  135. char* endptr = nullptr;
  136. // Reset errno to a value other than ERANGE
  137. errno = 0;
  138. unsigned long value = strtoul(str.c_str(), &endptr, 0);
  139. if (!endptr || *endptr)
  140. return false;
  141. if (errno == ERANGE)
  142. return false;
  143. #if ULONG_MAX > UINT_MAX
  144. if (value >= 0x100000000ull && value <= 0xFFFFFFFF00000000ull)
  145. return false;
  146. #endif
  147. *output = static_cast<u32>(value);
  148. return true;
  149. }
  150. bool TryParse(const std::string& str, bool* const output) {
  151. if ("1" == str || "true" == ToLower(str))
  152. *output = true;
  153. else if ("0" == str || "false" == ToLower(str))
  154. *output = false;
  155. else
  156. return false;
  157. return true;
  158. }
  159. std::string StringFromBool(bool value) {
  160. return value ? "True" : "False";
  161. }
  162. bool SplitPath(const std::string& full_path, std::string* _pPath, std::string* _pFilename,
  163. std::string* _pExtension) {
  164. if (full_path.empty())
  165. return false;
  166. size_t dir_end = full_path.find_last_of("/"
  167. // windows needs the : included for something like just "C:" to be considered a directory
  168. #ifdef _WIN32
  169. ":"
  170. #endif
  171. );
  172. if (std::string::npos == dir_end)
  173. dir_end = 0;
  174. else
  175. dir_end += 1;
  176. size_t fname_end = full_path.rfind('.');
  177. if (fname_end < dir_end || std::string::npos == fname_end)
  178. fname_end = full_path.size();
  179. if (_pPath)
  180. *_pPath = full_path.substr(0, dir_end);
  181. if (_pFilename)
  182. *_pFilename = full_path.substr(dir_end, fname_end - dir_end);
  183. if (_pExtension)
  184. *_pExtension = full_path.substr(fname_end);
  185. return true;
  186. }
  187. void BuildCompleteFilename(std::string& _CompleteFilename, const std::string& _Path,
  188. const std::string& _Filename) {
  189. _CompleteFilename = _Path;
  190. // check for seperator
  191. if (DIR_SEP_CHR != *_CompleteFilename.rbegin())
  192. _CompleteFilename += DIR_SEP_CHR;
  193. // add the filename
  194. _CompleteFilename += _Filename;
  195. }
  196. void SplitString(const std::string& str, const char delim, std::vector<std::string>& output) {
  197. std::istringstream iss(str);
  198. output.resize(1);
  199. while (std::getline(iss, *output.rbegin(), delim))
  200. output.push_back("");
  201. output.pop_back();
  202. }
  203. std::string TabsToSpaces(int tab_size, const std::string& in) {
  204. const std::string spaces(tab_size, ' ');
  205. std::string out(in);
  206. size_t i = 0;
  207. while (out.npos != (i = out.find('\t')))
  208. out.replace(i, 1, spaces);
  209. return out;
  210. }
  211. std::string ReplaceAll(std::string result, const std::string& src, const std::string& dest) {
  212. size_t pos = 0;
  213. if (src == dest)
  214. return result;
  215. while ((pos = result.find(src, pos)) != std::string::npos) {
  216. result.replace(pos, src.size(), dest);
  217. pos += dest.length();
  218. }
  219. return result;
  220. }
  221. #ifdef _WIN32
  222. std::string UTF16ToUTF8(const std::u16string& input) {
  223. #if _MSC_VER >= 1900
  224. // Workaround for missing char16_t/char32_t instantiations in MSVC2015
  225. std::wstring_convert<std::codecvt_utf8_utf16<__int16>, __int16> convert;
  226. std::basic_string<__int16> tmp_buffer(input.cbegin(), input.cend());
  227. return convert.to_bytes(tmp_buffer);
  228. #else
  229. std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
  230. return convert.to_bytes(input);
  231. #endif
  232. }
  233. std::u16string UTF8ToUTF16(const std::string& input) {
  234. #if _MSC_VER >= 1900
  235. // Workaround for missing char16_t/char32_t instantiations in MSVC2015
  236. std::wstring_convert<std::codecvt_utf8_utf16<__int16>, __int16> convert;
  237. auto tmp_buffer = convert.from_bytes(input);
  238. return std::u16string(tmp_buffer.cbegin(), tmp_buffer.cend());
  239. #else
  240. std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
  241. return convert.from_bytes(input);
  242. #endif
  243. }
  244. static std::wstring CPToUTF16(u32 code_page, const std::string& input) {
  245. auto const size =
  246. MultiByteToWideChar(code_page, 0, input.data(), static_cast<int>(input.size()), nullptr, 0);
  247. std::wstring output;
  248. output.resize(size);
  249. if (size == 0 ||
  250. size != MultiByteToWideChar(code_page, 0, input.data(), static_cast<int>(input.size()),
  251. &output[0], static_cast<int>(output.size())))
  252. output.clear();
  253. return output;
  254. }
  255. std::string UTF16ToUTF8(const std::wstring& input) {
  256. auto const size = WideCharToMultiByte(CP_UTF8, 0, input.data(), static_cast<int>(input.size()),
  257. nullptr, 0, nullptr, nullptr);
  258. std::string output;
  259. output.resize(size);
  260. if (size == 0 ||
  261. size != WideCharToMultiByte(CP_UTF8, 0, input.data(), static_cast<int>(input.size()),
  262. &output[0], static_cast<int>(output.size()), nullptr, nullptr))
  263. output.clear();
  264. return output;
  265. }
  266. std::wstring UTF8ToUTF16W(const std::string& input) {
  267. return CPToUTF16(CP_UTF8, input);
  268. }
  269. std::string SHIFTJISToUTF8(const std::string& input) {
  270. return UTF16ToUTF8(CPToUTF16(932, input));
  271. }
  272. std::string CP1252ToUTF8(const std::string& input) {
  273. return UTF16ToUTF8(CPToUTF16(1252, input));
  274. }
  275. #else
  276. template <typename T>
  277. static std::string CodeToUTF8(const char* fromcode, const std::basic_string<T>& input) {
  278. std::string result;
  279. iconv_t const conv_desc = iconv_open("UTF-8", fromcode);
  280. if ((iconv_t)(-1) == conv_desc) {
  281. LOG_ERROR(Common, "Iconv initialization failure [%s]: %s", fromcode, strerror(errno));
  282. iconv_close(conv_desc);
  283. return {};
  284. }
  285. const size_t in_bytes = sizeof(T) * input.size();
  286. // Multiply by 4, which is the max number of bytes to encode a codepoint
  287. const size_t out_buffer_size = 4 * in_bytes;
  288. std::string out_buffer;
  289. out_buffer.resize(out_buffer_size);
  290. auto src_buffer = &input[0];
  291. size_t src_bytes = in_bytes;
  292. auto dst_buffer = &out_buffer[0];
  293. size_t dst_bytes = out_buffer.size();
  294. while (0 != src_bytes) {
  295. size_t const iconv_result =
  296. iconv(conv_desc, (char**)(&src_buffer), &src_bytes, &dst_buffer, &dst_bytes);
  297. if (static_cast<size_t>(-1) == iconv_result) {
  298. if (EILSEQ == errno || EINVAL == errno) {
  299. // Try to skip the bad character
  300. if (0 != src_bytes) {
  301. --src_bytes;
  302. ++src_buffer;
  303. }
  304. } else {
  305. LOG_ERROR(Common, "iconv failure [%s]: %s", fromcode, strerror(errno));
  306. break;
  307. }
  308. }
  309. }
  310. out_buffer.resize(out_buffer_size - dst_bytes);
  311. out_buffer.swap(result);
  312. iconv_close(conv_desc);
  313. return result;
  314. }
  315. std::u16string UTF8ToUTF16(const std::string& input) {
  316. std::u16string result;
  317. iconv_t const conv_desc = iconv_open("UTF-16LE", "UTF-8");
  318. if ((iconv_t)(-1) == conv_desc) {
  319. LOG_ERROR(Common, "Iconv initialization failure [UTF-8]: %s", strerror(errno));
  320. iconv_close(conv_desc);
  321. return {};
  322. }
  323. const size_t in_bytes = sizeof(char) * input.size();
  324. // Multiply by 4, which is the max number of bytes to encode a codepoint
  325. const size_t out_buffer_size = 4 * sizeof(char16_t) * in_bytes;
  326. std::u16string out_buffer;
  327. out_buffer.resize(out_buffer_size);
  328. char* src_buffer = const_cast<char*>(&input[0]);
  329. size_t src_bytes = in_bytes;
  330. char* dst_buffer = (char*)(&out_buffer[0]);
  331. size_t dst_bytes = out_buffer.size();
  332. while (0 != src_bytes) {
  333. size_t const iconv_result =
  334. iconv(conv_desc, &src_buffer, &src_bytes, &dst_buffer, &dst_bytes);
  335. if (static_cast<size_t>(-1) == iconv_result) {
  336. if (EILSEQ == errno || EINVAL == errno) {
  337. // Try to skip the bad character
  338. if (0 != src_bytes) {
  339. --src_bytes;
  340. ++src_buffer;
  341. }
  342. } else {
  343. LOG_ERROR(Common, "iconv failure [UTF-8]: %s", strerror(errno));
  344. break;
  345. }
  346. }
  347. }
  348. out_buffer.resize(out_buffer_size - dst_bytes);
  349. out_buffer.swap(result);
  350. iconv_close(conv_desc);
  351. return result;
  352. }
  353. std::string UTF16ToUTF8(const std::u16string& input) {
  354. return CodeToUTF8("UTF-16LE", input);
  355. }
  356. std::string CP1252ToUTF8(const std::string& input) {
  357. // return CodeToUTF8("CP1252//TRANSLIT", input);
  358. // return CodeToUTF8("CP1252//IGNORE", input);
  359. return CodeToUTF8("CP1252", input);
  360. }
  361. std::string SHIFTJISToUTF8(const std::string& input) {
  362. // return CodeToUTF8("CP932", input);
  363. return CodeToUTF8("SJIS", input);
  364. }
  365. #endif
  366. std::string StringFromFixedZeroTerminatedBuffer(const char* buffer, size_t max_len) {
  367. size_t len = 0;
  368. while (len < max_len && buffer[len] != '\0')
  369. ++len;
  370. return std::string(buffer, len);
  371. }
  372. }