| 1 | // Adapted from the coregex project, https://github.com/coregx/coregex |
| 2 | // (package simd), Copyright (c) 2025 Andrey Kolkov and contributors, |
| 3 | // MIT License. See the LICENSE file in this directory for the full text. |
| 4 | |
| 5 | //go:build amd64 |
| 6 | |
| 7 | package simd |
| 8 | |
| 9 | // The ASCII kernels are implemented in ascii_amd64.s. All three read the |
| 10 | // same signal (a byte is non-ASCII exactly when its high bit is set, which |
| 11 | // VPMOVMSKB gathers 32 at a time) and process four vectors per iteration. |
| 12 | // Like the rest of the package's kernels they are self-bounding: each one |
| 13 | // clamps its own vector loops and finishes short remainders itself, so |
| 14 | // none of them carries a length precondition for the caller to uphold. |
| 15 | // |
| 16 | //go:noescape |
| 17 | func isASCIIAVX2(data []byte) bool |
| 18 | |
| 19 | //go:noescape |
| 20 | func firstNonASCIIAVX2(data []byte) int |
| 21 | |
| 22 | //go:noescape |
| 23 | func countNonASCIIAVX2(data []byte) int |
| 24 | |
| 25 | // isASCIIImpl dispatches to the AVX2 kernel for inputs large enough to amortize |
| 26 | // the vector setup; smaller inputs and pre-AVX2 CPUs take the SWAR path. |
| 27 | func isASCIIImpl(data []byte) bool { |
| 28 | if hasAVX2 && len(data) >= MinLen { |
| 29 | return isASCIIAVX2(data) |
| 30 | } |
| 31 | return isASCIIGeneric(data) |
| 32 | } |
| 33 | |
| 34 | // firstNonASCIIImpl dispatches like isASCIIImpl. |
| 35 | func firstNonASCIIImpl(data []byte) int { |
| 36 | if hasAVX2 && len(data) >= MinLen { |
| 37 | return firstNonASCIIAVX2(data) |
| 38 | } |
| 39 | return firstNonASCIIGeneric(data) |
| 40 | } |
| 41 | |
| 42 | // countNonASCIIImpl dispatches like isASCIIImpl, with the extra POPCNT |
| 43 | // check its kernel needs. The kernel counts its own sub-vector remainder, |
| 44 | // so there is no prefix/suffix split here. An earlier version did split, |
| 45 | // handing the remainder to countNonASCIIGeneric, and paid a second |
| 46 | // non-inlinable call even when the remainder was empty — enough to put |
| 47 | // this scan behind its own SWAR fallback at MinLen (11.3ns vs 8.8ns at |
| 48 | // 32B). With the split gone the two are level at 32B and the kernel pulls |
| 49 | // ahead from 64B up, so MinLen stays the shared threshold. |
| 50 | func countNonASCIIImpl(data []byte) int { |
| 51 | if hasAVX2 && hasPOPCNT && len(data) >= MinLen { |
| 52 | return countNonASCIIAVX2(data) |
| 53 | } |
| 54 | return countNonASCIIGeneric(data) |
| 55 | } |