utf8.hpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #pragma once
  2. using uint = unsigned;
  3. namespace nall {
  4. //UTF-8 to UTF-16
  5. struct utf16_t {
  6. utf16_t(const char* s = "") { operator=(s); }
  7. ~utf16_t() { reset(); }
  8. utf16_t(const utf16_t&) = delete;
  9. auto operator=(const utf16_t&) -> utf16_t& = delete;
  10. auto operator=(const char* s) -> utf16_t& {
  11. reset();
  12. if(!s) s = "";
  13. length = MultiByteToWideChar(CP_UTF8, 0, s, -1, nullptr, 0);
  14. buffer = new wchar_t[length + 1];
  15. MultiByteToWideChar(CP_UTF8, 0, s, -1, buffer, length);
  16. buffer[length] = 0;
  17. return *this;
  18. }
  19. operator wchar_t*() { return buffer; }
  20. operator const wchar_t*() const { return buffer; }
  21. auto reset() -> void {
  22. delete[] buffer;
  23. length = 0;
  24. }
  25. auto data() -> wchar_t* { return buffer; }
  26. auto data() const -> const wchar_t* { return buffer; }
  27. auto size() const -> uint { return length; }
  28. private:
  29. wchar_t* buffer = nullptr;
  30. uint length = 0;
  31. };
  32. //UTF-16 to UTF-8
  33. struct utf8_t {
  34. utf8_t(const wchar_t* s = L"") { operator=(s); }
  35. ~utf8_t() { reset(); }
  36. utf8_t(const utf8_t&) = delete;
  37. auto operator=(const utf8_t&) -> utf8_t& = delete;
  38. auto operator=(const wchar_t* s) -> utf8_t& {
  39. reset();
  40. if(!s) s = L"";
  41. length = WideCharToMultiByte(CP_UTF8, 0, s, -1, nullptr, 0, nullptr, nullptr);
  42. buffer = new char[length + 1];
  43. WideCharToMultiByte(CP_UTF8, 0, s, -1, buffer, length, nullptr, nullptr);
  44. buffer[length] = 0;
  45. return *this;
  46. }
  47. auto reset() -> void {
  48. delete[] buffer;
  49. length = 0;
  50. }
  51. operator char*() { return buffer; }
  52. operator const char*() const { return buffer; }
  53. auto data() -> char* { return buffer; }
  54. auto data() const -> const char* { return buffer; }
  55. auto size() const -> uint { return length; }
  56. private:
  57. char* buffer = nullptr;
  58. uint length = 0;
  59. };
  60. inline auto utf8_arguments(int& argc, char**& argv) -> void {
  61. wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
  62. argv = new char*[argc + 1]();
  63. for(uint i = 0; i < argc; i++) {
  64. argv[i] = new char[PATH_MAX];
  65. strcpy(argv[i], nall::utf8_t(wargv[i]));
  66. }
  67. }
  68. }