-
Notifications
You must be signed in to change notification settings - Fork 66
/
Util.hpp
91 lines (79 loc) · 1.78 KB
/
Util.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#pragma once
// https://msdn.microsoft.com/en-us/magazine/mt763237
std::wstring Utf8ToUtf16(std::string_view utf8)
{
if (utf8.empty())
{
return {};
}
constexpr DWORD kFlags = MB_ERR_INVALID_CHARS;
const int utf8Length = static_cast<int>(utf8.length());
const int utf16Length = MultiByteToWideChar(
CP_UTF8,
kFlags,
utf8.data(),
utf8Length,
nullptr,
0
);
THROW_LAST_ERROR_IF(utf16Length == 0);
std::wstring utf16(utf16Length, L'\0');
const int result = MultiByteToWideChar(
CP_UTF8,
kFlags,
utf8.data(),
utf8Length,
utf16.data(),
utf16Length
);
THROW_LAST_ERROR_IF(result == 0);
return utf16;
}
std::string Utf16ToUtf8(std::wstring_view utf16)
{
if (utf16.empty())
{
return {};
}
constexpr DWORD kFlags = WC_ERR_INVALID_CHARS;
const int utf16Length = static_cast<int>(utf16.length());
const int utf8Length = WideCharToMultiByte(
CP_UTF8,
kFlags,
utf16.data(),
utf16Length,
nullptr,
0,
nullptr, nullptr
);
THROW_LAST_ERROR_IF(utf8Length == 0);
std::string utf8(utf8Length, '\0');
const int result = WideCharToMultiByte(
CP_UTF8,
kFlags,
utf16.data(),
utf16Length,
utf8.data(),
utf8Length,
nullptr, nullptr
);
THROW_LAST_ERROR_IF(result == 0);
return utf8;
}
// https://docs.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/author-coclasses#add-helper-types-and-functions
// License: see the https://github.com/MicrosoftDocs/windows-uwp/blob/docs/LICENSE-CODE file
auto GetModuleFsPath(HMODULE hModule)
{
std::wstring path(MAX_PATH, L'\0');
DWORD actualSize;
while (1)
{
actualSize = GetModuleFileNameW(hModule, path.data(), static_cast<DWORD>(path.size()));
if (static_cast<size_t>(actualSize) + 1 > path.size())
path.resize(path.size() * 2);
else
break;
}
path.resize(actualSize);
return fs::path(path);
}