1#ifndef SIMDUTF_VALID_UTF16_TO_UTF8_H
2#define SIMDUTF_VALID_UTF16_TO_UTF8_H
7namespace utf16_to_utf8 {
9template <endianness big_endian,
typename InputPtr,
typename OutputPtr>
10#if SIMDUTF_CPLUSPLUS20
11 requires(simdutf::detail::indexes_into_utf16<InputPtr> &&
12 simdutf::detail::index_assignable_from_char<OutputPtr>)
14simdutf_constexpr23
size_t convert_valid(InputPtr data,
size_t len,
15 OutputPtr utf8_output) {
17 auto start = utf8_output;
19#if SIMDUTF_CPLUSPLUS23
27 ::memcpy(&v, data + pos,
sizeof(uint64_t));
28 if simdutf_constexpr (!match_system(big_endian)) {
29 v = (v >> 8) | (v << (64 - 8));
31 if ((v & 0xFF80FF80FF80FF80) == 0) {
32 size_t final_pos = pos + 4;
33 while (pos < final_pos) {
34 *utf8_output++ = !match_system(big_endian)
35 ? char(u16_swap_bytes(data[pos]))
45 !match_system(big_endian) ? u16_swap_bytes(data[pos]) : data[pos];
46 if ((word & 0xFF80) == 0) {
48 *utf8_output++ = char(word);
50 }
else if ((word & 0xF800) == 0) {
53 *utf8_output++ = char((word >> 6) | 0b11000000);
54 *utf8_output++ = char((word & 0b111111) | 0b10000000);
56 }
else if ((word & 0xF800) != 0xD800) {
59 *utf8_output++ = char((word >> 12) | 0b11100000);
60 *utf8_output++ = char(((word >> 6) & 0b111111) | 0b10000000);
61 *utf8_output++ = char((word & 0b111111) | 0b10000000);
65 uint16_t diff = uint16_t(word - 0xD800);
69 uint16_t next_word = !match_system(big_endian)
70 ? u16_swap_bytes(data[pos + 1])
72 uint16_t diff2 = uint16_t(next_word - 0xDC00);
73 uint32_t value = (diff << 10) + diff2 + 0x10000;
76 *utf8_output++ = char((value >> 18) | 0b11110000);
77 *utf8_output++ = char(((value >> 12) & 0b111111) | 0b10000000);
78 *utf8_output++ = char(((value >> 6) & 0b111111) | 0b10000000);
79 *utf8_output++ = char((value & 0b111111) | 0b10000000);
83 return utf8_output - start;