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