From 981d02e4112645fe6bb7a586a868f00a8aeac0ea Mon Sep 17 00:00:00 2001 From: Adam Hojka Date: Sat, 11 Jun 2022 18:30:26 +0200 Subject: [PATCH] Custom wstring to UTF-8 string conversion function (codecvt may not be included in some toolchains and was deprecated in C++17 anyway). --- project/src/ExternalInterface.cpp | 62 ++++++++++++++++++++++++++----- 1 file changed, 53 insertions(+), 9 deletions(-) diff --git a/project/src/ExternalInterface.cpp b/project/src/ExternalInterface.cpp index 371d03fc5..1b70d43fa 100644 --- a/project/src/ExternalInterface.cpp +++ b/project/src/ExternalInterface.cpp @@ -48,8 +48,8 @@ #include #include +#ifdef HX_WINDOWS #include -#ifndef ANDROID #include #endif #include @@ -137,14 +137,58 @@ namespace lime { std::string wstring_utf8 (const std::wstring& val) { - #ifdef ANDROID - struct codecvt : public std::codecvt { - ~codecvt () = default; - }; - return std::wstring_convert ().to_bytes (val); - #else - return std::wstring_convert> ().to_bytes (val); - #endif + std::string out; + unsigned int codepoint = 0; + + for (const wchar_t chr : val) { + + if (chr >= 0xd800 && chr <= 0xdbff) { + + codepoint = ((chr - 0xd800) << 10) + 0x10000; + + } else { + + if (chr >= 0xdc00 && chr <= 0xdfff) { + + codepoint |= chr - 0xdc00; + + } else { + + codepoint = chr; + + } + + if (codepoint <= 0x7f) { + + out.append (1, static_cast (codepoint)); + + } else if (codepoint <= 0x7ff) { + + out.append (1, static_cast (0xc0 | ((codepoint >> 6) & 0x1f))); + out.append (1, static_cast (0x80 | (codepoint & 0x3f))); + + } else if (codepoint <= 0xffff) { + + out.append (1, static_cast (0xe0 | ((codepoint >> 12) & 0x0f))); + out.append (1, static_cast (0x80 | ((codepoint >> 6) & 0x3f))); + out.append (1, static_cast (0x80 | (codepoint & 0x3f))); + + } else { + + out.append (1, static_cast (0xf0 | ((codepoint >> 18) & 0x07))); + out.append (1, static_cast (0x80 | ((codepoint >> 12) & 0x3f))); + out.append (1, static_cast (0x80 | ((codepoint >> 6) & 0x3f))); + out.append (1, static_cast (0x80 | (codepoint & 0x3f))); + + } + + codepoint = 0; + + } + + } + + return out; }