string_util.cpp 13 KB

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