From 6ca1506935dc3ab160e811e55d6da85ee7c42136 Mon Sep 17 00:00:00 2001
From: Rolf Eike Beer <eike@sf-mail.de>
Date: Tue, 3 Oct 2017 00:37:24 +0200
Subject: [PATCH] SystemTools: make Getcwd() more efficient on Windows

Only do one conversion attempt and write that directly to the target buffer. Do
the uppercasing of the drive letter only in the ASCII domain, not in wide chars.
---
 SystemTools.cxx | 17 +++++++++++------
 1 file changed, 11 insertions(+), 6 deletions(-)

diff --git a/SystemTools.cxx b/SystemTools.cxx
index ecfa331..a24a326 100644
--- a/SystemTools.cxx
+++ b/SystemTools.cxx
@@ -20,6 +20,7 @@
 #include KWSYS_HEADER(SystemTools.hxx)
 #include KWSYS_HEADER(Directory.hxx)
 #include KWSYS_HEADER(FStream.hxx)
+#include KWSYS_HEADER(Encoding.h)
 #include KWSYS_HEADER(Encoding.hxx)
 
 #include <fstream>
@@ -227,13 +228,17 @@ inline const char* Getcwd(char* buf, unsigned int len)
 {
   std::vector<wchar_t> w_buf(len);
   if (_wgetcwd(&w_buf[0], len)) {
-    // make sure the drive letter is capital
-    if (wcslen(&w_buf[0]) > 1 && w_buf[1] == L':') {
-      w_buf[0] = towupper(w_buf[0]);
+    size_t nlen = kwsysEncoding_wcstombs(buf, &w_buf[0], len);
+    if (nlen == static_cast<size_t>(-1)) {
+      return 0;
+    }
+    if (nlen < len) {
+      // make sure the drive letter is capital
+      if (nlen > 1 && buf[1] == ':') {
+        buf[0] = toupper(buf[0]);
+      }
+      return buf;
     }
-    std::string tmp = KWSYS_NAMESPACE::Encoding::ToNarrow(&w_buf[0]);
-    strcpy(buf, tmp.c_str());
-    return buf;
   }
   return 0;
 }
-- 
GitLab