1 // Adapted from https://github.com/lemire/fastvalidate-utf-8
2 
3 #ifdef __x86_64__
4 
5 #include <stdio.h>
6 #include <stddef.h>
7 #include <stdint.h>
8 #include <string.h>
9 #include <x86intrin.h>
10 
11 /*
12  * legal utf-8 byte sequence
13  * http://www.unicode.org/versions/Unicode6.0.0/ch03.pdf - page 94
14  *
15  *  Code Points        1st       2s       3s       4s
16  * U+0000..U+007F     00..7F
17  * U+0080..U+07FF     C2..DF   80..BF
18  * U+0800..U+0FFF     E0       A0..BF   80..BF
19  * U+1000..U+CFFF     E1..EC   80..BF   80..BF
20  * U+D000..U+D7FF     ED       80..9F   80..BF
21  * U+E000..U+FFFF     EE..EF   80..BF   80..BF
22  * U+10000..U+3FFFF   F0       90..BF   80..BF   80..BF
23  * U+40000..U+FFFFF   F1..F3   80..BF   80..BF   80..BF
24  * U+100000..U+10FFFF F4       80..8F   80..BF   80..BF
25  *
26  */
27 
28 #if 0
29 static void print128(const char *s, const __m128i *v128)
30 {
31   const unsigned char *v8 = (const unsigned char *)v128;
32   if (s)
33     printf("%s: ", s);
34   for (int i = 0; i < 16; i++)
35     printf("%02x ", v8[i]);
36   printf("\n");
37 }
38 #endif
39 
40 // all byte values must be no larger than 0xF4
checkSmallerThan0xF4(__m128i current_bytes,__m128i * has_error)41 static inline void checkSmallerThan0xF4(__m128i current_bytes,
42                                         __m128i *has_error) {
43   // unsigned, saturates to 0 below max
44   *has_error = _mm_or_si128(*has_error,
45                             _mm_subs_epu8(current_bytes, _mm_set1_epi8(0xF4)));
46 }
47 
continuationLengths(__m128i high_nibbles)48 static inline __m128i continuationLengths(__m128i high_nibbles) {
49   return _mm_shuffle_epi8(
50       _mm_setr_epi8(1, 1, 1, 1, 1, 1, 1, 1, // 0xxx (ASCII)
51                     0, 0, 0, 0,             // 10xx (continuation)
52                     2, 2,                   // 110x
53                     3,                      // 1110
54                     4), // 1111, next should be 0 (not checked here)
55       high_nibbles);
56 }
57 
carryContinuations(__m128i initial_lengths,__m128i previous_carries)58 static inline __m128i carryContinuations(__m128i initial_lengths,
59                                          __m128i previous_carries) {
60 
61   __m128i right1 =
62       _mm_subs_epu8(_mm_alignr_epi8(initial_lengths, previous_carries, 16 - 1),
63                     _mm_set1_epi8(1));
64   __m128i sum = _mm_add_epi8(initial_lengths, right1);
65 
66   __m128i right2 = _mm_subs_epu8(_mm_alignr_epi8(sum, previous_carries, 16 - 2),
67                                  _mm_set1_epi8(2));
68   return _mm_add_epi8(sum, right2);
69 }
70 
checkContinuations(__m128i initial_lengths,__m128i carries,__m128i * has_error)71 static inline void checkContinuations(__m128i initial_lengths, __m128i carries,
72                                       __m128i *has_error) {
73 
74   // overlap || underlap
75   // carry > length && length > 0 || !(carry > length) && !(length > 0)
76   // (carries > length) == (lengths > 0)
77   __m128i overunder =
78       _mm_cmpeq_epi8(_mm_cmpgt_epi8(carries, initial_lengths),
79                      _mm_cmpgt_epi8(initial_lengths, _mm_setzero_si128()));
80 
81   *has_error = _mm_or_si128(*has_error, overunder);
82 }
83 
84 // when 0xED is found, next byte must be no larger than 0x9F
85 // when 0xF4 is found, next byte must be no larger than 0x8F
86 // next byte must be continuation, ie sign bit is set, so signed < is ok
checkFirstContinuationMax(__m128i current_bytes,__m128i off1_current_bytes,__m128i * has_error)87 static inline void checkFirstContinuationMax(__m128i current_bytes,
88                                              __m128i off1_current_bytes,
89                                              __m128i *has_error) {
90   __m128i maskED = _mm_cmpeq_epi8(off1_current_bytes, _mm_set1_epi8(0xED));
91   __m128i maskF4 = _mm_cmpeq_epi8(off1_current_bytes, _mm_set1_epi8(0xF4));
92 
93   __m128i badfollowED =
94       _mm_and_si128(_mm_cmpgt_epi8(current_bytes, _mm_set1_epi8(0x9F)), maskED);
95   __m128i badfollowF4 =
96       _mm_and_si128(_mm_cmpgt_epi8(current_bytes, _mm_set1_epi8(0x8F)), maskF4);
97 
98   *has_error = _mm_or_si128(*has_error, _mm_or_si128(badfollowED, badfollowF4));
99 }
100 
101 // map off1_hibits => error condition
102 // hibits     off1    cur
103 // C       => < C2 && true
104 // E       => < E1 && < A0
105 // F       => < F1 && < 90
106 // else      false && false
checkOverlong(__m128i current_bytes,__m128i off1_current_bytes,__m128i hibits,__m128i previous_hibits,__m128i * has_error)107 static inline void checkOverlong(__m128i current_bytes,
108                                  __m128i off1_current_bytes, __m128i hibits,
109                                  __m128i previous_hibits, __m128i *has_error) {
110   __m128i off1_hibits = _mm_alignr_epi8(hibits, previous_hibits, 16 - 1);
111   __m128i initial_mins = _mm_shuffle_epi8(
112       _mm_setr_epi8(-128, -128, -128, -128, -128, -128, -128, -128, -128, -128,
113                     -128, -128, // 10xx => false
114                     0xC2, -128, // 110x
115                     0xE1,       // 1110
116                     0xF1),
117       off1_hibits);
118 
119   __m128i initial_under = _mm_cmpgt_epi8(initial_mins, off1_current_bytes);
120 
121   __m128i second_mins = _mm_shuffle_epi8(
122       _mm_setr_epi8(-128, -128, -128, -128, -128, -128, -128, -128, -128, -128,
123                     -128, -128, // 10xx => false
124                     127, 127,   // 110x => true
125                     0xA0,       // 1110
126                     0x90),
127       off1_hibits);
128   __m128i second_under = _mm_cmpgt_epi8(second_mins, current_bytes);
129   *has_error =
130       _mm_or_si128(*has_error, _mm_and_si128(initial_under, second_under));
131 }
132 
133 struct processed_utf_bytes {
134   __m128i rawbytes;
135   __m128i high_nibbles;
136   __m128i carried_continuations;
137 };
138 
count_nibbles(__m128i bytes,struct processed_utf_bytes * answer)139 static inline void count_nibbles(__m128i bytes,
140                                  struct processed_utf_bytes *answer) {
141   answer->rawbytes = bytes;
142   answer->high_nibbles =
143       _mm_and_si128(_mm_srli_epi16(bytes, 4), _mm_set1_epi8(0x0F));
144 }
145 
146 // check whether the current bytes are valid UTF-8
147 // at the end of the function, previous gets updated
148 static inline struct processed_utf_bytes
checkUTF8Bytes(__m128i current_bytes,struct processed_utf_bytes * previous,__m128i * has_error)149 checkUTF8Bytes(__m128i current_bytes, struct processed_utf_bytes *previous,
150                __m128i *has_error) {
151 
152   struct processed_utf_bytes pb;
153   count_nibbles(current_bytes, &pb);
154 
155   checkSmallerThan0xF4(current_bytes, has_error);
156 
157   __m128i initial_lengths = continuationLengths(pb.high_nibbles);
158 
159   pb.carried_continuations =
160       carryContinuations(initial_lengths, previous->carried_continuations);
161 
162   checkContinuations(initial_lengths, pb.carried_continuations, has_error);
163 
164   __m128i off1_current_bytes =
165       _mm_alignr_epi8(pb.rawbytes, previous->rawbytes, 16 - 1);
166   checkFirstContinuationMax(current_bytes, off1_current_bytes, has_error);
167 
168   checkOverlong(current_bytes, off1_current_bytes, pb.high_nibbles,
169                 previous->high_nibbles, has_error);
170   return pb;
171 }
172 
173 /* Return 0 on success, -1 on error */
utf8_lemire(const unsigned char * src,int len)174 int utf8_lemire(const unsigned char *src, int len) {
175   size_t i = 0;
176   __m128i has_error = _mm_setzero_si128();
177   struct processed_utf_bytes previous = {.rawbytes = _mm_setzero_si128(),
178                                          .high_nibbles = _mm_setzero_si128(),
179                                          .carried_continuations =
180                                              _mm_setzero_si128()};
181   if (len >= 16) {
182     for (; i <= len - 16; i += 16) {
183       __m128i current_bytes = _mm_loadu_si128((const __m128i *)(src + i));
184       previous = checkUTF8Bytes(current_bytes, &previous, &has_error);
185     }
186   }
187 
188   // last part
189   if (i < len) {
190     char buffer[16];
191     memset(buffer, 0, 16);
192     memcpy(buffer, src + i, len - i);
193     __m128i current_bytes = _mm_loadu_si128((const __m128i *)(buffer));
194     previous = checkUTF8Bytes(current_bytes, &previous, &has_error);
195   } else {
196     has_error =
197         _mm_or_si128(_mm_cmpgt_epi8(previous.carried_continuations,
198                                     _mm_setr_epi8(9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
199                                                   9, 9, 9, 9, 9, 1)),
200                      has_error);
201   }
202 
203   return _mm_testz_si128(has_error, has_error) ? 0 : -1;
204 }
205 
206 #endif
207