@@ -93,6 +93,42 @@ std::wstring Utf8ToUtf16(const std::string &utf8) {
9393 return Utf8ToUtf16 (utf8.c_str (), utf8.length ());
9494}
9595
96+ size_t Utf8ToUtf16Length (const char *utf8, size_t utf8Len) {
97+ if (utf8Len == 0 ) {
98+ return 0 ;
99+ }
100+
101+ if (utf8Len > static_cast <size_t >((std::numeric_limits<int >::max)())) {
102+ throw std::overflow_error (" Length of input string to Utf8ToUtf16Length() must fit into an int." );
103+ }
104+
105+ const int utf8Length = static_cast <int >(utf8Len);
106+
107+ constexpr DWORD flags = 0 ;
108+
109+ const int utf16Length = ::MultiByteToWideChar (
110+ CP_UTF8 , // Source string is in UTF-8.
111+ flags, // Conversion flags.
112+ utf8, // Source UTF-8 string pointer.
113+ utf8Length, // Length of the source UTF-8 string, in chars.
114+ nullptr , // Do not convert, just request the size.
115+ 0 // Request size of destination buffer, in wchar_ts.
116+ );
117+
118+ if (utf16Length == 0 ) {
119+ throw UnicodeConversionException (
120+ " Cannot get result string length when converting from UTF-8 to UTF-16 "
121+ " (MultiByteToWideChar failed)." ,
122+ GetLastError ());
123+ }
124+
125+ return static_cast <size_t >(utf16Length);
126+ }
127+
128+ size_t Utf8ToUtf16Length (const std::string &utf8) {
129+ return Utf8ToUtf16Length (utf8.c_str (), utf8.length ());
130+ }
131+
96132#if _HAS_CXX17
97133std::wstring Utf8ToUtf16 (const std::string_view &utf8) {
98134 return Utf8ToUtf16 (utf8.data (), utf8.length ());
0 commit comments