simdutf 9.0.0
Unicode at GB/s.
Loading...
Searching...
No Matches
valid_utf16_to_utf8.h
1#ifndef SIMDUTF_VALID_UTF16_TO_UTF8_H
2#define SIMDUTF_VALID_UTF16_TO_UTF8_H
3
4#include <cstring>
5
6namespace simdutf {
7namespace scalar {
8namespace {
9namespace utf16_to_utf8 {
10
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>)
15#endif
16simdutf_constexpr23 size_t convert_valid(InputPtr data, size_t len,
17 OutputPtr utf8_output) {
18 size_t pos = 0;
19 auto start = utf8_output;
20 while (pos < len) {
21#if SIMDUTF_CPLUSPLUS23
22 if !consteval
23#endif
24 {
25 // try to convert the next block of 4 ASCII characters
26 if (pos + 4 <= len) { // if it is safe to read 8 more bytes, check that
27 // they are ascii
28 uint64_t v;
29 ::memcpy(&v, data + pos, sizeof(uint64_t));
30 if constexpr (!match_system(big_endian)) {
31 v = (v >> 8) | (v << (64 - 8));
32 }
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]))
38 : char(data[pos]);
39 pos++;
40 }
41 continue;
42 }
43 }
44 }
45
46 uint16_t word =
47 !match_system(big_endian) ? u16_swap_bytes(data[pos]) : data[pos];
48 if ((word & 0xFF80) == 0) {
49 // will generate one UTF-8 bytes
50 *utf8_output++ = char(word);
51 pos++;
52 } else if ((word & 0xF800) == 0) {
53 // will generate two UTF-8 bytes
54 // we have 0b110XXXXX 0b10XXXXXX
55 *utf8_output++ = char((word >> 6) | 0b11000000);
56 *utf8_output++ = char((word & 0b111111) | 0b10000000);
57 pos++;
58 } else if ((word & 0xF800) != 0xD800) {
59 // will generate three UTF-8 bytes
60 // we have 0b1110XXXX 0b10XXXXXX 0b10XXXXXX
61 *utf8_output++ = char((word >> 12) | 0b11100000);
62 *utf8_output++ = char(((word >> 6) & 0b111111) | 0b10000000);
63 *utf8_output++ = char((word & 0b111111) | 0b10000000);
64 pos++;
65 } else {
66 // must be a surrogate pair
67 uint16_t diff = uint16_t(word - 0xD800);
68 if (pos + 1 >= len) {
69 return 0;
70 } // minimal bound checking
71 uint16_t next_word = !match_system(big_endian)
72 ? u16_swap_bytes(data[pos + 1])
73 : data[pos + 1];
74 uint16_t diff2 = uint16_t(next_word - 0xDC00);
75 uint32_t value = (diff << 10) + diff2 + 0x10000;
76 // will generate four UTF-8 bytes
77 // we have 0b11110XXX 0b10XXXXXX 0b10XXXXXX 0b10XXXXXX
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);
82 pos += 2;
83 }
84 }
85 return utf8_output - start;
86}
87
88} // namespace utf16_to_utf8
89} // unnamed namespace
90} // namespace scalar
91} // namespace simdutf
92
93#endif
helpers placed in namespace detail are not a part of the public API