string_util.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. // Copyright 2013 Dolphin Emulator Project
  2. // Licensed under GPLv2
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <cstdlib>
  6. #include <cstdio>
  7. #include "common/common.h"
  8. #include "common/common_paths.h"
  9. #include "common/string_util.h"
  10. #ifdef _WIN32
  11. #include <Windows.h>
  12. #else
  13. #include <cerrno>
  14. #include <iconv.h>
  15. #endif
  16. namespace Common {
  17. /// Make a string lowercase
  18. std::string ToLower(std::string str) {
  19. std::transform(str.begin(), str.end(), str.begin(), ::tolower);
  20. return str;
  21. }
  22. /// Make a string uppercase
  23. std::string ToUpper(std::string str) {
  24. std::transform(str.begin(), str.end(), str.begin(), ::toupper);
  25. return str;
  26. }
  27. // faster than sscanf
  28. bool AsciiToHex(const char* _szValue, u32& result)
  29. {
  30. char *endptr = NULL;
  31. const u32 value = strtoul(_szValue, &endptr, 16);
  32. if (!endptr || *endptr)
  33. return false;
  34. result = value;
  35. return true;
  36. }
  37. bool CharArrayFromFormatV(char* out, int outsize, const char* format, va_list args)
  38. {
  39. int writtenCount;
  40. #ifdef _WIN32
  41. // You would think *printf are simple, right? Iterate on each character,
  42. // if it's a format specifier handle it properly, etc.
  43. //
  44. // Nooooo. Not according to the C standard.
  45. //
  46. // According to the C99 standard (7.19.6.1 "The fprintf function")
  47. // The format shall be a multibyte character sequence
  48. //
  49. // Because some character encodings might have '%' signs in the middle of
  50. // a multibyte sequence (SJIS for example only specifies that the first
  51. // byte of a 2 byte sequence is "high", the second byte can be anything),
  52. // printf functions have to decode the multibyte sequences and try their
  53. // best to not screw up.
  54. //
  55. // Unfortunately, on Windows, the locale for most languages is not UTF-8
  56. // as we would need. Notably, for zh_TW, Windows chooses EUC-CN as the
  57. // locale, and completely fails when trying to decode UTF-8 as EUC-CN.
  58. //
  59. // On the other hand, the fix is simple: because we use UTF-8, no such
  60. // multibyte handling is required as we can simply assume that no '%' char
  61. // will be present in the middle of a multibyte sequence.
  62. //
  63. // This is why we lookup an ANSI (cp1252) locale here and use _vsnprintf_l.
  64. static locale_t c_locale = NULL;
  65. if (!c_locale)
  66. c_locale = _create_locale(LC_ALL, ".1252");
  67. writtenCount = _vsnprintf_l(out, outsize, format, c_locale, args);
  68. #else
  69. writtenCount = vsnprintf(out, outsize, format, args);
  70. #endif
  71. if (writtenCount > 0 && writtenCount < outsize)
  72. {
  73. out[writtenCount] = '\0';
  74. return true;
  75. }
  76. else
  77. {
  78. out[outsize - 1] = '\0';
  79. return false;
  80. }
  81. }
  82. std::string StringFromFormat(const char* format, ...)
  83. {
  84. va_list args;
  85. char *buf = NULL;
  86. #ifdef _WIN32
  87. int required = 0;
  88. va_start(args, format);
  89. required = _vscprintf(format, args);
  90. buf = new char[required + 1];
  91. CharArrayFromFormatV(buf, required + 1, format, args);
  92. va_end(args);
  93. std::string temp = buf;
  94. delete[] buf;
  95. #else
  96. va_start(args, format);
  97. if (vasprintf(&buf, format, args) < 0)
  98. ERROR_LOG(COMMON, "Unable to allocate memory for string");
  99. va_end(args);
  100. std::string temp = buf;
  101. free(buf);
  102. #endif
  103. return temp;
  104. }
  105. // For Debugging. Read out an u8 array.
  106. std::string ArrayToString(const u8 *data, u32 size, int line_len, bool spaces)
  107. {
  108. std::ostringstream oss;
  109. oss << std::setfill('0') << std::hex;
  110. for (int line = 0; size; ++data, --size)
  111. {
  112. oss << std::setw(2) << (int)*data;
  113. if (line_len == ++line)
  114. {
  115. oss << '\n';
  116. line = 0;
  117. }
  118. else if (spaces)
  119. oss << ' ';
  120. }
  121. return oss.str();
  122. }
  123. // Turns " hej " into "hej". Also handles tabs.
  124. std::string StripSpaces(const std::string &str)
  125. {
  126. const size_t s = str.find_first_not_of(" \t\r\n");
  127. if (str.npos != s)
  128. return str.substr(s, str.find_last_not_of(" \t\r\n") - s + 1);
  129. else
  130. return "";
  131. }
  132. // "\"hello\"" is turned to "hello"
  133. // This one assumes that the string has already been space stripped in both
  134. // ends, as done by StripSpaces above, for example.
  135. std::string StripQuotes(const std::string& s)
  136. {
  137. if (s.size() && '\"' == s[0] && '\"' == *s.rbegin())
  138. return s.substr(1, s.size() - 2);
  139. else
  140. return s;
  141. }
  142. bool TryParse(const std::string &str, u32 *const output)
  143. {
  144. char *endptr = NULL;
  145. // Reset errno to a value other than ERANGE
  146. errno = 0;
  147. unsigned long value = strtoul(str.c_str(), &endptr, 0);
  148. if (!endptr || *endptr)
  149. return false;
  150. if (errno == ERANGE)
  151. return false;
  152. #if ULONG_MAX > UINT_MAX
  153. if (value >= 0x100000000ull
  154. && value <= 0xFFFFFFFF00000000ull)
  155. return false;
  156. #endif
  157. *output = static_cast<u32>(value);
  158. return true;
  159. }
  160. bool TryParse(const std::string &str, bool *const output)
  161. {
  162. if ("1" == str || !strcasecmp("true", str.c_str()))
  163. *output = true;
  164. else if ("0" == str || !strcasecmp("false", str.c_str()))
  165. *output = false;
  166. else
  167. return false;
  168. return true;
  169. }
  170. std::string StringFromInt(int value)
  171. {
  172. char temp[16];
  173. sprintf(temp, "%i", value);
  174. return temp;
  175. }
  176. std::string StringFromBool(bool value)
  177. {
  178. return value ? "True" : "False";
  179. }
  180. bool SplitPath(const std::string& full_path, std::string* _pPath, std::string* _pFilename, std::string* _pExtension)
  181. {
  182. if (full_path.empty())
  183. return false;
  184. size_t dir_end = full_path.find_last_of("/"
  185. // windows needs the : included for something like just "C:" to be considered a directory
  186. #ifdef _WIN32
  187. ":"
  188. #endif
  189. );
  190. if (std::string::npos == dir_end)
  191. dir_end = 0;
  192. else
  193. dir_end += 1;
  194. size_t fname_end = full_path.rfind('.');
  195. if (fname_end < dir_end || std::string::npos == fname_end)
  196. fname_end = full_path.size();
  197. if (_pPath)
  198. *_pPath = full_path.substr(0, dir_end);
  199. if (_pFilename)
  200. *_pFilename = full_path.substr(dir_end, fname_end - dir_end);
  201. if (_pExtension)
  202. *_pExtension = full_path.substr(fname_end);
  203. return true;
  204. }
  205. void BuildCompleteFilename(std::string& _CompleteFilename, const std::string& _Path, const std::string& _Filename)
  206. {
  207. _CompleteFilename = _Path;
  208. // check for seperator
  209. if (DIR_SEP_CHR != *_CompleteFilename.rbegin())
  210. _CompleteFilename += DIR_SEP_CHR;
  211. // add the filename
  212. _CompleteFilename += _Filename;
  213. }
  214. void SplitString(const std::string& str, const char delim, std::vector<std::string>& output)
  215. {
  216. std::istringstream iss(str);
  217. output.resize(1);
  218. while (std::getline(iss, *output.rbegin(), delim))
  219. output.push_back("");
  220. output.pop_back();
  221. }
  222. std::string TabsToSpaces(int tab_size, const std::string &in)
  223. {
  224. const std::string spaces(tab_size, ' ');
  225. std::string out(in);
  226. size_t i = 0;
  227. while (out.npos != (i = out.find('\t')))
  228. out.replace(i, 1, spaces);
  229. return out;
  230. }
  231. std::string ReplaceAll(std::string result, const std::string& src, const std::string& dest)
  232. {
  233. while(1)
  234. {
  235. size_t pos = result.find(src);
  236. if (pos == std::string::npos) break;
  237. result.replace(pos, src.size(), dest);
  238. }
  239. return result;
  240. }
  241. // UriDecode and UriEncode are from http://www.codeguru.com/cpp/cpp/string/conversions/print.php/c12759
  242. // by jinq0123 (November 2, 2006)
  243. // Uri encode and decode.
  244. // RFC1630, RFC1738, RFC2396
  245. //#include <string>
  246. //#include <assert.h>
  247. const char HEX2DEC[256] =
  248. {
  249. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  250. /* 0 */ 16,16,16,16, 16,16,16,16, 16,16,16,16, 16,16,16,16,
  251. /* 1 */ 16,16,16,16, 16,16,16,16, 16,16,16,16, 16,16,16,16,
  252. /* 2 */ 16,16,16,16, 16,16,16,16, 16,16,16,16, 16,16,16,16,
  253. /* 3 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,16,16, 16,16,16,16,
  254. /* 4 */ 16,10,11,12, 13,14,15,16, 16,16,16,16, 16,16,16,16,
  255. /* 5 */ 16,16,16,16, 16,16,16,16, 16,16,16,16, 16,16,16,16,
  256. /* 6 */ 16,10,11,12, 13,14,15,16, 16,16,16,16, 16,16,16,16,
  257. /* 7 */ 16,16,16,16, 16,16,16,16, 16,16,16,16, 16,16,16,16,
  258. /* 8 */ 16,16,16,16, 16,16,16,16, 16,16,16,16, 16,16,16,16,
  259. /* 9 */ 16,16,16,16, 16,16,16,16, 16,16,16,16, 16,16,16,16,
  260. /* A */ 16,16,16,16, 16,16,16,16, 16,16,16,16, 16,16,16,16,
  261. /* B */ 16,16,16,16, 16,16,16,16, 16,16,16,16, 16,16,16,16,
  262. /* C */ 16,16,16,16, 16,16,16,16, 16,16,16,16, 16,16,16,16,
  263. /* D */ 16,16,16,16, 16,16,16,16, 16,16,16,16, 16,16,16,16,
  264. /* E */ 16,16,16,16, 16,16,16,16, 16,16,16,16, 16,16,16,16,
  265. /* F */ 16,16,16,16, 16,16,16,16, 16,16,16,16, 16,16,16,16
  266. };
  267. std::string UriDecode(const std::string & sSrc)
  268. {
  269. // Note from RFC1630: "Sequences which start with a percent sign
  270. // but are not followed by two hexadecimal characters (0-9, A-F) are reserved
  271. // for future extension"
  272. const unsigned char * pSrc = (const unsigned char *)sSrc.c_str();
  273. const size_t SRC_LEN = sSrc.length();
  274. const unsigned char * const SRC_END = pSrc + SRC_LEN;
  275. const unsigned char * const SRC_LAST_DEC = SRC_END - 2; // last decodable '%'
  276. char * const pStart = new char[SRC_LEN];
  277. char * pEnd = pStart;
  278. while (pSrc < SRC_LAST_DEC)
  279. {
  280. if (*pSrc == '%')
  281. {
  282. char dec1, dec2;
  283. if (16 != (dec1 = HEX2DEC[*(pSrc + 1)])
  284. && 16 != (dec2 = HEX2DEC[*(pSrc + 2)]))
  285. {
  286. *pEnd++ = (dec1 << 4) + dec2;
  287. pSrc += 3;
  288. continue;
  289. }
  290. }
  291. *pEnd++ = *pSrc++;
  292. }
  293. // the last 2- chars
  294. while (pSrc < SRC_END)
  295. *pEnd++ = *pSrc++;
  296. std::string sResult(pStart, pEnd);
  297. delete [] pStart;
  298. return sResult;
  299. }
  300. // Only alphanum is safe.
  301. const char SAFE[256] =
  302. {
  303. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  304. /* 0 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
  305. /* 1 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
  306. /* 2 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
  307. /* 3 */ 1,1,1,1, 1,1,1,1, 1,1,0,0, 0,0,0,0,
  308. /* 4 */ 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1,
  309. /* 5 */ 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,0,
  310. /* 6 */ 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1,
  311. /* 7 */ 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,0,
  312. /* 8 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
  313. /* 9 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
  314. /* A */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
  315. /* B */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
  316. /* C */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
  317. /* D */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
  318. /* E */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
  319. /* F */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0
  320. };
  321. std::string UriEncode(const std::string & sSrc)
  322. {
  323. const char DEC2HEX[16 + 1] = "0123456789ABCDEF";
  324. const unsigned char * pSrc = (const unsigned char *)sSrc.c_str();
  325. const size_t SRC_LEN = sSrc.length();
  326. unsigned char * const pStart = new unsigned char[SRC_LEN * 3];
  327. unsigned char * pEnd = pStart;
  328. const unsigned char * const SRC_END = pSrc + SRC_LEN;
  329. for (; pSrc < SRC_END; ++pSrc)
  330. {
  331. if (SAFE[*pSrc])
  332. *pEnd++ = *pSrc;
  333. else
  334. {
  335. // escape this char
  336. *pEnd++ = '%';
  337. *pEnd++ = DEC2HEX[*pSrc >> 4];
  338. *pEnd++ = DEC2HEX[*pSrc & 0x0F];
  339. }
  340. }
  341. std::string sResult((char *)pStart, (char *)pEnd);
  342. delete [] pStart;
  343. return sResult;
  344. }
  345. #ifdef _WIN32
  346. std::string UTF16ToUTF8(const std::wstring& input)
  347. {
  348. auto const size = WideCharToMultiByte(CP_UTF8, 0, input.data(), input.size(), nullptr, 0, nullptr, nullptr);
  349. std::string output;
  350. output.resize(size);
  351. if (size == 0 || size != WideCharToMultiByte(CP_UTF8, 0, input.data(), input.size(), &output[0], output.size(), nullptr, nullptr))
  352. output.clear();
  353. return output;
  354. }
  355. std::wstring CPToUTF16(u32 code_page, const std::string& input)
  356. {
  357. auto const size = MultiByteToWideChar(code_page, 0, input.data(), input.size(), nullptr, 0);
  358. std::wstring output;
  359. output.resize(size);
  360. if (size == 0 || size != MultiByteToWideChar(code_page, 0, input.data(), input.size(), &output[0], output.size()))
  361. output.clear();
  362. return output;
  363. }
  364. std::wstring UTF8ToUTF16(const std::string& input)
  365. {
  366. return CPToUTF16(CP_UTF8, input);
  367. }
  368. std::string SHIFTJISToUTF8(const std::string& input)
  369. {
  370. return UTF16ToUTF8(CPToUTF16(932, input));
  371. }
  372. std::string CP1252ToUTF8(const std::string& input)
  373. {
  374. return UTF16ToUTF8(CPToUTF16(1252, input));
  375. }
  376. #else
  377. template <typename T>
  378. std::string CodeToUTF8(const char* fromcode, const std::basic_string<T>& input)
  379. {
  380. std::string result;
  381. iconv_t const conv_desc = iconv_open("UTF-8", fromcode);
  382. if ((iconv_t)-1 == conv_desc)
  383. {
  384. ERROR_LOG(COMMON, "Iconv initialization failure [%s]: %s", fromcode, strerror(errno));
  385. }
  386. else
  387. {
  388. size_t const in_bytes = sizeof(T) * input.size();
  389. size_t const out_buffer_size = 4 * in_bytes;
  390. std::string out_buffer;
  391. out_buffer.resize(out_buffer_size);
  392. auto src_buffer = &input[0];
  393. size_t src_bytes = in_bytes;
  394. auto dst_buffer = &out_buffer[0];
  395. size_t dst_bytes = out_buffer.size();
  396. while (src_bytes != 0)
  397. {
  398. size_t const iconv_result = iconv(conv_desc, (char**)(&src_buffer), &src_bytes,
  399. &dst_buffer, &dst_bytes);
  400. if ((size_t)-1 == iconv_result)
  401. {
  402. if (EILSEQ == errno || EINVAL == errno)
  403. {
  404. // Try to skip the bad character
  405. if (src_bytes != 0)
  406. {
  407. --src_bytes;
  408. ++src_buffer;
  409. }
  410. }
  411. else
  412. {
  413. ERROR_LOG(COMMON, "iconv failure [%s]: %s", fromcode, strerror(errno));
  414. break;
  415. }
  416. }
  417. }
  418. out_buffer.resize(out_buffer_size - dst_bytes);
  419. out_buffer.swap(result);
  420. iconv_close(conv_desc);
  421. }
  422. return result;
  423. }
  424. std::string CP1252ToUTF8(const std::string& input)
  425. {
  426. //return CodeToUTF8("CP1252//TRANSLIT", input);
  427. //return CodeToUTF8("CP1252//IGNORE", input);
  428. return CodeToUTF8("CP1252", input);
  429. }
  430. std::string SHIFTJISToUTF8(const std::string& input)
  431. {
  432. //return CodeToUTF8("CP932", input);
  433. return CodeToUTF8("SJIS", input);
  434. }
  435. std::string UTF16ToUTF8(const std::wstring& input)
  436. {
  437. std::string result =
  438. // CodeToUTF8("UCS-2", input);
  439. // CodeToUTF8("UCS-2LE", input);
  440. // CodeToUTF8("UTF-16", input);
  441. CodeToUTF8("UTF-16LE", input);
  442. // TODO: why is this needed?
  443. result.erase(std::remove(result.begin(), result.end(), 0x00), result.end());
  444. return result;
  445. }
  446. #endif
  447. }