strutils.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. #include "alstring.h"
  8. std::string wstr_to_utf8(std::wstring_view wstr)
  9. {
  10. std::string ret;
  11. const int len{WideCharToMultiByte(CP_UTF8, 0, wstr.data(), al::sizei(wstr), nullptr, 0,
  12. nullptr, nullptr)};
  13. if(len > 0)
  14. {
  15. ret.resize(static_cast<size_t>(len));
  16. WideCharToMultiByte(CP_UTF8, 0, wstr.data(), al::sizei(wstr), ret.data(), len,
  17. nullptr, nullptr);
  18. }
  19. return ret;
  20. }
  21. std::wstring utf8_to_wstr(std::string_view str)
  22. {
  23. std::wstring ret;
  24. const int len{MultiByteToWideChar(CP_UTF8, 0, str.data(), al::sizei(str), nullptr, 0)};
  25. if(len > 0)
  26. {
  27. ret.resize(static_cast<size_t>(len));
  28. MultiByteToWideChar(CP_UTF8, 0, str.data(), al::sizei(str), ret.data(), len);
  29. }
  30. return ret;
  31. }
  32. #endif
  33. namespace al {
  34. std::optional<std::string> getenv(const char *envname)
  35. {
  36. #ifdef _GAMING_XBOX
  37. const char *str{::getenv(envname)};
  38. #else
  39. const char *str{std::getenv(envname)};
  40. #endif
  41. if(str && *str != '\0')
  42. return str;
  43. return std::nullopt;
  44. }
  45. #ifdef _WIN32
  46. std::optional<std::wstring> getenv(const WCHAR *envname)
  47. {
  48. const WCHAR *str{_wgetenv(envname)};
  49. if(str && *str != L'\0')
  50. return str;
  51. return std::nullopt;
  52. }
  53. #endif
  54. } // namespace al