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