Find the first occurrence of a @b single-character needle in an arbitrary length haystack. * This implementation uses hardware-agnostic SWAR technique, to process 8 characters at a time. * Identical to `memchr(haystack, needle[0], haystack_length)`. */
| 378 | * Identical to `memchr(haystack, needle[0], haystack_length)`. |
| 379 | */ |
| 380 | SZ_PUBLIC sz_cptr_t sz_find_byte_serial(sz_cptr_t h_chars, sz_size_t h_length, sz_cptr_t n_chars) { |
| 381 | |
| 382 | if (!h_length) return SZ_NULL_CHAR; |
| 383 | // Reinterpret as unsigned bytes so the SWAR broadcast below cannot sign-extend |
| 384 | // on platforms where `char` is signed (e.g. `-fsigned-char`). See issue #306. |
| 385 | sz_u8_t const *h = (sz_u8_t const *)h_chars; |
| 386 | sz_u8_t const *const n = (sz_u8_t const *)n_chars; |
| 387 | sz_u8_t const *const h_end = h + h_length; |
| 388 | |
| 389 | #if !SZ_IS_BIG_ENDIAN_ // Use SWAR only on little-endian platforms for brevity. |
| 390 | #if !SZ_USE_MISALIGNED_LOADS // Process the misaligned head, to void UB on unaligned 64-bit loads. |
| 391 | for (; ((sz_size_t)h & 7ull) && h < h_end; ++h) |
| 392 | if (*h == *n) return (sz_cptr_t)h; |
| 393 | #endif |
| 394 | |
| 395 | // Broadcast the n into every byte of a 64-bit integer to use SWAR |
| 396 | // techniques and process eight characters at a time. |
| 397 | sz_u64_vec_t h_vec, n_vec, match_vec; |
| 398 | match_vec.u64 = 0; |
| 399 | n_vec.u64 = (sz_u64_t)*n * 0x0101010101010101ull; |
| 400 | for (; h + 8 <= h_end; h += 8) { |
| 401 | h_vec.u64 = *(sz_u64_t const *)h; |
| 402 | match_vec = sz_u64_each_byte_equal_(h_vec, n_vec); |
| 403 | if (match_vec.u64) return (sz_cptr_t)(h + sz_u64_ctz(match_vec.u64) / 8); |
| 404 | } |
| 405 | #endif |
| 406 | |
| 407 | // Handle the misaligned tail. |
| 408 | for (; h < h_end; ++h) |
| 409 | if (*h == *n) return (sz_cptr_t)h; |
| 410 | return SZ_NULL_CHAR; |
| 411 | } |
| 412 | |
| 413 | /* Find the last occurrence of a @b single-character needle in an arbitrary length haystack. |
| 414 | * This implementation uses hardware-agnostic SWAR technique, to process 8 characters at a time. |
no test coverage detected
searching dependent graphs…