openMSX
utf8_checked.cc
Go to the documentation of this file.
1 #ifdef _WIN32
2 
3 #include "utf8_checked.hh"
4 #include "vla.hh"
5 #include "MSXException.hh"
6 #include <windows.h>
7 
8 namespace utf8 {
9 
10 static bool multibytetoutf16(const std::string& multibyte, UINT cp, DWORD dwFlags, std::wstring& utf16)
11 {
12  const char* multibyteA = multibyte.c_str();
13  int len = MultiByteToWideChar(cp, dwFlags, multibyteA, -1, nullptr, 0);
14  if (len) {
15  VLA(wchar_t, utf16W, len);
16  len = MultiByteToWideChar(cp, dwFlags, multibyteA, -1, utf16W, len);
17  if (len) {
18  utf16 = utf16W;
19  return true;
20  }
21  }
22  return false;
23 }
24 
25 static bool utf16tomultibyte(const std::wstring& utf16, UINT cp, std::string& multibyte)
26 {
27  const wchar_t* utf16W = utf16.c_str();
28  int len = WideCharToMultiByte(cp, 0, utf16W, -1, nullptr, 0, nullptr, nullptr);
29  if (len) {
30  VLA(char, multibyteA, len);
31  len = WideCharToMultiByte(cp, 0, utf16W, -1, multibyteA, len, nullptr, nullptr);
32  if (len) {
33  multibyte = multibyteA;
34  return true;
35  }
36  }
37  return false;
38 }
39 
40 std::string utf8toansi(const std::string& utf8)
41 {
42  std::wstring utf16;
43  if (!multibytetoutf16(utf8, CP_UTF8, MB_ERR_INVALID_CHARS, utf16))
44  {
45  throw openmsx::FatalError(
46  "MultiByteToWideChar failed: ", GetLastError());
47  }
48 
49  std::string ansi;
50  if (!utf16tomultibyte(utf16, CP_ACP, ansi))
51  {
52  throw openmsx::FatalError(
53  "MultiByteToWideChar failed: ", GetLastError());
54  }
55  return ansi;
56 }
57 
58 std::wstring utf8to16(const std::string& utf8)
59 {
60  std::wstring utf16;
61  if (!multibytetoutf16(utf8, CP_UTF8, MB_ERR_INVALID_CHARS, utf16))
62  {
63  throw openmsx::FatalError(
64  "MultiByteToWideChar failed: ", GetLastError());
65  }
66  return utf16;
67 }
68 
69 std::string utf16to8(const std::wstring& utf16)
70 {
71  std::string utf8;
72  if (!utf16tomultibyte(utf16, CP_UTF8, utf8))
73  {
74  throw openmsx::FatalError(
75  "MultiByteToWideChar failed: ", GetLastError());
76  }
77  return utf8;
78 }
79 
80 } // namespace utf8
81 
82 #endif // _WIN32
utf8
Definition: utf8_checked.hh:36
utf8::utf8to16
u16bit_iterator utf8to16(octet_iterator start, octet_iterator end, u16bit_iterator result)
Definition: utf8_checked.hh:227
MSXException.hh
vla.hh
openmsx::FatalError
Definition: MSXException.hh:31
utf8_checked.hh
utf8::utf16to8
octet_iterator utf16to8(u16bit_iterator start, u16bit_iterator end, octet_iterator result)
Definition: utf8_checked.hh:204
VLA
#define VLA(TYPE, NAME, LENGTH)
Definition: vla.hh:10