| 1 |
/* |
| 2 |
Returns a pair: the first unprocessed byte from buf and utf8_output |
| 3 |
A scalar routing should carry on the conversion of the tail. |
| 4 |
*/ |
| 5 |
|
| 6 |
std::pair<const char *, char *> |
| 7 |
lsx_convert_latin1_to_utf8(const char *latin1_input, size_t len, |
| 8 |
char *utf8_out) { |
| 9 |
uint8_t *utf8_output = reinterpret_cast<uint8_t *>(utf8_out); |
| 10 |
const char *end = latin1_input + len; |
| 11 |
|
| 12 |
__m128i zero = __lsx_vldi(0); |
| 13 |
// We always write 16 bytes, of which more than the first 8 bytes |
| 14 |
// are valid. A safety margin of 8 is more than sufficient. |
| 15 |
while (latin1_input + 16 <= end) { |
| 16 |
__m128i in8 = __lsx_vld(reinterpret_cast<const uint8_t *>(latin1_input), 0); |
| 17 |
uint32_t ascii = __lsx_vpickve2gr_hu(__lsx_vmskgez_b(in8), 0); |
| 18 |
if (ascii == 0xffff) { // ASCII fast path!!!! |
| 19 |
__lsx_vst(in8, utf8_output, 0); |
| 20 |
utf8_output += 16; |
| 21 |
latin1_input += 16; |
| 22 |
continue; |
| 23 |
} |
| 24 |
// We just fallback on UTF-16 code. This could be optimized/simplified |
| 25 |
// further. |
| 26 |
__m128i in16 = __lsx_vilvl_b(zero, in8); |
| 27 |
// 1. prepare 2-byte values |
| 28 |
// input 8-bit word : [aabb|bbbb] x 8 |
| 29 |
// expected output : [1100|00aa|10bb|bbbb] x 8 |
| 30 |
// t0 = [0000|00aa|bbbb|bb00] |
| 31 |
__m128i t0 = __lsx_vslli_h(in16, 2); |
| 32 |
// t1 = [0000|00aa|0000|0000] |
| 33 |
__m128i t1 = __lsx_vand_v(t0, __lsx_vldi(-2785)); |
| 34 |
// t3 = [0000|00aa|00bb|bbbb] |
| 35 |
__m128i t2 = __lsx_vbitsel_v(t1, in16, __lsx_vrepli_h(0x3f)); |
| 36 |
// t4 = [1100|00aa|10bb|bbbb] |
| 37 |
__m128i t3 = __lsx_vor_v(t2, __lsx_vreplgr2vr_h(uint16_t(0xc080))); |
| 38 |
// merge ASCII and 2-byte codewords |
| 39 |
__m128i one_byte_bytemask = __lsx_vsle_hu(in16, __lsx_vrepli_h(0x7F)); |
| 40 |
__m128i utf8_unpacked = __lsx_vbitsel_v(t3, in16, one_byte_bytemask); |
| 41 |
|
| 42 |
const uint8_t *row = &simdutf::tables::utf16_to_utf8::pack_1_2_utf8_bytes |
| 43 |
[lsx_1_2_utf8_bytes_mask[(ascii & 0xff)]][0]; |
| 44 |
__m128i shuffle = __lsx_vld(row + 1, 0); |
| 45 |
__m128i utf8_packed = __lsx_vshuf_b(zero, utf8_unpacked, shuffle); |
| 46 |
|
| 47 |
// store bytes |
| 48 |
__lsx_vst(utf8_packed, utf8_output, 0); |
| 49 |
// adjust pointers |
| 50 |
latin1_input += 8; |
| 51 |
utf8_output += row[0]; |
| 52 |
|
| 53 |
} // while |
| 54 |
|
| 55 |
return std::make_pair(latin1_input, reinterpret_cast<char *>(utf8_output)); |
| 56 |
} |