string_util.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. // For Debugging. Read out an u8 array.
  32. std::string ArrayToString(const u8* data, size_t size, int line_len, bool spaces) {
  33. std::ostringstream oss;
  34. oss << std::setfill('0') << std::hex;
  35. for (int line = 0; size; ++data, --size) {
  36. oss << std::setw(2) << (int)*data;
  37. if (line_len == ++line) {
  38. oss << '\n';
  39. line = 0;
  40. } else if (spaces)
  41. oss << ' ';
  42. }
  43. return oss.str();
  44. }
  45. std::string StringFromBuffer(const std::vector<u8>& data) {
  46. return std::string(data.begin(), std::find(data.begin(), data.end(), '\0'));
  47. }
  48. // Turns " hej " into "hej". Also handles tabs.
  49. std::string StripSpaces(const std::string& str) {
  50. const size_t s = str.find_first_not_of(" \t\r\n");
  51. if (str.npos != s)
  52. return str.substr(s, str.find_last_not_of(" \t\r\n") - s + 1);
  53. else
  54. return "";
  55. }
  56. // "\"hello\"" is turned to "hello"
  57. // This one assumes that the string has already been space stripped in both
  58. // ends, as done by StripSpaces above, for example.
  59. std::string StripQuotes(const std::string& s) {
  60. if (s.size() && '\"' == s[0] && '\"' == *s.rbegin())
  61. return s.substr(1, s.size() - 2);
  62. else
  63. return s;
  64. }
  65. bool TryParse(const std::string& str, u32* const output) {
  66. char* endptr = nullptr;
  67. // Reset errno to a value other than ERANGE
  68. errno = 0;
  69. unsigned long value = strtoul(str.c_str(), &endptr, 0);
  70. if (!endptr || *endptr)
  71. return false;
  72. if (errno == ERANGE)
  73. return false;
  74. #if ULONG_MAX > UINT_MAX
  75. if (value >= 0x100000000ull && value <= 0xFFFFFFFF00000000ull)
  76. return false;
  77. #endif
  78. *output = static_cast<u32>(value);
  79. return true;
  80. }
  81. bool TryParse(const std::string& str, bool* const output) {
  82. if ("1" == str || "true" == ToLower(str))
  83. *output = true;
  84. else if ("0" == str || "false" == ToLower(str))
  85. *output = false;
  86. else
  87. return false;
  88. return true;
  89. }
  90. std::string StringFromBool(bool value) {
  91. return value ? "True" : "False";
  92. }
  93. bool SplitPath(const std::string& full_path, std::string* _pPath, std::string* _pFilename,
  94. std::string* _pExtension) {
  95. if (full_path.empty())
  96. return false;
  97. size_t dir_end = full_path.find_last_of("/"
  98. // windows needs the : included for something like just "C:" to be considered a directory
  99. #ifdef _WIN32
  100. "\\:"
  101. #endif
  102. );
  103. if (std::string::npos == dir_end)
  104. dir_end = 0;
  105. else
  106. dir_end += 1;
  107. size_t fname_end = full_path.rfind('.');
  108. if (fname_end < dir_end || std::string::npos == fname_end)
  109. fname_end = full_path.size();
  110. if (_pPath)
  111. *_pPath = full_path.substr(0, dir_end);
  112. if (_pFilename)
  113. *_pFilename = full_path.substr(dir_end, fname_end - dir_end);
  114. if (_pExtension)
  115. *_pExtension = full_path.substr(fname_end);
  116. return true;
  117. }
  118. void BuildCompleteFilename(std::string& _CompleteFilename, const std::string& _Path,
  119. const std::string& _Filename) {
  120. _CompleteFilename = _Path;
  121. // check for seperator
  122. if (DIR_SEP_CHR != *_CompleteFilename.rbegin())
  123. _CompleteFilename += DIR_SEP_CHR;
  124. // add the filename
  125. _CompleteFilename += _Filename;
  126. }
  127. void SplitString(const std::string& str, const char delim, std::vector<std::string>& output) {
  128. std::istringstream iss(str);
  129. output.resize(1);
  130. while (std::getline(iss, *output.rbegin(), delim)) {
  131. output.emplace_back();
  132. }
  133. output.pop_back();
  134. }
  135. std::string TabsToSpaces(int tab_size, std::string in) {
  136. size_t i = 0;
  137. while ((i = in.find('\t')) != std::string::npos) {
  138. in.replace(i, 1, tab_size, ' ');
  139. }
  140. return in;
  141. }
  142. std::string ReplaceAll(std::string result, const std::string& src, const std::string& dest) {
  143. size_t pos = 0;
  144. if (src == dest)
  145. return result;
  146. while ((pos = result.find(src, pos)) != std::string::npos) {
  147. result.replace(pos, src.size(), dest);
  148. pos += dest.length();
  149. }
  150. return result;
  151. }
  152. #ifdef _WIN32
  153. std::string UTF16ToUTF8(const std::u16string& input) {
  154. #if _MSC_VER >= 1900
  155. // Workaround for missing char16_t/char32_t instantiations in MSVC2015
  156. std::wstring_convert<std::codecvt_utf8_utf16<__int16>, __int16> convert;
  157. std::basic_string<__int16> tmp_buffer(input.cbegin(), input.cend());
  158. return convert.to_bytes(tmp_buffer);
  159. #else
  160. std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
  161. return convert.to_bytes(input);
  162. #endif
  163. }
  164. std::u16string UTF8ToUTF16(const std::string& input) {
  165. #if _MSC_VER >= 1900
  166. // Workaround for missing char16_t/char32_t instantiations in MSVC2015
  167. std::wstring_convert<std::codecvt_utf8_utf16<__int16>, __int16> convert;
  168. auto tmp_buffer = convert.from_bytes(input);
  169. return std::u16string(tmp_buffer.cbegin(), tmp_buffer.cend());
  170. #else
  171. std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
  172. return convert.from_bytes(input);
  173. #endif
  174. }
  175. static std::wstring CPToUTF16(u32 code_page, const std::string& input) {
  176. const auto size =
  177. MultiByteToWideChar(code_page, 0, input.data(), static_cast<int>(input.size()), nullptr, 0);
  178. if (size == 0) {
  179. return L"";
  180. }
  181. std::wstring output(size, L'\0');
  182. if (size != MultiByteToWideChar(code_page, 0, input.data(), static_cast<int>(input.size()),
  183. &output[0], static_cast<int>(output.size()))) {
  184. output.clear();
  185. }
  186. return output;
  187. }
  188. std::string UTF16ToUTF8(const std::wstring& input) {
  189. const auto size = WideCharToMultiByte(CP_UTF8, 0, input.data(), static_cast<int>(input.size()),
  190. nullptr, 0, nullptr, nullptr);
  191. if (size == 0) {
  192. return "";
  193. }
  194. std::string output(size, '\0');
  195. if (size != WideCharToMultiByte(CP_UTF8, 0, input.data(), static_cast<int>(input.size()),
  196. &output[0], static_cast<int>(output.size()), nullptr,
  197. nullptr)) {
  198. output.clear();
  199. }
  200. return output;
  201. }
  202. std::wstring UTF8ToUTF16W(const std::string& input) {
  203. return CPToUTF16(CP_UTF8, input);
  204. }
  205. std::string SHIFTJISToUTF8(const std::string& input) {
  206. return UTF16ToUTF8(CPToUTF16(932, input));
  207. }
  208. std::string CP1252ToUTF8(const std::string& input) {
  209. return UTF16ToUTF8(CPToUTF16(1252, input));
  210. }
  211. #else
  212. template <typename T>
  213. static std::string CodeToUTF8(const char* fromcode, const std::basic_string<T>& input) {
  214. iconv_t const conv_desc = iconv_open("UTF-8", fromcode);
  215. if ((iconv_t)(-1) == conv_desc) {
  216. LOG_ERROR(Common, "Iconv initialization failure [{}]: {}", fromcode, strerror(errno));
  217. iconv_close(conv_desc);
  218. return {};
  219. }
  220. const size_t in_bytes = sizeof(T) * input.size();
  221. // Multiply by 4, which is the max number of bytes to encode a codepoint
  222. const size_t out_buffer_size = 4 * in_bytes;
  223. std::string out_buffer(out_buffer_size, '\0');
  224. auto src_buffer = &input[0];
  225. size_t src_bytes = in_bytes;
  226. auto dst_buffer = &out_buffer[0];
  227. size_t dst_bytes = out_buffer.size();
  228. while (0 != src_bytes) {
  229. size_t const iconv_result =
  230. iconv(conv_desc, (char**)(&src_buffer), &src_bytes, &dst_buffer, &dst_bytes);
  231. if (static_cast<size_t>(-1) == iconv_result) {
  232. if (EILSEQ == errno || EINVAL == errno) {
  233. // Try to skip the bad character
  234. if (0 != src_bytes) {
  235. --src_bytes;
  236. ++src_buffer;
  237. }
  238. } else {
  239. LOG_ERROR(Common, "iconv failure [{}]: {}", fromcode, strerror(errno));
  240. break;
  241. }
  242. }
  243. }
  244. std::string result;
  245. out_buffer.resize(out_buffer_size - dst_bytes);
  246. out_buffer.swap(result);
  247. iconv_close(conv_desc);
  248. return result;
  249. }
  250. std::u16string UTF8ToUTF16(const std::string& input) {
  251. iconv_t const conv_desc = iconv_open("UTF-16LE", "UTF-8");
  252. if ((iconv_t)(-1) == conv_desc) {
  253. LOG_ERROR(Common, "Iconv initialization failure [UTF-8]: {}", strerror(errno));
  254. iconv_close(conv_desc);
  255. return {};
  256. }
  257. const size_t in_bytes = sizeof(char) * input.size();
  258. // Multiply by 4, which is the max number of bytes to encode a codepoint
  259. const size_t out_buffer_size = 4 * sizeof(char16_t) * in_bytes;
  260. std::u16string out_buffer(out_buffer_size, char16_t{});
  261. char* src_buffer = const_cast<char*>(&input[0]);
  262. size_t src_bytes = in_bytes;
  263. char* dst_buffer = (char*)(&out_buffer[0]);
  264. size_t dst_bytes = out_buffer.size();
  265. while (0 != src_bytes) {
  266. size_t const iconv_result =
  267. iconv(conv_desc, &src_buffer, &src_bytes, &dst_buffer, &dst_bytes);
  268. if (static_cast<size_t>(-1) == iconv_result) {
  269. if (EILSEQ == errno || EINVAL == errno) {
  270. // Try to skip the bad character
  271. if (0 != src_bytes) {
  272. --src_bytes;
  273. ++src_buffer;
  274. }
  275. } else {
  276. LOG_ERROR(Common, "iconv failure [UTF-8]: {}", strerror(errno));
  277. break;
  278. }
  279. }
  280. }
  281. std::u16string result;
  282. out_buffer.resize(out_buffer_size - dst_bytes);
  283. out_buffer.swap(result);
  284. iconv_close(conv_desc);
  285. return result;
  286. }
  287. std::string UTF16ToUTF8(const std::u16string& input) {
  288. return CodeToUTF8("UTF-16LE", input);
  289. }
  290. std::string CP1252ToUTF8(const std::string& input) {
  291. // return CodeToUTF8("CP1252//TRANSLIT", input);
  292. // return CodeToUTF8("CP1252//IGNORE", input);
  293. return CodeToUTF8("CP1252", input);
  294. }
  295. std::string SHIFTJISToUTF8(const std::string& input) {
  296. // return CodeToUTF8("CP932", input);
  297. return CodeToUTF8("SJIS", input);
  298. }
  299. #endif
  300. std::string StringFromFixedZeroTerminatedBuffer(const char* buffer, size_t max_len) {
  301. size_t len = 0;
  302. while (len < max_len && buffer[len] != '\0')
  303. ++len;
  304. return std::string(buffer, len);
  305. }
  306. const char* TrimSourcePath(const char* path, const char* root) {
  307. const char* p = path;
  308. while (*p != '\0') {
  309. const char* next_slash = p;
  310. while (*next_slash != '\0' && *next_slash != '/' && *next_slash != '\\') {
  311. ++next_slash;
  312. }
  313. bool is_src = Common::ComparePartialString(p, next_slash, root);
  314. p = next_slash;
  315. if (*p != '\0') {
  316. ++p;
  317. }
  318. if (is_src) {
  319. path = p;
  320. }
  321. }
  322. return path;
  323. }
  324. } // namespace Common