Debian Codegraph @

tests/tests.rs

raw symbols SCIP
1 #![allow(clippy::non_ascii_literal)]
2
3 use simdutf8::basic::from_utf8 as basic_from_utf8;
4 use simdutf8::basic::from_utf8_mut as basic_from_utf8_mut;
5 use simdutf8::compat::from_utf8 as compat_from_utf8;
6 use simdutf8::compat::from_utf8_mut as compat_from_utf8_mut;
7
8 #[cfg(not(feature = "std"))]
9 extern crate std;
10
11 #[cfg(not(feature = "std"))]
12 use std::{borrow::ToOwned, format};
13
14 pub trait BStrExt {
15 fn repeat_x(&self, count: usize) -> Vec<u8>;
16 }
17
18 /// b"a".repeat() is not implemented for Rust 1.38.0 (MSRV)
19 impl<T> BStrExt for T
20 where
21 T: AsRef<[u8]>,
22 {
23 fn repeat_x(&self, count: usize) -> Vec<u8> {
24 use std::io::Write;
25
26 let x = self.as_ref();
27 let mut res = Vec::with_capacity(x.len() * count);
28 for _ in 0..count {
29 #[allow(clippy::unwrap_used)]
30 res.write_all(x).unwrap();
31 }
32 res
33 }
34 }
35
36 fn test_valid(input: &[u8]) {
37 // std lib sanity check
38 assert!(std::str::from_utf8(input).is_ok());
39
40 assert!(basic_from_utf8(input).is_ok());
41 assert!(compat_from_utf8(input).is_ok());
42
43 let mut mut_input = input.to_owned();
44 assert!(basic_from_utf8_mut(mut_input.as_mut_slice()).is_ok());
45 assert!(compat_from_utf8_mut(mut_input.as_mut_slice()).is_ok());
46
47 #[cfg(feature = "public_imp")]
48 test_valid_public_imp(input);
49 }
50
51 // unused for cases where public_imp is set but no SIMD functions generated...
52 #[cfg(feature = "public_imp")]
53 #[allow(dead_code)]
54 fn test_streaming<T: simdutf8::basic::imp::Utf8Validator>(input: &[u8], ok: bool) {
55 unsafe {
56 let mut validator = T::new();
57 validator.update(input);
58 assert_eq!(validator.finalize().is_ok(), ok);
59 }
60 for i in [64, 128, 256, 1024, 65536, 1, 2, 3, 36, 99].iter() {
61 test_streaming_blocks::<T>(input, *i, ok)
62 }
63 }
64
65 // unused for cases where public_imp is set but no SIMD functions generated...
66 #[cfg(feature = "public_imp")]
67 #[allow(dead_code)]
68 fn test_streaming_blocks<T: simdutf8::basic::imp::Utf8Validator>(
69 input: &[u8],
70 block_size: usize,
71 ok: bool,
72 ) {
73 unsafe {
74 let mut validator = T::new();
75 for chunk in input.chunks(block_size) {
76 validator.update(chunk);
77 }
78 assert_eq!(validator.finalize().is_ok(), ok);
79 }
80 }
81
82 // unused for cases where public_imp is set but no SIMD functions generated...
83 #[cfg(feature = "public_imp")]
84 #[allow(dead_code)]
85 fn test_chunked_streaming<T: simdutf8::basic::imp::ChunkedUtf8Validator>(input: &[u8], ok: bool) {
86 for i in [64, 128, 256, 1024, 65536].iter() {
87 test_chunked_streaming_with_chunk_size::<T>(input, *i, ok)
88 }
89 }
90
91 // unused for cases where public_imp is set but no SIMD functions generated...
92 #[cfg(feature = "public_imp")]
93 #[allow(dead_code)]
94 fn test_chunked_streaming_with_chunk_size<T: simdutf8::basic::imp::ChunkedUtf8Validator>(
95 input: &[u8],
96 chunk_size: usize,
97 ok: bool,
98 ) {
99 unsafe {
100 let mut validator = T::new();
101 let mut chunks = input.chunks_exact(chunk_size);
102 for chunk in &mut chunks {
103 validator.update_from_chunks(chunk);
104 }
105 assert_eq!(validator.finalize(Some(chunks.remainder())).is_ok(), ok);
106 }
107 }
108
109 #[cfg(feature = "public_imp")]
110 #[allow(unused_variables)]
111 fn test_valid_public_imp(input: &[u8]) {
112 if cfg!(any(target_arch = "x86", target_arch = "x86_64")) {
113 #[cfg(target_feature = "avx2")]
114 unsafe {
115 assert!(simdutf8::basic::imp::x86::avx2::validate_utf8(input).is_ok());
116 assert!(simdutf8::compat::imp::x86::avx2::validate_utf8(input).is_ok());
117
118 test_streaming::<simdutf8::basic::imp::x86::avx2::Utf8ValidatorImp>(input, true);
119 test_chunked_streaming::<simdutf8::basic::imp::x86::avx2::ChunkedUtf8ValidatorImp>(
120 input, true,
121 );
122 }
123
124 #[cfg(target_feature = "sse4.2")]
125 unsafe {
126 assert!(simdutf8::basic::imp::x86::sse42::validate_utf8(input).is_ok());
127 assert!(simdutf8::compat::imp::x86::sse42::validate_utf8(input).is_ok());
128
129 test_streaming::<simdutf8::basic::imp::x86::sse42::Utf8ValidatorImp>(input, true);
130 test_chunked_streaming::<simdutf8::basic::imp::x86::sse42::ChunkedUtf8ValidatorImp>(
131 input, true,
132 );
133 }
134 }
135 #[cfg(all(
136 feature = "aarch64_neon",
137 target_arch = "aarch64",
138 target_feature = "neon"
139 ))]
140 unsafe {
141 assert!(simdutf8::basic::imp::aarch64::neon::validate_utf8(input).is_ok());
142 assert!(simdutf8::compat::imp::aarch64::neon::validate_utf8(input).is_ok());
143
144 test_streaming::<simdutf8::basic::imp::aarch64::neon::Utf8ValidatorImp>(input, true);
145 test_chunked_streaming::<simdutf8::basic::imp::aarch64::neon::ChunkedUtf8ValidatorImp>(
146 input, true,
147 );
148 }
149 #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
150 unsafe {
151 assert!(simdutf8::basic::imp::wasm32::simd128::validate_utf8(input).is_ok());
152 assert!(simdutf8::compat::imp::wasm32::simd128::validate_utf8(input).is_ok());
153
154 test_streaming::<simdutf8::basic::imp::wasm32::simd128::Utf8ValidatorImp>(input, true);
155 test_chunked_streaming::<simdutf8::basic::imp::wasm32::simd128::ChunkedUtf8ValidatorImp>(
156 input, true,
157 );
158 }
159 }
160
161 fn test_invalid(input: &[u8], valid_up_to: usize, error_len: Option<usize>) {
162 // std lib sanity check
163 let err = std::str::from_utf8(input).unwrap_err();
164 assert_eq!(err.valid_up_to(), valid_up_to);
165 assert_eq!(err.error_len(), error_len);
166
167 assert!(basic_from_utf8(input).is_err());
168 let err = compat_from_utf8(input).unwrap_err();
169 assert_eq!(err.valid_up_to(), valid_up_to);
170 assert_eq!(err.error_len(), error_len);
171
172 #[cfg(feature = "public_imp")]
173 test_invalid_public_imp(input, valid_up_to, error_len);
174 }
175
176 #[cfg(feature = "public_imp")]
177 #[allow(unused_variables)]
178 fn test_invalid_public_imp(input: &[u8], valid_up_to: usize, error_len: Option<usize>) {
179 if cfg!(any(target_arch = "x86", target_arch = "x86_64")) {
180 #[cfg(target_feature = "avx2")]
181 unsafe {
182 assert!(simdutf8::basic::imp::x86::avx2::validate_utf8(input).is_err());
183 let err = simdutf8::compat::imp::x86::avx2::validate_utf8(input).unwrap_err();
184 assert_eq!(err.valid_up_to(), valid_up_to);
185 assert_eq!(err.error_len(), error_len);
186
187 test_streaming::<simdutf8::basic::imp::x86::avx2::Utf8ValidatorImp>(input, false);
188 test_chunked_streaming::<simdutf8::basic::imp::x86::avx2::ChunkedUtf8ValidatorImp>(
189 input, false,
190 );
191 }
192 #[cfg(target_feature = "sse4.2")]
193 unsafe {
194 assert!(simdutf8::basic::imp::x86::sse42::validate_utf8(input).is_err());
195 let err = simdutf8::compat::imp::x86::sse42::validate_utf8(input).unwrap_err();
196 assert_eq!(err.valid_up_to(), valid_up_to);
197 assert_eq!(err.error_len(), error_len);
198
199 test_streaming::<simdutf8::basic::imp::x86::sse42::Utf8ValidatorImp>(input, false);
200 test_chunked_streaming::<simdutf8::basic::imp::x86::sse42::ChunkedUtf8ValidatorImp>(
201 input, false,
202 );
203 }
204 }
205 #[cfg(all(
206 feature = "aarch64_neon",
207 target_arch = "aarch64",
208 target_feature = "neon"
209 ))]
210 unsafe {
211 assert!(simdutf8::basic::imp::aarch64::neon::validate_utf8(input).is_err());
212 let err = simdutf8::compat::imp::aarch64::neon::validate_utf8(input).unwrap_err();
213 assert_eq!(err.valid_up_to(), valid_up_to);
214 assert_eq!(err.error_len(), error_len);
215
216 test_streaming::<simdutf8::basic::imp::aarch64::neon::Utf8ValidatorImp>(input, false);
217 test_chunked_streaming::<simdutf8::basic::imp::aarch64::neon::ChunkedUtf8ValidatorImp>(
218 input, false,
219 );
220 }
221 #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
222 unsafe {
223 assert!(simdutf8::basic::imp::wasm32::simd128::validate_utf8(input).is_err());
224 let err = simdutf8::compat::imp::wasm32::simd128::validate_utf8(input).unwrap_err();
225 assert_eq!(err.valid_up_to(), valid_up_to);
226 assert_eq!(err.error_len(), error_len);
227
228 test_streaming::<simdutf8::basic::imp::wasm32::simd128::Utf8ValidatorImp>(input, false);
229 test_chunked_streaming::<simdutf8::basic::imp::wasm32::simd128::ChunkedUtf8ValidatorImp>(
230 input, false,
231 );
232 }
233 }
234
235 fn test_invalid_after_specific_prefix(
236 input: &[u8],
237 valid_up_to: usize,
238 error_len: Option<usize>,
239 with_suffix_error_len: Option<usize>,
240 repeat: usize,
241 prefix_bytes: &[u8],
242 ) {
243 {
244 let mut prefixed_input = prefix_bytes.repeat_x(repeat);
245 let prefix_len = prefixed_input.len();
246 prefixed_input.extend_from_slice(input);
247 test_invalid(prefixed_input.as_ref(), valid_up_to + prefix_len, error_len)
248 }
249
250 if repeat != 0 {
251 let mut prefixed_input = prefix_bytes.repeat_x(repeat);
252 let prefix_len = prefixed_input.len();
253 prefixed_input.extend_from_slice(input);
254 prefixed_input.extend_from_slice(prefix_bytes.repeat_x(repeat).as_slice());
255 test_invalid(
256 prefixed_input.as_ref(),
257 valid_up_to + prefix_len,
258 with_suffix_error_len,
259 )
260 }
261 }
262
263 fn test_invalid_after_prefix(
264 input: &[u8],
265 valid_up_to: usize,
266 error_len: Option<usize>,
267 with_suffix_error_len: Option<usize>,
268 repeat: usize,
269 ) {
270 for prefix in [
271 "a",
272 "ö",
273 "😊",
274 "a".repeat(64).as_str(),
275 ("a".repeat(64) + "ö".repeat(32).as_str()).as_str(),
276 ]
277 .iter()
278 {
279 test_invalid_after_specific_prefix(
280 input,
281 valid_up_to,
282 error_len,
283 with_suffix_error_len,
284 repeat,
285 prefix.as_bytes(),
286 );
287 }
288 }
289
290 fn test_invalid_after_prefixes(
291 input: &[u8],
292 valid_up_to: usize,
293 error_len: Option<usize>,
294 with_suffix_error_len: Option<usize>,
295 ) {
296 for repeat in [
297 0, 1, 2, 7, 8, 9, 15, 16, 16, 31, 32, 33, 63, 64, 65, 127, 128, 129,
298 ]
299 .iter()
300 {
301 test_invalid_after_prefix(
302 input,
303 valid_up_to,
304 error_len,
305 with_suffix_error_len,
306 *repeat,
307 );
308 }
309 }
310
311 #[test]
312 fn simple_valid() {
313 test_valid(b"");
314
315 test_valid(b"\0");
316
317 test_valid(b"a".repeat_x(64).as_ref());
318
319 test_valid(b"a".repeat_x(128).as_ref());
320
321 test_valid(b"The quick brown fox jumps over the lazy dog");
322
323 // umlauts
324 test_valid("öäüÖÄÜß".as_bytes());
325
326 // emojis
327 test_valid("❤️✨🥺🔥😂😊✔️👍🥰".as_bytes());
328
329 // Chinese
330 test_valid("断用山昨屈内銀代意検瓶調像。情旗最投任留財夜隆年表高学送意功者。辺図掲記込真通第民国聞平。海帰傷芸記築世防橋整済歳権君注。選紙例並情夕破勢景移情誇進場豊読。景関有権米武野範随惑旬特覧刊野。相毎加共情面教地作減関絡。暖料児違歩致本感閉浦出楽赤何。時選権週邑針格事提一案質名投百定。止感右聞食三年外積文載者別。".as_bytes());
331
332 // Japanese
333 test_valid("意ざど禁23費サヒ車園オスミト規更ワエ異67事続トソキ音合岡治こ訪京ぴ日9稿がト明安イ抗的ウクロコ売一エコヨホ必噴塗ッ。索墓ー足議需レ応予ニ質県トぴン学市機だほせフ車捕コニ自校がこで極3力イい増娘汁表製ク。委セヤホネ作誌ミマクソ続新ほし月中報制どてびフ字78完りっせが村惹ヨサコ訳器りそ参受草ムタ大移ッけでつ番足ほこン質北ぽのよう応一ア輝労イ手人う再茨夕へしう。".as_bytes());
334
335 // Korean
336 test_valid("3인은 대법원장이 지명하는 자를 임명한다, 대통령은 제3항과 제4항의 사유를 지체없이 공포하여야 한다, 제한하는 경우에도 자유와 권리의 본질적인 내용을 침해할 수 없다, 국가는 전통문화의 계승·발전과 민족문화의 창달에 노력하여야 한다.".as_bytes());
337 }
338
339 #[test]
340 fn simple_invalid() {
341 test_invalid_after_prefixes(b"\xFF", 0, Some(1), Some(1));
342
343 // incomplete umlaut
344 test_invalid_after_prefixes(b"\xC3", 0, None, Some(1));
345
346 // incomplete emoji
347 test_invalid_after_prefixes(b"\xF0", 0, None, Some(1));
348 test_invalid_after_prefixes(b"\xF0\x9F", 0, None, Some(2));
349 test_invalid_after_prefixes(b"\xF0\x9F\x98", 0, None, Some(3));
350 }
351
352 #[test]
353 fn incomplete_on_32nd_byte() {
354 let mut invalid = b"a".repeat_x(31);
355 invalid.push(b'\xF0');
356 test_invalid(&invalid, 31, None)
357 }
358
359 #[test]
360 fn incomplete_on_64th_byte() {
361 let mut invalid = b"a".repeat_x(63);
362 invalid.push(b'\xF0');
363 test_invalid(&invalid, 63, None)
364 }
365
366 #[test]
367 fn incomplete_on_64th_byte_65_bytes_total() {
368 let mut invalid = b"a".repeat_x(63);
369 invalid.push(b'\xF0');
370 invalid.push(b'a');
371 test_invalid(&invalid, 63, Some(1))
372 }
373
374 #[test]
375 fn error_display_basic() {
376 assert_eq!(
377 format!("{}", basic_from_utf8(b"\xF0").unwrap_err()),
378 "invalid utf-8 sequence"
379 );
380 assert_eq!(
381 format!("{}", basic_from_utf8(b"a\xF0a").unwrap_err()),
382 "invalid utf-8 sequence"
383 );
384 }
385
386 #[test]
387 fn error_display_compat() {
388 assert_eq!(
389 format!("{}", compat_from_utf8(b"\xF0").unwrap_err()),
390 "incomplete utf-8 byte sequence from index 0"
391 );
392 assert_eq!(
393 format!("{}", compat_from_utf8(b"a\xF0a").unwrap_err()),
394 "invalid utf-8 sequence of 1 bytes from index 1"
395 );
396 assert_eq!(
397 format!("{}", compat_from_utf8(b"a\xF0\x9Fa").unwrap_err()),
398 "invalid utf-8 sequence of 2 bytes from index 1"
399 );
400 assert_eq!(
401 format!("{}", compat_from_utf8(b"a\xF0\x9F\x98a").unwrap_err()),
402 "invalid utf-8 sequence of 3 bytes from index 1"
403 );
404 }
405
406 #[test]
407 fn error_debug_basic() {
408 assert_eq!(
409 format!("{:?}", basic_from_utf8(b"\xF0").unwrap_err()),
410 "Utf8Error"
411 );
412 }
413
414 #[test]
415 fn error_debug_compat() {
416 assert_eq!(
417 format!("{:?}", compat_from_utf8(b"\xF0").unwrap_err()),
418 "Utf8Error { valid_up_to: 0, error_len: None }"
419 );
420 assert_eq!(
421 format!("{:?}", compat_from_utf8(b"a\xF0a").unwrap_err()),
422 "Utf8Error { valid_up_to: 1, error_len: Some(1) }"
423 );
424 }
425
426 #[test]
427 fn error_derives_basic() {
428 let err = basic_from_utf8(b"\xF0").unwrap_err();
429 #[allow(clippy::clone_on_copy)] // used for coverage
430 let err2 = err.clone();
431 assert_eq!(err, err2);
432 assert!(!(err != err2));
433 }
434
435 #[test]
436 fn error_derives_compat() {
437 let err = compat_from_utf8(b"\xF0").unwrap_err();
438 #[allow(clippy::clone_on_copy)] // used for coverage
439 let err2 = err.clone();
440 assert_eq!(err, err2);
441 assert!(!(err != err2));
442 }
443
444 #[test]
445 #[should_panic]
446 #[cfg(all(feature = "public_imp", target_feature = "avx2"))]
447 fn test_avx2_chunked_panic() {
448 test_chunked_streaming_with_chunk_size::<
449 simdutf8::basic::imp::x86::avx2::ChunkedUtf8ValidatorImp,
450 >(b"abcd", 1, true);
451 }
452
453 #[test]
454 #[should_panic]
455 #[cfg(all(feature = "public_imp", target_feature = "sse4.2"))]
456 fn test_sse42_chunked_panic() {
457 test_chunked_streaming_with_chunk_size::<
458 simdutf8::basic::imp::x86::sse42::ChunkedUtf8ValidatorImp,
459 >(b"abcd", 1, true);
460 }
461
462 #[test]
463 #[should_panic]
464 #[cfg(all(
465 feature = "public_imp",
466 target_arch = "aarch64",
467 feature = "aarch64_neon"
468 ))]
469 fn test_neon_chunked_panic() {
470 test_chunked_streaming_with_chunk_size::<
471 simdutf8::basic::imp::aarch64::neon::ChunkedUtf8ValidatorImp,
472 >(b"abcd", 1, true);
473 }
474
475 // the test runner will ignore this test probably due to limitations of panic handling/threading
476 // of that target--keeping this here so that when it can be tested properly, it will
477 // FIXME: remove this comment once this works properly.
478 #[test]
479 #[should_panic]
480 #[cfg(all(
481 feature = "public_imp",
482 target_arch = "wasm32",
483 target_feature = "simd128"
484 ))]
485 fn test_simd128_chunked_panic() {
486 test_chunked_streaming_with_chunk_size::<
487 simdutf8::basic::imp::wasm32::simd128::ChunkedUtf8ValidatorImp,
488 >(b"abcd", 1, true);
489 }