1#include "duckdb/common/windows_util.hpp"
2
3namespace duckdb {
4
5#ifdef DUCKDB_WINDOWS
6
7std::wstring WindowsUtil::UTF8ToUnicode(const char *input) {
8 idx_t result_size;
9
10 result_size = MultiByteToWideChar(CP_UTF8, 0, input, -1, nullptr, 0);
11 if (result_size == 0) {
12 throw IOException("Failure in MultiByteToWideChar");
13 }
14 auto buffer = make_unsafe_uniq_array<wchar_t>(result_size);
15 result_size = MultiByteToWideChar(CP_UTF8, 0, input, -1, buffer.get(), result_size);
16 if (result_size == 0) {
17 throw IOException("Failure in MultiByteToWideChar");
18 }
19 return std::wstring(buffer.get(), result_size);
20}
21
22static string WideCharToMultiByteWrapper(LPCWSTR input, uint32_t code_page) {
23 idx_t result_size;
24
25 result_size = WideCharToMultiByte(code_page, 0, input, -1, 0, 0, 0, 0);
26 if (result_size == 0) {
27 throw IOException("Failure in WideCharToMultiByte");
28 }
29 auto buffer = make_unsafe_uniq_array<char>(result_size);
30 result_size = WideCharToMultiByte(code_page, 0, input, -1, buffer.get(), result_size, 0, 0);
31 if (result_size == 0) {
32 throw IOException("Failure in WideCharToMultiByte");
33 }
34 return string(buffer.get(), result_size - 1);
35}
36
37string WindowsUtil::UnicodeToUTF8(LPCWSTR input) {
38 return WideCharToMultiByteWrapper(input, CP_UTF8);
39}
40
41static string WindowsUnicodeToMBCS(LPCWSTR unicode_text, int use_ansi) {
42 uint32_t code_page = use_ansi ? CP_ACP : CP_OEMCP;
43 return WideCharToMultiByteWrapper(unicode_text, code_page);
44}
45
46string WindowsUtil::UTF8ToMBCS(const char *input, bool use_ansi) {
47 auto unicode = WindowsUtil::UTF8ToUnicode(input);
48 return WindowsUnicodeToMBCS(unicode.c_str(), use_ansi);
49}
50
51#endif
52
53} // namespace duckdb
54