| 344 | |
| 345 | |
| 346 | std::string UTF32toUTF8(const std::u32string& s32) { |
| 347 | std::string s8; |
| 348 | // Pre-allocate maximum possible size |
| 349 | s8.reserve(s32.length() * 4); |
| 350 | |
| 351 | for (char32_t c : s32) { |
| 352 | // 7-bit codepoint to 1-byte sequence |
| 353 | if (c <= 0x7F) { |
| 354 | s8.push_back(c); |
| 355 | } |
| 356 | // 11-bit codepoint to 2-byte sequence |
| 357 | else if (c <= 0x7FF) { |
| 358 | s8.push_back(0xC0 | ((c >> 6) & 0x1F)); |
| 359 | s8.push_back(0x80 | (c & 0x3F)); |
| 360 | } |
| 361 | // 16-bit codepoint to 3-byte sequence |
| 362 | else if (c <= 0xFFFF) { |
| 363 | s8.push_back(0xE0 | ((c >> 12) & 0x0F)); |
| 364 | s8.push_back(0x80 | ((c >> 6) & 0x3F)); |
| 365 | s8.push_back(0x80 | (c & 0x3F)); |
| 366 | } |
| 367 | // 21-bit codepoint to 4-byte sequence |
| 368 | else if (c <= 0x10FFFF) { |
| 369 | s8.push_back(0xF0 | ((c >> 18) & 0x07)); |
| 370 | s8.push_back(0x80 | ((c >> 12) & 0x3F)); |
| 371 | s8.push_back(0x80 | ((c >> 6) & 0x3F)); |
| 372 | s8.push_back(0x80 | (c & 0x3F)); |
| 373 | } |
| 374 | // invalid codepoint |
| 375 | else { |
| 376 | // Ignore character |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | s8.shrink_to_fit(); |
| 381 | return s8; |
| 382 | } |
| 383 | |
| 384 | |
| 385 | std::u32string UTF8toUTF32(const std::string& s8) { |