| 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 | package simd |
| 6 | |
| 7 | import ( |
| 8 | "bytes" |
| 9 | ) |
| 10 | |
| 11 | // memmemMinHaystack is the haystack size below which Memmem skips the |
| 12 | // prefilter and calls bytes.Index directly: rare-byte selection and scan |
| 13 | // setup are per-call costs that need enough haystack to amortize. The |
| 14 | // tradeoff is measurable with Benchmark_Memmem_Prefilter, which forces |
| 15 | // the prefilter helpers at every size — the paired scan breaks even with |
| 16 | // bytes.Index around its 64B point — so 128 keeps a conservative margin |
| 17 | // over that break-even, covering the SelectRareBytes cost the direct |
| 18 | // calls exclude and the needle shapes that route to the less selective |
| 19 | // single-byte scan. Benchmark_Memmem shows the resulting end-to-end |
| 20 | // routing (its sub-128B simd rows measure dispatch overhead only, since |
| 21 | // both variants run bytes.Index there). |
| 22 | const memmemMinHaystack = 128 |
| 23 | |
| 24 | // memmemMaxPairNeedle is the needle length up to which the paired-byte |
| 25 | // prefilter beats a single rare-byte scan: short needles produce frequent |
| 26 | // single-byte false positives, and verifying them costs more than the second |
| 27 | // byte check saves. |
| 28 | const memmemMaxPairNeedle = 6 |
| 29 | |
| 30 | // memmemMaxMisses caps how many failed candidate verifications the |
| 31 | // prefilter loops tolerate before handing the search to bytes.Index. A |
| 32 | // pathological input (rare byte everywhere, long almost-matching needle) |
| 33 | // would otherwise cost O(len(haystack) * len(needle)); the cap bounds the |
| 34 | // wasted work at memmemMaxMisses needle comparisons, keeping the worst case |
| 35 | // at bytes.Index's O(n+m) plus a constant. |
| 36 | const memmemMaxMisses = 16 |
| 37 | |
| 38 | // Memmem returns the index of the first occurrence of needle in haystack, |
| 39 | // or -1 if needle is not present. An empty needle matches at index 0, |
| 40 | // mirroring bytes.Index. |
| 41 | // |
| 42 | // On amd64 with AVX2 and haystacks of 128+ bytes it prefilters with the |
| 43 | // needle's rarest bytes (per ByteRank) and verifies only the candidate |
| 44 | // positions, which typically beats bytes.Index by a wide margin on large |
| 45 | // inputs: needles of 2-6 bytes containing two distinct byte values are |
| 46 | // scanned for their two rarest values at the exact relative distance, |
| 47 | // while longer or single-valued needles are scanned for the single rarest |
| 48 | // byte. In all other cases it delegates to bytes.Index directly, and the |
| 49 | // prefilter itself falls back to bytes.Index after a bounded number of |
| 50 | // failed candidate verifications, so the worst case stays within a |
| 51 | // constant of the stdlib's O(n+m). |
| 52 | func Memmem(haystack, needle []byte) int { |
| 53 | needleLen := len(needle) |
| 54 | if needleLen == 0 { |
| 55 | return 0 |
| 56 | } |
| 57 | if len(haystack) < needleLen { |
| 58 | return -1 |
| 59 | } |
| 60 | if needleLen == 1 { |
| 61 | return bytes.IndexByte(haystack, needle[0]) |
| 62 | } |
| 63 | if !hasAVX2 || len(haystack) < memmemMinHaystack { |
| 64 | return bytes.Index(haystack, needle) |
| 65 | } |
| 66 | |
| 67 | info := SelectRareBytes(needle) |
| 68 | // Distinct byte values imply distinct indices, so Byte1 != Byte2 alone |
| 69 | // guarantees the offset MemchrPair needs is >= 1. |
| 70 | if needleLen <= memmemMaxPairNeedle && info.Byte1 != info.Byte2 { |
| 71 | return memmemPaired(haystack, needle, info) |
| 72 | } |
| 73 | return memmemSingle(haystack, needle, info.Byte1, info.Index1) |
| 74 | } |
| 75 | |
| 76 | // memmemPaired scans for the needle's two rarest bytes at their exact |
| 77 | // relative distance with MemchrPair and verifies each candidate. False |
| 78 | // candidates need both bytes at the right distance, so verification is |
| 79 | // rare; if it still misses too often, memmemFallback finishes the search. |
| 80 | func memmemPaired(haystack, needle []byte, info RareByteInfo) int { |
| 81 | byte1, idx1 := info.Byte1, info.Index1 |
| 82 | byte2, idx2 := info.Byte2, info.Index2 |
| 83 | if idx1 > idx2 { |
| 84 | byte1, byte2 = byte2, byte1 |
| 85 | idx1, idx2 = idx2, idx1 |
| 86 | } |
| 87 | offset := idx2 - idx1 |
| 88 | |
| 89 | misses := 0 |
| 90 | for start := 0; ; { |
| 91 | cand := MemchrPair(haystack[start:], byte1, byte2, offset) |
| 92 | if cand == -1 { |
| 93 | return -1 |
| 94 | } |
| 95 | // cand is the position of byte1; the needle would start idx1 earlier. |
| 96 | pos := start + cand - idx1 |
| 97 | if pos >= 0 && pos+len(needle) <= len(haystack) && |
| 98 | bytes.Equal(haystack[pos:pos+len(needle)], needle) { |
| 99 | return pos |
| 100 | } |
| 101 | start += cand + 1 |
| 102 | if misses++; misses >= memmemMaxMisses { |
| 103 | return memmemFallback(haystack, needle, start, idx1) |
| 104 | } |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | // memmemSingle scans for the needle's rarest byte and verifies each |
| 109 | // candidate; for longer needles the rare byte alone is selective enough |
| 110 | // that the paired scan's second comparison stops paying for itself. Like |
| 111 | // memmemPaired it hands persistent misses to memmemFallback. |
| 112 | func memmemSingle(haystack, needle []byte, rareByte byte, rareIdx int) int { |
| 113 | misses := 0 |
| 114 | for start := 0; ; { |
| 115 | cand := bytes.IndexByte(haystack[start:], rareByte) |
| 116 | if cand == -1 { |
| 117 | return -1 |
| 118 | } |
| 119 | pos := start + cand - rareIdx |
| 120 | if pos >= 0 && pos+len(needle) <= len(haystack) && |
| 121 | bytes.Equal(haystack[pos:pos+len(needle)], needle) { |
| 122 | return pos |
| 123 | } |
| 124 | start += cand + 1 |
| 125 | if misses++; misses >= memmemMaxMisses { |
| 126 | return memmemFallback(haystack, needle, start, rareIdx) |
| 127 | } |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | // memmemFallback finishes a prefiltered search with bytes.Index once the |
| 132 | // candidate loops exhaust their miss budget. Every anchor before start has |
| 133 | // been checked, and any remaining occurrence carries its anchor byte at |
| 134 | // anchorIdx, so it starts at or after start-anchorIdx; searching from there |
| 135 | // cannot skip a match or return one out of order. The subtraction is in |
| 136 | // fact defensive: start-1 is always an anchor at handover and anchorIdx is |
| 137 | // the anchor byte's first occurrence in the needle, so no remaining |
| 138 | // occurrence can start below start itself — resuming at start-anchorIdx |
| 139 | // keeps correctness independent of that selection detail. |
| 140 | func memmemFallback(haystack, needle []byte, start, anchorIdx int) int { |
| 141 | from := max(start-anchorIdx, 0) |
| 142 | if pos := bytes.Index(haystack[from:], needle); pos >= 0 { |
| 143 | return from + pos |
| 144 | } |
| 145 | return -1 |
| 146 | } |