1#ifndef SIMDUTF_VALID_UTF16_TO_UTF8_H
2#define SIMDUTF_VALID_UTF16_TO_UTF8_H
9namespace utf16_to_utf8 {
11template <endianness big_endian,
typename InputPtr,
typename OutputPtr>
12#if SIMDUTF_CPLUSPLUS20
13 requires(simdutf::detail::indexes_into_utf16<InputPtr> &&
14 simdutf::detail::index_assignable_from_char<OutputPtr>)
16simdutf_constexpr23
size_t convert_valid(InputPtr data,
size_t len,
17 OutputPtr utf8_output) {
19 auto start = utf8_output;
21#if SIMDUTF_CPLUSPLUS23
29 ::memcpy(&v, data + pos,
sizeof(uint64_t));
30 if constexpr (!match_system(big_endian)) {
31 v = (v >> 8) | (v << (64 - 8));
33 if ((v & 0xFF80FF80FF80FF80) == 0) {
34 size_t final_pos = pos + 4;
35 while (pos < final_pos) {
36 *utf8_output++ = !match_system(big_endian)
37 ? char(u16_swap_bytes(data[pos]))
47 !match_system(big_endian) ? u16_swap_bytes(data[pos]) : data[pos];
48 if ((word & 0xFF80) == 0) {
50 *utf8_output++ = char(word);
52 }
else if ((word & 0xF800) == 0) {
55 *utf8_output++ = char((word >> 6) | 0b11000000);
56 *utf8_output++ = char((word & 0b111111) | 0b10000000);
58 }
else if ((word & 0xF800) != 0xD800) {
61 *utf8_output++ = char((word >> 12) | 0b11100000);
62 *utf8_output++ = char(((word >> 6) & 0b111111) | 0b10000000);
63 *utf8_output++ = char((word & 0b111111) | 0b10000000);
67 uint16_t diff = uint16_t(word - 0xD800);
71 uint16_t next_word = !match_system(big_endian)
72 ? u16_swap_bytes(data[pos + 1])
74 uint16_t diff2 = uint16_t(next_word - 0xDC00);
75 uint32_t value = (diff << 10) + diff2 + 0x10000;
78 *utf8_output++ = char((value >> 18) | 0b11110000);
79 *utf8_output++ = char(((value >> 12) & 0b111111) | 0b10000000);
80 *utf8_output++ = char(((value >> 6) & 0b111111) | 0b10000000);
81 *utf8_output++ = char((value & 0b111111) | 0b10000000);
85 return utf8_output - start;
helpers placed in namespace detail are not a part of the public API