From dddfe85604bb2ed6c14dd73a77a067ec278403eb Mon Sep 17 00:00:00 2001 From: Frederic BORRY Date: Tue, 14 Jul 2026 19:22:25 +0200 Subject: [PATCH] Fix for https://github.com/ngscopeclient/xptools/issues/40 --- StringUtil.cpp | 27 ++++++++++++++++++++------- StringUtil.h | 4 ++-- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/StringUtil.cpp b/StringUtil.cpp index 0904ee3..e112495 100644 --- a/StringUtil.cpp +++ b/StringUtil.cpp @@ -37,8 +37,8 @@ #ifdef _WIN32 #include #else -#include -#include +#include +#include #endif /** @@ -62,9 +62,15 @@ std::string WstringToString(const std::wstring &wstr) return res; #else // Linux / macOS - std::wstring ws(wstr); - std::wstring_convert> conv; - return conv.to_bytes(ws); + std::size_t len = std::wcstombs(nullptr, wstr.c_str(), 0); + + if (len == static_cast(-1)) + return "Invalid wide-character sequence or invalid locale"; + + std::string result(len, '\0'); + std::wcstombs(result.data(), wstr.c_str(), len); + + return result; #endif // _WIN32 } @@ -89,7 +95,14 @@ std::wstring StringToWstring(const std::string &str) return res; #else // Linux / macOS - std::wstring_convert> conv; - return conv.from_bytes(str); + std::size_t len = std::mbstowcs(nullptr, str.c_str(), 0); + + if (len == static_cast(-1)) + return L"Invalid UTF-8 string or invalid locale"; + + std::wstring result(len, L'\0'); + std::mbstowcs(result.data(), str.c_str(), len); + + return result; #endif // _WIN32 } diff --git a/StringUtil.h b/StringUtil.h index 365d5d8..905bff7 100644 --- a/StringUtil.h +++ b/StringUtil.h @@ -33,8 +33,8 @@ @brief Declaration of global string utility functions */ -#ifndef TimeUtil_h -#define TimeUtil_h +#ifndef StringUtil_h +#define StringUtil_h #include