diff options
author | stoffu <stoffu@protonmail.ch> | 2018-06-25 09:44:07 +0900 |
---|---|---|
committer | stoffu <stoffu@protonmail.ch> | 2018-06-28 09:40:26 +0900 |
commit | 1d176473e90d0e75588ac97f32feb354f4b5da37 (patch) | |
tree | 5ec0b9cb18c651f7c703b48da9cc6bcf94eefa1f /contrib/epee/include/string_tools.h | |
parent | Merge pull request #3907 (diff) | |
download | monero-1d176473e90d0e75588ac97f32feb354f4b5da37.tar.xz |
epee.string_tools: add conversion between UTF-8 and UTF-16
Diffstat (limited to '')
-rw-r--r-- | contrib/epee/include/string_tools.h | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/contrib/epee/include/string_tools.h b/contrib/epee/include/string_tools.h index 63705e401..8d8603076 100644 --- a/contrib/epee/include/string_tools.h +++ b/contrib/epee/include/string_tools.h @@ -381,6 +381,41 @@ POP_WARNINGS res = str.substr(0, pos); return res; } + //---------------------------------------------------------------------------- +#ifdef _WIN32 + inline std::wstring utf8_to_utf16(const std::string& str) + { + if (str.empty()) + return {}; + int wstr_size = MultiByteToWideChar(CP_UTF8, 0, &str[0], str.size(), NULL, 0); + if (wstr_size == 0) + { + throw std::runtime_error(std::error_code(GetLastError(), std::system_category()).message()); + } + std::wstring wstr(wstr_size, wchar_t{}); + if (!MultiByteToWideChar(CP_UTF8, 0, &str[0], str.size(), &wstr[0], wstr_size)) + { + throw std::runtime_error(std::error_code(GetLastError(), std::system_category()).message()); + } + return wstr; + } + inline std::string utf16_to_utf8(const std::wstring& wstr) + { + if (wstr.empty()) + return {}; + int str_size = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], wstr.size(), NULL, 0, NULL, NULL); + if (str_size == 0) + { + throw std::runtime_error(std::error_code(GetLastError(), std::system_category()).message()); + } + std::string str(str_size, char{}); + if (!WideCharToMultiByte(CP_UTF8, 0, &wstr[0], wstr.size(), &str[0], str_size, NULL, NULL)) + { + throw std::runtime_error(std::error_code(GetLastError(), std::system_category()).message()); + } + return str; + } +#endif } } #endif //_STRING_TOOLS_H_ |