Support unicode APIs for LabVIEW

This commit is contained in:
2026-04-06 14:20:43 +10:00
parent 091a61d2be
commit b98aed21bf
4 changed files with 98 additions and 2 deletions

View File

@@ -1002,5 +1002,55 @@ namespace ANSCENTER
return utf8Str;
#endif
}
std::string ANSUtilities::ConvertUTF16LEToUnicodeEscapes(const char* utf16leBytes, int byteLen) {
if (!utf16leBytes || byteLen <= 0) return "";
int offset = 0;
// Strip BOM (FF FE) if present
if (byteLen >= 2 &&
static_cast<unsigned char>(utf16leBytes[0]) == 0xFF &&
static_cast<unsigned char>(utf16leBytes[1]) == 0xFE) {
offset = 2;
}
int remaining = byteLen - offset;
if (remaining <= 0 || remaining % 2 != 0) return "";
std::string result;
result.reserve(remaining * 3);
for (int i = offset; i + 1 < byteLen; i += 2) {
uint16_t codepoint = static_cast<unsigned char>(utf16leBytes[i])
| (static_cast<unsigned char>(utf16leBytes[i + 1]) << 8);
if (codepoint >= 0x20 && codepoint <= 0x7E) {
result += static_cast<char>(codepoint);
} else {
char buf[7];
snprintf(buf, sizeof(buf), "\\u%04X", codepoint);
result += buf;
}
}
return result;
}
std::string ANSUtilities::ConvertUnicodeEscapesToUTF8(const std::string& escapedStr) {
if (escapedStr.empty()) return "";
// First decode \uXXXX to UTF-16LE, then convert to UTF-8
std::string utf16le;
utf16le.reserve(escapedStr.size() * 2);
size_t i = 0;
while (i < escapedStr.size()) {
if (i + 5 < escapedStr.size() && escapedStr[i] == '\\' && escapedStr[i + 1] == 'u') {
char hex[5] = { escapedStr[i + 2], escapedStr[i + 3], escapedStr[i + 4], escapedStr[i + 5], 0 };
uint16_t codepoint = (uint16_t)strtoul(hex, nullptr, 16);
utf16le += static_cast<char>(codepoint & 0xFF);
utf16le += static_cast<char>((codepoint >> 8) & 0xFF);
i += 6;
} else {
utf16le += escapedStr[i];
utf16le += '\0';
i++;
}
}
return ConvertUTF16LEToUTF8(utf16le.data(), (int)utf16le.size());
}
}