mirror of
https://github.com/monero-project/monero.git
synced 2025-05-06 13:45:00 -04:00
epee.string_tools: add conversion between UTF-8 and UTF-16
This commit is contained in:
parent
2329d2f4c8
commit
1d176473e9
3 changed files with 63 additions and 26 deletions
|
@ -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_
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue