Convert a unicode code point into a UTF-8 representation by appending it to a string. Returns the number of bytes generated.
| 482 | // Convert a unicode code point into a UTF-8 representation by appending it |
| 483 | // to a string. Returns the number of bytes generated. |
| 484 | inline int ToUTF8(uint32_t ucc, std::string *out) { |
| 485 | FLATBUFFERS_ASSERT(!(ucc & 0x80000000)); // Top bit can't be set. |
| 486 | // 6 possible encodings: http://en.wikipedia.org/wiki/UTF-8 |
| 487 | for (int i = 0; i < 6; i++) { |
| 488 | // Max bits this encoding can represent. |
| 489 | uint32_t max_bits = 6 + i * 5 + static_cast<int>(!i); |
| 490 | if (ucc < (1u << max_bits)) { // does it fit? |
| 491 | // Remaining bits not encoded in the first byte, store 6 bits each |
| 492 | uint32_t remain_bits = i * 6; |
| 493 | // Store first byte: |
| 494 | (*out) += static_cast<char>((0xFE << (max_bits - remain_bits)) | |
| 495 | (ucc >> remain_bits)); |
| 496 | // Store remaining bytes: |
| 497 | for (int j = i - 1; j >= 0; j--) { |
| 498 | (*out) += static_cast<char>(((ucc >> (j * 6)) & 0x3F) | 0x80); |
| 499 | } |
| 500 | return i + 1; // Return the number of bytes added. |
| 501 | } |
| 502 | } |
| 503 | FLATBUFFERS_ASSERT(0); // Impossible to arrive here. |
| 504 | return -1; |
| 505 | } |
| 506 | |
| 507 | // Converts whatever prefix of the incoming string corresponds to a valid |
| 508 | // UTF-8 sequence into a unicode code. The incoming pointer will have been |