win_utils.cc 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #include "./win_utils.hh"
  2. std::wstring utf8ToUtf16(std::string input) {
  3. unsigned int len = MultiByteToWideChar(CP_UTF8, 0, input.c_str(), -1, NULL, 0);
  4. WCHAR *output = new WCHAR[len];
  5. MultiByteToWideChar(CP_UTF8, 0, input.c_str(), -1, output, len);
  6. std::wstring res(output);
  7. delete output;
  8. return res;
  9. }
  10. std::string utf16ToUtf8(const WCHAR *input, size_t length) {
  11. unsigned int len = WideCharToMultiByte(CP_UTF8, 0, input, length, NULL, 0, NULL, NULL);
  12. char *output = new char[len + 1];
  13. WideCharToMultiByte(CP_UTF8, 0, input, length, output, len, NULL, NULL);
  14. output[len] = '\0';
  15. std::string res(output);
  16. delete output;
  17. return res;
  18. }
  19. std::string normalizePath(std::string path) {
  20. // Prevent truncation to MAX_PATH characters by adding the \\?\ prefix
  21. std::wstring p = utf8ToUtf16("\\\\?\\" + path);
  22. // Get the required length for the output
  23. unsigned int len = GetLongPathNameW(p.data(), NULL, 0);
  24. if (!len) {
  25. return path;
  26. }
  27. // Allocate output array and get long path
  28. WCHAR *output = new WCHAR[len];
  29. len = GetLongPathNameW(p.data(), output, len);
  30. if (!len) {
  31. delete output;
  32. return path;
  33. }
  34. // Convert back to utf8
  35. std::string res = utf16ToUtf8(output + 4, len - 4);
  36. delete output;
  37. return res;
  38. }