Skip to content

Commit 0d67a33

Browse files
author
pfeatherstone
committed
fixed convert_wstring_to_mbstring as well
1 parent 2d68d52 commit 0d67a33

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

dlib/unicode/unicode.cpp

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -114,11 +114,19 @@ namespace dlib
114114

115115
const std::string convert_wstring_to_mbstring(const std::wstring &src)
116116
{
117-
using namespace std;
118-
std::string str;
119-
str.resize((src.length() + 1) * MB_CUR_MAX);
120-
wcstombs(&str[0], src.c_str(), str.size());
121-
return std::string(&str[0]);
117+
std::mbstate_t st{};
118+
const wchar_t* p = src.c_str();
119+
120+
// Compute length
121+
size_t n = std::wcsrtombs(nullptr, &p, 0, &st);
122+
if (n == static_cast<std::size_t>(-1)) throw std::runtime_error("Invalid wide sequence / locale mismatch");
123+
124+
// Convert
125+
std::string out(n, '\0');
126+
st = std::mbstate_t{};
127+
n = std::wcsrtombs(out.data(), &p, out.size(), &st);
128+
if (n == static_cast<std::size_t>(-1)) throw std::runtime_error("Conversion failed");
129+
return out;
122130
}
123131

124132
// ----------------------------------------------------------------------------------------

0 commit comments

Comments
 (0)