utf8_validity.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. // Copyright 2022 Google LLC
  2. //
  3. // Use of this source code is governed by an MIT-style
  4. // license that can be found in the LICENSE file or at
  5. // https://opensource.org/licenses/MIT.
  6. /* This is a wrapper for the Google range-sse.cc algorithm which checks whether a
  7. * sequence of bytes is a valid UTF-8 sequence and finds the longest valid prefix of
  8. * the UTF-8 sequence.
  9. *
  10. * The key difference is that it checks for as much ASCII symbols as possible
  11. * and then falls back to the range-sse.cc algorithm. The changes to the
  12. * algorithm are cosmetic, mostly to trick the clang compiler to produce optimal
  13. * code.
  14. *
  15. * For API see the utf8_validity.h header.
  16. */
  17. #include "utf8_validity.h"
  18. #include <cstddef>
  19. #include <cstdint>
  20. #include "y_absl/strings/ascii.h"
  21. #include "y_absl/strings/string_view.h"
  22. #ifdef __SSE4_1__
  23. #include <emmintrin.h>
  24. #include <smmintrin.h>
  25. #include <tmmintrin.h>
  26. #endif
  27. namespace utf8_range {
  28. namespace {
  29. inline arc_ui64 UNALIGNED_LOAD64(const void* p) {
  30. arc_ui64 t;
  31. memcpy(&t, p, sizeof t);
  32. return t;
  33. }
  34. inline bool TrailByteOk(const char c) {
  35. return static_cast<int8_t>(c) <= static_cast<int8_t>(0xBF);
  36. }
  37. /* If ReturnPosition is false then it returns 1 if |data| is a valid utf8
  38. * sequence, otherwise returns 0.
  39. * If ReturnPosition is set to true, returns the length in bytes of the prefix
  40. of |data| that is all structurally valid UTF-8.
  41. */
  42. template <bool ReturnPosition>
  43. size_t ValidUTF8Span(const char* data, const char* end) {
  44. /* We return err_pos in the loop which is always 0 if !ReturnPosition */
  45. size_t err_pos = 0;
  46. size_t codepoint_bytes = 0;
  47. /* The early check is done because of early continue's on codepoints of all
  48. * sizes, i.e. we first check for ascii and if it is, we call continue, then
  49. * for 2 byte codepoints, etc. This is done in order to reduce indentation and
  50. * improve readability of the codepoint validity check.
  51. */
  52. while (data + codepoint_bytes < end) {
  53. if (ReturnPosition) {
  54. err_pos += codepoint_bytes;
  55. }
  56. data += codepoint_bytes;
  57. const size_t len = end - data;
  58. const unsigned char byte1 = data[0];
  59. /* We do not skip many ascii bytes at the same time as this function is
  60. used for tail checking (< 16 bytes) and for non x86 platforms. We also
  61. don't think that cases where non-ASCII codepoints are followed by ascii
  62. happen often. For small strings it also introduces some penalty. For
  63. purely ascii UTF8 strings (which is the overwhelming case) we call
  64. SkipAscii function which is multiplatform and extremely fast.
  65. */
  66. /* [00..7F] ASCII -> 1 byte */
  67. if (y_absl::ascii_isascii(byte1)) {
  68. codepoint_bytes = 1;
  69. continue;
  70. }
  71. /* [C2..DF], [80..BF] -> 2 bytes */
  72. if (len >= 2 && byte1 >= 0xC2 && byte1 <= 0xDF && TrailByteOk(data[1])) {
  73. codepoint_bytes = 2;
  74. continue;
  75. }
  76. if (len >= 3) {
  77. const unsigned char byte2 = data[1];
  78. const unsigned char byte3 = data[2];
  79. /* Is byte2, byte3 between [0x80, 0xBF]
  80. * Check for 0x80 was done above.
  81. */
  82. if (!TrailByteOk(byte2) || !TrailByteOk(byte3)) {
  83. return err_pos;
  84. }
  85. if (/* E0, A0..BF, 80..BF */
  86. ((byte1 == 0xE0 && byte2 >= 0xA0) ||
  87. /* E1..EC, 80..BF, 80..BF */
  88. (byte1 >= 0xE1 && byte1 <= 0xEC) ||
  89. /* ED, 80..9F, 80..BF */
  90. (byte1 == 0xED && byte2 <= 0x9F) ||
  91. /* EE..EF, 80..BF, 80..BF */
  92. (byte1 >= 0xEE && byte1 <= 0xEF))) {
  93. codepoint_bytes = 3;
  94. continue;
  95. }
  96. if (len >= 4) {
  97. const unsigned char byte4 = data[3];
  98. /* Is byte4 between 0x80 ~ 0xBF */
  99. if (!TrailByteOk(byte4)) {
  100. return err_pos;
  101. }
  102. if (/* F0, 90..BF, 80..BF, 80..BF */
  103. ((byte1 == 0xF0 && byte2 >= 0x90) ||
  104. /* F1..F3, 80..BF, 80..BF, 80..BF */
  105. (byte1 >= 0xF1 && byte1 <= 0xF3) ||
  106. /* F4, 80..8F, 80..BF, 80..BF */
  107. (byte1 == 0xF4 && byte2 <= 0x8F))) {
  108. codepoint_bytes = 4;
  109. continue;
  110. }
  111. }
  112. }
  113. return err_pos;
  114. }
  115. if (ReturnPosition) {
  116. err_pos += codepoint_bytes;
  117. }
  118. /* if ReturnPosition is false, this returns 1.
  119. * if ReturnPosition is true, this returns err_pos.
  120. */
  121. return err_pos + (1 - ReturnPosition);
  122. }
  123. /* Returns the number of bytes needed to skip backwards to get to the first
  124. byte of codepoint.
  125. */
  126. inline int CodepointSkipBackwards(arc_i32 codepoint_word) {
  127. const int8_t* const codepoint =
  128. reinterpret_cast<const int8_t*>(&codepoint_word);
  129. if (!TrailByteOk(codepoint[3])) {
  130. return 1;
  131. } else if (!TrailByteOk(codepoint[2])) {
  132. return 2;
  133. } else if (!TrailByteOk(codepoint[1])) {
  134. return 3;
  135. }
  136. return 0;
  137. }
  138. /* Skipping over ASCII as much as possible, per 8 bytes. It is intentional
  139. as most strings to check for validity consist only of 1 byte codepoints.
  140. */
  141. inline const char* SkipAscii(const char* data, const char* end) {
  142. while (8 <= end - data &&
  143. (UNALIGNED_LOAD64(data) & 0x8080808080808080) == 0) {
  144. data += 8;
  145. }
  146. while (data < end && y_absl::ascii_isascii(*data)) {
  147. ++data;
  148. }
  149. return data;
  150. }
  151. template <bool ReturnPosition>
  152. size_t ValidUTF8(const char* data, size_t len) {
  153. if (len == 0) return 1 - ReturnPosition;
  154. const char* const end = data + len;
  155. data = SkipAscii(data, end);
  156. /* SIMD algorithm always outperforms the naive version for any data of
  157. length >=16.
  158. */
  159. if (end - data < 16) {
  160. return (ReturnPosition ? (data - (end - len)) : 0) +
  161. ValidUTF8Span<ReturnPosition>(data, end);
  162. }
  163. #ifndef __SSE4_1__
  164. return (ReturnPosition ? (data - (end - len)) : 0) +
  165. ValidUTF8Span<ReturnPosition>(data, end);
  166. #else
  167. /* This code checks that utf-8 ranges are structurally valid 16 bytes at once
  168. * using superscalar instructions.
  169. * The mapping between ranges of codepoint and their corresponding utf-8
  170. * sequences is below.
  171. */
  172. /*
  173. * U+0000...U+007F 00...7F
  174. * U+0080...U+07FF C2...DF 80...BF
  175. * U+0800...U+0FFF E0 A0...BF 80...BF
  176. * U+1000...U+CFFF E1...EC 80...BF 80...BF
  177. * U+D000...U+D7FF ED 80...9F 80...BF
  178. * U+E000...U+FFFF EE...EF 80...BF 80...BF
  179. * U+10000...U+3FFFF F0 90...BF 80...BF 80...BF
  180. * U+40000...U+FFFFF F1...F3 80...BF 80...BF 80...BF
  181. * U+100000...U+10FFFF F4 80...8F 80...BF 80...BF
  182. */
  183. /* First we compute the type for each byte, as given by the table below.
  184. * This type will be used as an index later on.
  185. */
  186. /*
  187. * Index Min Max Byte Type
  188. * 0 00 7F Single byte sequence
  189. * 1,2,3 80 BF Second, third and fourth byte for many of the sequences.
  190. * 4 A0 BF Second byte after E0
  191. * 5 80 9F Second byte after ED
  192. * 6 90 BF Second byte after F0
  193. * 7 80 8F Second byte after F4
  194. * 8 C2 F4 First non ASCII byte
  195. * 9..15 7F 80 Invalid byte
  196. */
  197. /* After the first step we compute the index for all bytes, then we permute
  198. the bytes according to their indices to check the ranges from the range
  199. table.
  200. * The range for a given type can be found in the range_min_table and
  201. range_max_table, the range for type/index X is in range_min_table[X] ...
  202. range_max_table[X].
  203. */
  204. /* Algorithm:
  205. * Put index zero to all bytes.
  206. * Find all non ASCII characters, give them index 8.
  207. * For each tail byte in a codepoint sequence, give it an index corresponding
  208. to the 1 based index from the end.
  209. * If the first byte of the codepoint is in the [C0...DF] range, we write
  210. index 1 in the following byte.
  211. * If the first byte of the codepoint is in the range [E0...EF], we write
  212. indices 2 and 1 in the next two bytes.
  213. * If the first byte of the codepoint is in the range [F0...FF] we write
  214. indices 3,2,1 into the next three bytes.
  215. * For finding the number of bytes we need to look at high nibbles (4 bits)
  216. and do the lookup from the table, it can be done with shift by 4 + shuffle
  217. instructions. We call it `first_len`.
  218. * Then we shift first_len by 8 bits to get the indices of the 2nd bytes.
  219. * Saturating sub 1 and shift by 8 bits to get the indices of the 3rd bytes.
  220. * Again to get the indices of the 4th bytes.
  221. * Take OR of all that 4 values and check within range.
  222. */
  223. /* For example:
  224. * input C3 80 68 E2 80 20 A6 F0 A0 80 AC 20 F0 93 80 80
  225. * first_len 1 0 0 2 0 0 0 3 0 0 0 0 3 0 0 0
  226. * 1st byte 8 0 0 8 0 0 0 8 0 0 0 0 8 0 0 0
  227. * 2nd byte 0 1 0 0 2 0 0 0 3 0 0 0 0 3 0 0 // Shift + sub
  228. * 3rd byte 0 0 0 0 0 1 0 0 0 2 0 0 0 0 2 0 // Shift + sub
  229. * 4th byte 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 // Shift + sub
  230. * Index 8 1 0 8 2 1 0 8 3 2 1 0 8 3 2 1 // OR of results
  231. */
  232. /* Checking for errors:
  233. * Error checking is done by looking up the high nibble (4 bits) of each byte
  234. against an error checking table.
  235. * Because the lookup value for the second byte depends of the value of the
  236. first byte in codepoint, we use saturated operations to adjust the index.
  237. * Specifically we need to add 2 for E0, 3 for ED, 3 for F0 and 4 for F4 to
  238. match the correct index.
  239. * If we subtract from all bytes EF then EO -> 241, ED -> 254, F0 -> 1,
  240. F4 -> 5
  241. * Do saturating sub 240, then E0 -> 1, ED -> 14 and we can do lookup to
  242. match the adjustment
  243. * Add saturating 112, then F0 -> 113, F4 -> 117, all that were > 16 will
  244. be more 128 and lookup in ef_fe_table will return 0 but for F0
  245. and F4 it will be 4 and 5 accordingly
  246. */
  247. /*
  248. * Then just check the appropriate ranges with greater/smaller equal
  249. instructions. Check tail with a naive algorithm.
  250. * To save from previous 16 byte checks we just align previous_first_len to
  251. get correct continuations of the codepoints.
  252. */
  253. /*
  254. * Map high nibble of "First Byte" to legal character length minus 1
  255. * 0x00 ~ 0xBF --> 0
  256. * 0xC0 ~ 0xDF --> 1
  257. * 0xE0 ~ 0xEF --> 2
  258. * 0xF0 ~ 0xFF --> 3
  259. */
  260. const __m128i first_len_table =
  261. _mm_setr_epi8(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 3);
  262. /* Map "First Byte" to 8-th item of range table (0xC2 ~ 0xF4) */
  263. const __m128i first_range_table =
  264. _mm_setr_epi8(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8);
  265. /*
  266. * Range table, map range index to min and max values
  267. */
  268. const __m128i range_min_table =
  269. _mm_setr_epi8(0x00, 0x80, 0x80, 0x80, 0xA0, 0x80, 0x90, 0x80, 0xC2, 0x7F,
  270. 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F);
  271. const __m128i range_max_table =
  272. _mm_setr_epi8(0x7F, 0xBF, 0xBF, 0xBF, 0xBF, 0x9F, 0xBF, 0x8F, 0xF4, 0x80,
  273. 0x80, 0x80, 0x80, 0x80, 0x80, 0x80);
  274. /*
  275. * Tables for fast handling of four special First Bytes(E0,ED,F0,F4), after
  276. * which the Second Byte are not 80~BF. It contains "range index adjustment".
  277. * +------------+---------------+------------------+----------------+
  278. * | First Byte | original range| range adjustment | adjusted range |
  279. * +------------+---------------+------------------+----------------+
  280. * | E0 | 2 | 2 | 4 |
  281. * +------------+---------------+------------------+----------------+
  282. * | ED | 2 | 3 | 5 |
  283. * +------------+---------------+------------------+----------------+
  284. * | F0 | 3 | 3 | 6 |
  285. * +------------+---------------+------------------+----------------+
  286. * | F4 | 4 | 4 | 8 |
  287. * +------------+---------------+------------------+----------------+
  288. */
  289. /* df_ee_table[1] -> E0, df_ee_table[14] -> ED as ED - E0 = 13 */
  290. // The values represent the adjustment in the Range Index table for a correct
  291. // index.
  292. const __m128i df_ee_table =
  293. _mm_setr_epi8(0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0);
  294. /* ef_fe_table[1] -> F0, ef_fe_table[5] -> F4, F4 - F0 = 4 */
  295. // The values represent the adjustment in the Range Index table for a correct
  296. // index.
  297. const __m128i ef_fe_table =
  298. _mm_setr_epi8(0, 3, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  299. __m128i prev_input = _mm_set1_epi8(0);
  300. __m128i prev_first_len = _mm_set1_epi8(0);
  301. __m128i error = _mm_set1_epi8(0);
  302. while (end - data >= 16) {
  303. const __m128i input =
  304. _mm_loadu_si128(reinterpret_cast<const __m128i*>(data));
  305. /* high_nibbles = input >> 4 */
  306. const __m128i high_nibbles =
  307. _mm_and_si128(_mm_srli_epi16(input, 4), _mm_set1_epi8(0x0F));
  308. /* first_len = legal character length minus 1 */
  309. /* 0 for 00~7F, 1 for C0~DF, 2 for E0~EF, 3 for F0~FF */
  310. /* first_len = first_len_table[high_nibbles] */
  311. __m128i first_len = _mm_shuffle_epi8(first_len_table, high_nibbles);
  312. /* First Byte: set range index to 8 for bytes within 0xC0 ~ 0xFF */
  313. /* range = first_range_table[high_nibbles] */
  314. __m128i range = _mm_shuffle_epi8(first_range_table, high_nibbles);
  315. /* Second Byte: set range index to first_len */
  316. /* 0 for 00~7F, 1 for C0~DF, 2 for E0~EF, 3 for F0~FF */
  317. /* range |= (first_len, prev_first_len) << 1 byte */
  318. range = _mm_or_si128(range, _mm_alignr_epi8(first_len, prev_first_len, 15));
  319. /* Third Byte: set range index to saturate_sub(first_len, 1) */
  320. /* 0 for 00~7F, 0 for C0~DF, 1 for E0~EF, 2 for F0~FF */
  321. __m128i tmp1;
  322. __m128i tmp2;
  323. /* tmp1 = saturate_sub(first_len, 1) */
  324. tmp1 = _mm_subs_epu8(first_len, _mm_set1_epi8(1));
  325. /* tmp2 = saturate_sub(prev_first_len, 1) */
  326. tmp2 = _mm_subs_epu8(prev_first_len, _mm_set1_epi8(1));
  327. /* range |= (tmp1, tmp2) << 2 bytes */
  328. range = _mm_or_si128(range, _mm_alignr_epi8(tmp1, tmp2, 14));
  329. /* Fourth Byte: set range index to saturate_sub(first_len, 2) */
  330. /* 0 for 00~7F, 0 for C0~DF, 0 for E0~EF, 1 for F0~FF */
  331. /* tmp1 = saturate_sub(first_len, 2) */
  332. tmp1 = _mm_subs_epu8(first_len, _mm_set1_epi8(2));
  333. /* tmp2 = saturate_sub(prev_first_len, 2) */
  334. tmp2 = _mm_subs_epu8(prev_first_len, _mm_set1_epi8(2));
  335. /* range |= (tmp1, tmp2) << 3 bytes */
  336. range = _mm_or_si128(range, _mm_alignr_epi8(tmp1, tmp2, 13));
  337. /*
  338. * Now we have below range indices calculated
  339. * Correct cases:
  340. * - 8 for C0~FF
  341. * - 3 for 1st byte after F0~FF
  342. * - 2 for 1st byte after E0~EF or 2nd byte after F0~FF
  343. * - 1 for 1st byte after C0~DF or 2nd byte after E0~EF or
  344. * 3rd byte after F0~FF
  345. * - 0 for others
  346. * Error cases:
  347. * >9 for non ascii First Byte overlapping
  348. * E.g., F1 80 C2 90 --> 8 3 10 2, where 10 indicates error
  349. */
  350. /* Adjust Second Byte range for special First Bytes(E0,ED,F0,F4) */
  351. /* Overlaps lead to index 9~15, which are illegal in range table */
  352. __m128i shift1;
  353. __m128i pos;
  354. __m128i range2;
  355. /* shift1 = (input, prev_input) << 1 byte */
  356. shift1 = _mm_alignr_epi8(input, prev_input, 15);
  357. pos = _mm_sub_epi8(shift1, _mm_set1_epi8(0xEF));
  358. /*
  359. * shift1: | EF F0 ... FE | FF 00 ... ... DE | DF E0 ... EE |
  360. * pos: | 0 1 15 | 16 17 239| 240 241 255|
  361. * pos-240: | 0 0 0 | 0 0 0 | 0 1 15 |
  362. * pos+112: | 112 113 127| >= 128 | >= 128 |
  363. */
  364. tmp1 = _mm_subs_epu8(pos, _mm_set1_epi8(-16));
  365. range2 = _mm_shuffle_epi8(df_ee_table, tmp1);
  366. tmp2 = _mm_adds_epu8(pos, _mm_set1_epi8(112));
  367. range2 = _mm_add_epi8(range2, _mm_shuffle_epi8(ef_fe_table, tmp2));
  368. range = _mm_add_epi8(range, range2);
  369. /* Load min and max values per calculated range index */
  370. __m128i min_range = _mm_shuffle_epi8(range_min_table, range);
  371. __m128i max_range = _mm_shuffle_epi8(range_max_table, range);
  372. /* Check value range */
  373. if (ReturnPosition) {
  374. error = _mm_cmplt_epi8(input, min_range);
  375. error = _mm_or_si128(error, _mm_cmpgt_epi8(input, max_range));
  376. /* 5% performance drop from this conditional branch */
  377. if (!_mm_testz_si128(error, error)) {
  378. break;
  379. }
  380. } else {
  381. error = _mm_or_si128(error, _mm_cmplt_epi8(input, min_range));
  382. error = _mm_or_si128(error, _mm_cmpgt_epi8(input, max_range));
  383. }
  384. prev_input = input;
  385. prev_first_len = first_len;
  386. data += 16;
  387. }
  388. /* If we got to the end, we don't need to skip any bytes backwards */
  389. if (ReturnPosition && (data - (end - len)) == 0) {
  390. return ValidUTF8Span<true>(data, end);
  391. }
  392. /* Find previous codepoint (not 80~BF) */
  393. data -= CodepointSkipBackwards(_mm_extract_epi32(prev_input, 3));
  394. if (ReturnPosition) {
  395. return (data - (end - len)) + ValidUTF8Span<true>(data, end);
  396. }
  397. /* Test if there was any error */
  398. if (!_mm_testz_si128(error, error)) {
  399. return 0;
  400. }
  401. /* Check the tail */
  402. return ValidUTF8Span<false>(data, end);
  403. #endif
  404. }
  405. } // namespace
  406. bool IsStructurallyValid(y_absl::string_view str) {
  407. return ValidUTF8</*ReturnPosition=*/false>(str.data(), str.size());
  408. }
  409. size_t SpanStructurallyValid(y_absl::string_view str) {
  410. return ValidUTF8</*ReturnPosition=*/true>(str.data(), str.size());
  411. }
  412. } // namespace utf8_range