Skip to content

Commit 49ee242

Browse files
committed
fix wide-narrow conversion for utf-8 strings
1 parent 7982cac commit 49ee242

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

IntelPresentMon/CommonUtilities/str/String.cpp

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
// Copyright (C) 2022 Intel Corporation
22
// SPDX-License-Identifier: MIT
33
#include "String.h"
4-
#include <stdlib.h>
54
#include <sstream>
65
#include <iomanip>
6+
// TODO: replace with with properly wrapped winapi include
7+
#include <Windows.h>
78

89
namespace pmon::util::str
910
{
@@ -27,25 +28,34 @@ namespace pmon::util::str
2728

2829
std::wstring ToWide(const std::string& narrow)
2930
{
31+
if (narrow.empty()) {
32+
return {};
33+
}
3034
std::wstring wide;
35+
// TODO: replace with resize_and_overwrite when it becomes widely available
3136
wide.resize(narrow.size() + 1);
32-
size_t actual;
33-
mbstowcs_s(&actual, wide.data(), wide.size(), narrow.c_str(), _TRUNCATE);
34-
if (actual > 0)
35-
{
36-
wide.resize(actual - 1);
37+
const auto actual = MultiByteToWideChar(CP_UTF8, 0, narrow.data(), (int)narrow.size(), wide.data(), (int)wide.size());
38+
if (actual > 0) {
39+
wide.resize(actual);
3740
return wide;
3841
}
42+
// TODO: log error here
3943
return {};
4044
}
4145

4246
std::string ToNarrow(const std::wstring& wide)
4347
{
4448
std::string narrow;
49+
// TODO: replace with resize_and_overwrite when it becomes widely available
4550
narrow.resize(wide.size() * 2);
46-
size_t actual;
47-
wcstombs_s(&actual, narrow.data(), narrow.size(), wide.c_str(), _TRUNCATE);
48-
narrow.resize(actual - 1);
49-
return narrow;
51+
const auto actual = WideCharToMultiByte(CP_UTF8, 0, wide.data(), (int)wide.size(),
52+
narrow.data(), (int)narrow.size(), nullptr, nullptr);
53+
if (actual > 0) {
54+
narrow.resize(actual);
55+
return narrow;
56+
}
57+
// TODO: (maybe) check for insufficient buffer error and do redo with two-pass (or just double buffer again)
58+
// TODO: log error here
59+
return {};
5060
}
5161
}

0 commit comments

Comments
 (0)