aboutsummaryrefslogtreecommitdiff
path: root/src/common/windows/string_utils.cc
diff options
context:
space:
mode:
Diffstat (limited to 'src/common/windows/string_utils.cc')
-rw-r--r--src/common/windows/string_utils.cc59
1 files changed, 50 insertions, 9 deletions
diff --git a/src/common/windows/string_utils.cc b/src/common/windows/string_utils.cc
index 5d464802..e6ffa082 100644
--- a/src/common/windows/string_utils.cc
+++ b/src/common/windows/string_utils.cc
@@ -28,6 +28,7 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <cassert>
+#include <vector>
#include "common/windows/string_utils-inl.h"
@@ -55,6 +56,7 @@ bool WindowsStringUtils::safe_mbstowcs(const string &mbs, wstring *wcs) {
if ((err = mbstowcs_s(&wcs_length, NULL, 0, mbs.c_str(), _TRUNCATE)) != 0) {
return false;
}
+ assert(wcs_length > 0);
#else // _MSC_VER >= 1400
if ((wcs_length = mbstowcs(NULL, mbs.c_str(), mbs.length())) < 0) {
return false;
@@ -64,28 +66,67 @@ bool WindowsStringUtils::safe_mbstowcs(const string &mbs, wstring *wcs) {
++wcs_length;
#endif // _MSC_VER >= 1400
- // TODO(mmentovai): move scoped_ptr into common and use it for wcs_c.
- wchar_t *wcs_c = new wchar_t[wcs_length];
+ std::vector<wchar_t> wcs_v(wcs_length);
// Now, convert.
#if _MSC_VER >= 1400 // MSVC 2005/8
- if ((err = mbstowcs_s(NULL, wcs_c, wcs_length, mbs.c_str(),
+ if ((err = mbstowcs_s(NULL, &wcs_v[0], wcs_length, mbs.c_str(),
_TRUNCATE)) != 0) {
- delete[] wcs_c;
return false;
}
#else // _MSC_VER >= 1400
- if (mbstowcs(wcs_c, mbs.c_str(), mbs.length()) < 0) {
- delete[] wcs_c;
+ if (mbstowcs(&wcs_v[0], mbs.c_str(), mbs.length()) < 0) {
return false;
}
// Ensure presence of 0-terminator.
- wcs_c[wcs_length - 1] = '\0';
+ wcs_v[wcs_length - 1] = '\0';
#endif // _MSC_VER >= 1400
- *wcs = wcs_c;
- delete[] wcs_c;
+ *wcs = &wcs_v[0];
+ return true;
+}
+
+// static
+bool WindowsStringUtils::safe_wcstombs(const wstring &wcs, string *mbs) {
+ assert(mbs);
+
+ // First, determine the length of the destination buffer.
+ size_t mbs_length;
+
+#if _MSC_VER >= 1400 // MSVC 2005/8
+ errno_t err;
+ if ((err = wcstombs_s(&mbs_length, NULL, 0, wcs.c_str(), _TRUNCATE)) != 0) {
+ return false;
+ }
+ assert(mbs_length > 0);
+#else // _MSC_VER >= 1400
+ if ((mbs_length = wcstombs(NULL, wcs.c_str(), wcs.length())) < 0) {
+ return false;
+ }
+
+ // Leave space for the 0-terminator.
+ ++mbs_length;
+#endif // _MSC_VER >= 1400
+
+ std::vector<char> mbs_v(mbs_length);
+
+ // Now, convert.
+#if _MSC_VER >= 1400 // MSVC 2005/8
+ if ((err = wcstombs_s(NULL, &mbs_v[0], mbs_length, wcs.c_str(),
+ _TRUNCATE)) != 0) {
+ return false;
+ }
+#else // _MSC_VER >= 1400
+ if (wcstombs(&mbs_v[0], wcs.c_str(), wcs.length()) < 0) {
+ return false;
+ }
+
+ // Ensure presence of 0-terminator.
+ mbs_v[mbs_length - 1] = '\0';
+#endif // _MSC_VER >= 1400
+
+ *mbs = &mbs_v[0];
return true;
}