strutils.cpp 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include "config.h"
  2. #include "strutils.h"
  3. #include <cstdlib>
  4. #ifdef _WIN32
  5. #define WIN32_LEAN_AND_MEAN
  6. #include <windows.h>
  7. std::string wstr_to_utf8(const WCHAR *wstr)
  8. {
  9. std::string ret;
  10. int len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, nullptr, 0, nullptr, nullptr);
  11. if(len > 0)
  12. {
  13. ret.resize(len);
  14. WideCharToMultiByte(CP_UTF8, 0, wstr, -1, &ret[0], len, nullptr, nullptr);
  15. ret.pop_back();
  16. }
  17. return ret;
  18. }
  19. std::wstring utf8_to_wstr(const char *str)
  20. {
  21. std::wstring ret;
  22. int len = MultiByteToWideChar(CP_UTF8, 0, str, -1, nullptr, 0);
  23. if(len > 0)
  24. {
  25. ret.resize(len);
  26. MultiByteToWideChar(CP_UTF8, 0, str, -1, &ret[0], len);
  27. ret.pop_back();
  28. }
  29. return ret;
  30. }
  31. #endif
  32. namespace al {
  33. al::optional<std::string> getenv(const char *envname)
  34. {
  35. const char *str{std::getenv(envname)};
  36. if(str && str[0] != '\0') return str;
  37. return al::nullopt;
  38. }
  39. #ifdef _WIN32
  40. al::optional<std::wstring> getenv(const WCHAR *envname)
  41. {
  42. const WCHAR *str{_wgetenv(envname)};
  43. if(str && str[0] != L'\0') return str;
  44. return al::nullopt;
  45. }
  46. #endif
  47. } // namespace al