Debian Codegraph @

simd/simd_test.go

raw symbols SCIP
1 package simd
2
3 import (
4 "bytes"
5 "os"
6 "runtime"
7 "strconv"
8 "testing"
9
10 "github.com/stretchr/testify/require"
11 "golang.org/x/sys/cpu"
12 )
13
14 // The tests compare every exported function AND its portable fallback
15 // against plain scalar references, sweeping sizes across the dispatch
16 // boundaries (sub-word, sub-vector, 32+ bytes, unaligned tails) so both the
17 // AVX2 kernels and the SWAR paths are exercised on amd64.
18
19 // testSizes crosses every dispatch boundary: scalar (<8), SWAR words with
20 // tails (8..31), one vector (32..63), several vectors plus tails, and sizes
21 // beyond the Memmem bytes.Index crossover (128+).
22 var testSizes = []int{
23 0, 1, 2, 3, 7, 8, 9, 15, 16, 17, 23, 24, 31, 32, 33, 39, 47, 48, 63, 64,
24 65, 95, 96, 100, 127, 128, 129, 130, 200, 255, 256, 257, 511, 512, 1000,
25 }
26
27 // fill produces deterministic pseudo-random bytes over the full 0..255
28 // range, seeded per call site, without math/rand (xorshift is plenty here).
29 func fill(n int, seed uint64) []byte {
30 b := make([]byte, n)
31 x := seed*2654435761 + 1
32 for i := range b {
33 x ^= x << 13
34 x ^= x >> 7
35 x ^= x << 17
36 b[i] = byte(x)
37 }
38 return b
39 }
40
41 func refMemchr2(h []byte, a, b byte) int {
42 for i, c := range h {
43 if c == a || c == b {
44 return i
45 }
46 }
47 return -1
48 }
49
50 func refMemchr3(h []byte, a, b, c byte) int {
51 for i, x := range h {
52 if x == a || x == b || x == c {
53 return i
54 }
55 }
56 return -1
57 }
58
59 func refMemchrPair(h []byte, b1, b2 byte, offset int) int {
60 if offset < 0 {
61 return -1
62 }
63 for i := 0; i+offset < len(h); i++ {
64 if h[i] == b1 && h[i+offset] == b2 {
65 return i
66 }
67 }
68 return -1
69 }
70
71 func refIsASCII(h []byte) bool {
72 for _, b := range h {
73 if b >= 0x80 {
74 return false
75 }
76 }
77 return true
78 }
79
80 func refFirstNonASCII(h []byte) int {
81 for i, b := range h {
82 if b >= 0x80 {
83 return i
84 }
85 }
86 return -1
87 }
88
89 func refCountNonASCII(h []byte) int {
90 n := 0
91 for _, b := range h {
92 if b >= 0x80 {
93 n++
94 }
95 }
96 return n
97 }
98
99 func checkMemchr2(t *testing.T, h []byte, a, b byte) {
100 t.Helper()
101 want := refMemchr2(h, a, b)
102 require.Equal(t, want, Memchr2(h, a, b), "Memchr2(%d bytes, %#x, %#x)", len(h), a, b)
103 require.Equal(t, want, memchr2Generic(h, a, b), "memchr2Generic(%d bytes, %#x, %#x)", len(h), a, b)
104 }
105
106 func checkMemchr3(t *testing.T, h []byte, a, b, c byte) {
107 t.Helper()
108 want := refMemchr3(h, a, b, c)
109 require.Equal(t, want, Memchr3(h, a, b, c), "Memchr3(%d bytes)", len(h))
110 require.Equal(t, want, memchr3Generic(h, a, b, c), "memchr3Generic(%d bytes)", len(h))
111 }
112
113 func checkMemchrPair(t *testing.T, h []byte, b1, b2 byte, offset int) {
114 t.Helper()
115 want := refMemchrPair(h, b1, b2, offset)
116 require.Equal(t, want, MemchrPair(h, b1, b2, offset), "MemchrPair(%d bytes, %#x, %#x, %d)", len(h), b1, b2, offset)
117 if offset >= 1 && len(h) > offset {
118 require.Equal(t, want, memchrPairGeneric(h, b1, b2, offset), "memchrPairGeneric(%d bytes, %#x, %#x, %d)", len(h), b1, b2, offset)
119 }
120 }
121
122 func Test_Memchr2(t *testing.T) {
123 t.Parallel()
124 for _, n := range testSizes {
125 // Absent needles force a full scan of clean data.
126 clean := bytes.Repeat([]byte{'x'}, n)
127 checkMemchr2(t, clean, 'a', 'b')
128 // Every single position, for either needle.
129 for pos := range n {
130 h := bytes.Repeat([]byte{'x'}, n)
131 h[pos] = 'a'
132 checkMemchr2(t, h, 'a', 'b')
133 h[pos] = 'b'
134 checkMemchr2(t, h, 'a', 'b')
135 // Identical needles must behave like a single-byte search.
136 checkMemchr2(t, h, 'b', 'b')
137 h[pos] = 0x80 // high-bit byte must not confuse the SWAR masks
138 checkMemchr2(t, h, 0x80, 0xff)
139 }
140 // First match wins when both needles are present.
141 if n >= 2 {
142 h := bytes.Repeat([]byte{'x'}, n)
143 h[n/2] = 'b'
144 h[n-1] = 'a'
145 checkMemchr2(t, h, 'a', 'b')
146 }
147 // Random data over the full byte range.
148 checkMemchr2(t, fill(n, uint64(n)), 0x00, 0x01)
149 }
150 }
151
152 func Test_Memchr2_SWARBorrow(t *testing.T) {
153 t.Parallel()
154 // 0x00/0x01 adjacency is where the SWAR zero-lane formula produces
155 // false positives above the first true match; the first-lane pick must
156 // stay exact.
157 patterns := [][]byte{
158 {0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00},
159 {0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x01},
160 bytes.Repeat([]byte{0x01}, 40),
161 append(bytes.Repeat([]byte{0x01}, 39), 0x00),
162 }
163 for _, h := range patterns {
164 checkMemchr2(t, h, 0x00, 0x02)
165 checkMemchr2(t, h, 0x02, 0x00)
166 checkMemchr3(t, h, 0x00, 0x02, 0x03)
167 checkMemchrPair(t, h, 0x01, 0x00, 1)
168 checkMemchrPair(t, h, 0x00, 0x00, 2)
169 }
170 }
171
172 func Test_Memchr3(t *testing.T) {
173 t.Parallel()
174 for _, n := range testSizes {
175 clean := bytes.Repeat([]byte{'x'}, n)
176 checkMemchr3(t, clean, 'a', 'b', 'c')
177 for pos := range n {
178 for _, needle := range []byte{'a', 'b', 'c'} {
179 h := bytes.Repeat([]byte{'x'}, n)
180 h[pos] = needle
181 checkMemchr3(t, h, 'a', 'b', 'c')
182 }
183 }
184 if n >= 3 {
185 h := bytes.Repeat([]byte{'x'}, n)
186 h[n-1] = 'a'
187 h[n/2] = 'b'
188 h[n/3] = 'c'
189 checkMemchr3(t, h, 'a', 'b', 'c')
190 }
191 checkMemchr3(t, fill(n, uint64(n)+1), 0x00, 0x80, 0xff)
192 }
193 }
194
195 func Test_MemchrPair(t *testing.T) {
196 t.Parallel()
197 // Degenerate parameters.
198 require.Equal(t, -1, MemchrPair([]byte("abc"), 'a', 'b', -1))
199 require.Equal(t, -1, MemchrPair([]byte("abc"), 'a', 'b', 3))
200 require.Equal(t, -1, MemchrPair([]byte("abc"), 'a', 'b', 7))
201 require.Equal(t, -1, MemchrPair(nil, 'a', 'b', 0))
202 // offset 0 needs both bytes at one position: only equal bytes can match.
203 require.Equal(t, -1, MemchrPair([]byte("abc"), 'a', 'b', 0))
204 require.Equal(t, 1, MemchrPair([]byte("abc"), 'b', 'b', 0))
205
206 offsets := []int{1, 2, 3, 7, 8, 9, 15, 31, 32, 40}
207 for _, n := range testSizes {
208 for _, offset := range offsets {
209 if offset >= n {
210 continue
211 }
212 // Plant the pair at every valid start position.
213 for pos := 0; pos+offset < n; pos++ {
214 h := bytes.Repeat([]byte{'x'}, n)
215 h[pos] = 'a'
216 h[pos+offset] = 'b'
217 checkMemchrPair(t, h, 'a', 'b', offset)
218 }
219 // Anchor byte present everywhere, partner absent.
220 checkMemchrPair(t, bytes.Repeat([]byte{'a'}, n), 'a', 'b', offset)
221 checkMemchrPair(t, fill(n, uint64(n*100+offset)), 'a', 'b', offset)
222 checkMemchrPair(t, fill(n, uint64(n*100+offset+1)), 0x00, 0x01, offset)
223 }
224 }
225 }
226
227 func Test_IsASCII(t *testing.T) {
228 t.Parallel()
229 require.True(t, IsASCII(nil))
230 for _, n := range testSizes {
231 clean := make([]byte, n)
232 for i := range clean {
233 clean[i] = byte(i % 0x80)
234 }
235 require.True(t, IsASCII(clean), "size %d", n)
236 require.True(t, isASCIIGeneric(clean), "generic size %d", n)
237 for pos := range n {
238 h := bytes.Clone(clean)
239 h[pos] = 0x80
240 require.False(t, IsASCII(h), "size %d pos %d", n, pos)
241 require.False(t, isASCIIGeneric(h), "generic size %d pos %d", n, pos)
242 h[pos] = 0xff
243 require.False(t, IsASCII(h), "size %d pos %d", n, pos)
244 }
245 }
246 }
247
248 func Test_FirstNonASCII_CountNonASCII(t *testing.T) {
249 t.Parallel()
250 require.Equal(t, -1, FirstNonASCII(nil))
251 require.Equal(t, 0, CountNonASCII(nil))
252 require.Equal(t, -1, FirstNonASCII([]byte("hello")))
253 require.Equal(t, 1, FirstNonASCII([]byte("h\xc3\xa9llo")))
254 require.Equal(t, 2, CountNonASCII([]byte("h\xc3\xa9llo")))
255 // The only non-ASCII byte sits in the overlapping final word (length
256 // not a multiple of 8, clean words before it).
257 require.Equal(t, 12, FirstNonASCII(append(bytes.Repeat([]byte{'a'}, 12), 0x80)))
258 require.Equal(t, -1, FirstNonASCII(bytes.Repeat([]byte{'a'}, 13)))
259 for _, n := range testSizes {
260 h := fill(n, uint64(n)+7)
261 wantFirst := -1
262 wantCount := 0
263 for i, b := range h {
264 if b >= 0x80 {
265 if wantFirst == -1 {
266 wantFirst = i
267 }
268 wantCount++
269 }
270 }
271 require.Equal(t, wantFirst, FirstNonASCII(h), "size %d", n)
272 require.Equal(t, wantFirst, firstNonASCIIGeneric(h), "generic size %d", n)
273 require.Equal(t, wantCount, CountNonASCII(h), "size %d", n)
274 require.Equal(t, wantCount, countNonASCIIGeneric(h), "generic size %d", n)
275 require.Equal(t, wantFirst == -1, IsASCII(h), "size %d", n)
276
277 // A single non-ASCII byte at every position: the position has to
278 // survive the block loop's combined test and the per-vector
279 // re-extraction that locates it, and CountNonASCII has to find it
280 // whether it lands in the vector-aligned prefix or the SWAR tail.
281 clean := make([]byte, n)
282 for i := range clean {
283 clean[i] = byte(i % 0x80)
284 }
285 require.Equal(t, -1, FirstNonASCII(clean), "clean size %d", n)
286 require.Equal(t, 0, CountNonASCII(clean), "clean size %d", n)
287 for pos := range n {
288 orig := clean[pos]
289 clean[pos] = 0xc3
290 require.Equal(t, pos, FirstNonASCII(clean), "size %d pos %d", n, pos)
291 require.Equal(t, pos, firstNonASCIIGeneric(clean), "generic size %d pos %d", n, pos)
292 require.Equal(t, 1, CountNonASCII(clean), "size %d pos %d", n, pos)
293 require.Equal(t, 1, countNonASCIIGeneric(clean), "generic size %d pos %d", n, pos)
294 clean[pos] = orig
295 }
296 }
297 }
298
299 func Test_MemchrDigit(t *testing.T) {
300 t.Parallel()
301 require.Equal(t, -1, MemchrDigit(nil))
302 // Every byte value alone: exactly '0'..'9' match.
303 for b := range 256 {
304 want := -1
305 if b >= '0' && b <= '9' {
306 want = 0
307 }
308 h := []byte{byte(b)}
309 require.Equal(t, want, MemchrDigit(h), "byte %#x", b)
310 require.Equal(t, want, memchrDigitGeneric(h), "generic byte %#x", b)
311 }
312 for _, n := range testSizes {
313 clean := bytes.Repeat([]byte{'x'}, n)
314 require.Equal(t, -1, MemchrDigit(clean), "size %d", n)
315 for pos := range n {
316 for _, d := range []byte{'0', '5', '9'} {
317 h := bytes.Repeat([]byte{'x'}, n)
318 h[pos] = d
319 require.Equal(t, pos, MemchrDigit(h), "size %d pos %d", n, pos)
320 require.Equal(t, pos, memchrDigitGeneric(h), "generic size %d pos %d", n, pos)
321 }
322 // Range neighbors must not match.
323 h := bytes.Repeat([]byte{'x'}, n)
324 h[pos] = '0' - 1 // '/'
325 require.Equal(t, -1, MemchrDigit(h))
326 h[pos] = '9' + 1 // ':'
327 require.Equal(t, -1, MemchrDigit(h))
328 h[pos] = 0xb5 // '5' with the high bit set: signed-compare trap
329 require.Equal(t, -1, MemchrDigit(h))
330 }
331 }
332 }
333
334 func Test_MemchrDigitAt(t *testing.T) {
335 t.Parallel()
336 h := []byte("abc123def456")
337 require.Equal(t, 3, MemchrDigitAt(h, 0))
338 require.Equal(t, 3, MemchrDigitAt(h, 3))
339 require.Equal(t, 5, MemchrDigitAt(h, 5))
340 require.Equal(t, 9, MemchrDigitAt(h, 6))
341 require.Equal(t, -1, MemchrDigitAt(h, 12))
342 require.Equal(t, -1, MemchrDigitAt(h, 100))
343 require.Equal(t, -1, MemchrDigitAt(h, -1))
344 require.Equal(t, -1, MemchrDigitAt(nil, 0))
345 // In-bounds start with no digit at or after it.
346 require.Equal(t, -1, MemchrDigitAt([]byte("abc123xyz"), 6))
347 }
348
349 func refIsWord(b byte) bool {
350 return b == '_' || (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '0' && b <= '9')
351 }
352
353 func Test_MemchrWord_NotWord(t *testing.T) {
354 t.Parallel()
355 require.Equal(t, -1, MemchrWord(nil))
356 require.Equal(t, -1, MemchrNotWord(nil))
357 // Every byte value alone, including the range boundaries and their
358 // unsigned-compare neighbors ('A'-1, 'Z'+1, 'a'-1, 'z'+1, '_'±1, 0x80+).
359 for b := range 256 {
360 h := []byte{byte(b)}
361 wantWord := -1
362 wantNot := 0
363 if refIsWord(byte(b)) {
364 wantWord = 0
365 wantNot = -1
366 }
367 require.Equal(t, wantWord, MemchrWord(h), "byte %#x", b)
368 require.Equal(t, wantNot, MemchrNotWord(h), "byte %#x", b)
369 }
370 // Every byte value again, this time inside a buffer long enough to
371 // reach the vector kernels (and past the 128-byte block loop), so the
372 // class table is checked for all 256 values and not just at length 1.
373 for b := range 256 {
374 for _, size := range []int{32, 33, 63, 64, 129, 200} {
375 for _, pos := range []int{0, 1, 31, 32, size - 1} {
376 if pos >= size {
377 continue
378 }
379 word := bytes.Repeat([]byte{' '}, size)
380 word[pos] = byte(b)
381 wantWord := -1
382 if refIsWord(byte(b)) {
383 wantWord = pos
384 }
385 require.Equal(t, wantWord, MemchrWord(word), "byte %#x size %d pos %d", b, size, pos)
386 require.Equal(t, wantWord, memchrWordGeneric(word), "generic byte %#x size %d pos %d", b, size, pos)
387
388 not := bytes.Repeat([]byte{'k'}, size)
389 not[pos] = byte(b)
390 wantNot := pos
391 if refIsWord(byte(b)) {
392 wantNot = -1
393 }
394 require.Equal(t, wantNot, MemchrNotWord(not), "byte %#x size %d pos %d", b, size, pos)
395 require.Equal(t, wantNot, memchrNotWordGeneric(not), "generic byte %#x size %d pos %d", b, size, pos)
396 }
397 }
398 }
399 for _, n := range testSizes {
400 nonWord := bytes.Repeat([]byte{' '}, n)
401 require.Equal(t, -1, MemchrWord(nonWord), "size %d", n)
402 allWord := bytes.Repeat([]byte{'k'}, n)
403 require.Equal(t, -1, MemchrNotWord(allWord), "size %d", n)
404 for pos := range n {
405 for _, w := range []byte{'A', 'Z', 'a', 'z', '0', '9', '_'} {
406 h := bytes.Repeat([]byte{' '}, n)
407 h[pos] = w
408 require.Equal(t, pos, MemchrWord(h), "size %d pos %d byte %q", n, pos, w)
409 require.Equal(t, pos, memchrWordGeneric(h), "generic size %d pos %d", n, pos)
410 }
411 for _, nw := range []byte{' ', '@', '[', '`', '{', '/', ':', 0x80, 0xff} {
412 h := bytes.Repeat([]byte{'k'}, n)
413 h[pos] = nw
414 require.Equal(t, pos, MemchrNotWord(h), "size %d pos %d byte %#x", n, pos, nw)
415 require.Equal(t, pos, memchrNotWordGeneric(h), "generic size %d pos %d", n, pos)
416 }
417 }
418 }
419 }
420
421 func Test_MemchrInTable_NotInTable(t *testing.T) {
422 t.Parallel()
423 require.Equal(t, -1, MemchrInTable([]byte("abc"), nil))
424 require.Equal(t, -1, MemchrNotInTable([]byte("abc"), nil))
425 require.Equal(t, -1, MemchrInTable(nil, &[256]bool{}))
426 require.Equal(t, -1, MemchrNotInTable(nil, &[256]bool{}))
427
428 var vowels [256]bool
429 for _, c := range []byte("aeiou") {
430 vowels[c] = true
431 }
432 require.Equal(t, 1, MemchrInTable([]byte("halo"), &vowels))
433 require.Equal(t, 0, MemchrNotInTable([]byte("halo"), &vowels))
434 require.Equal(t, -1, MemchrInTable([]byte("xyz"), &vowels))
435 require.Equal(t, -1, MemchrNotInTable([]byte("aeiou"), &vowels))
436
437 for _, n := range testSizes {
438 h := fill(n, uint64(n)+13)
439 var table [256]bool
440 inSet := make(map[byte]bool, 86)
441 for i := range table {
442 if i%3 == 0 {
443 table[i] = true
444 inSet[byte(i)] = true
445 }
446 }
447 wantIn, wantNot := -1, -1
448 for i, b := range h {
449 if inSet[b] && wantIn == -1 {
450 wantIn = i
451 }
452 if !inSet[b] && wantNot == -1 {
453 wantNot = i
454 }
455 }
456 require.Equal(t, wantIn, MemchrInTable(h, &table), "size %d", n)
457 require.Equal(t, wantNot, MemchrNotInTable(h, &table), "size %d", n)
458 }
459 }
460
461 func Test_SelectRareBytes(t *testing.T) {
462 t.Parallel()
463 require.Equal(t, RareByteInfo{}, SelectRareBytes(nil))
464 require.Equal(t, RareByteInfo{Byte1: 'q', Byte2: 'q'}, SelectRareBytes([]byte("q")))
465
466 // 'z' (rank 20) is rarer than 'e' (rank 245) and 'l' (rank 175).
467 info := SelectRareBytes([]byte("zeel"))
468 require.Equal(t, byte('z'), info.Byte1)
469 require.Equal(t, 0, info.Index1)
470 require.Equal(t, byte('l'), info.Byte2)
471 require.Equal(t, 3, info.Index2)
472
473 // Duplicated leading rare byte: the distinct-preference rule must pick
474 // the common 'e' over the second 'z' (regression: seeding Byte2 from
475 // needle[1] kept the duplicate 'z' and disqualified such needles from
476 // the paired prefilter).
477 info = SelectRareBytes([]byte("zze"))
478 require.Equal(t, byte('z'), info.Byte1)
479 require.Equal(t, 0, info.Index1)
480 require.Equal(t, byte('e'), info.Byte2)
481 require.Equal(t, 2, info.Index2)
482
483 // Late promotions: 'z' (rank 20) and then 'Z' (rank 10) displace Byte1
484 // in turn, and the direct case must still improve Byte2 to 'q' (rank
485 // 15) afterwards instead of freezing on the demoted 'z'.
486 info = SelectRareBytes([]byte("ezZq"))
487 require.Equal(t, byte('Z'), info.Byte1)
488 require.Equal(t, 2, info.Index1)
489 require.Equal(t, byte('q'), info.Byte2)
490 require.Equal(t, 3, info.Index2)
491
492 // Byte2's value repeating: Index2 must be its first occurrence. Every
493 // other case's Byte2 value appears exactly once in its needle, so this
494 // is the only case separating first from last occurrence.
495 info = SelectRareBytes([]byte("zzee"))
496 require.Equal(t, byte('z'), info.Byte1)
497 require.Equal(t, 0, info.Index1)
498 require.Equal(t, byte('e'), info.Byte2)
499 require.Equal(t, 2, info.Index2)
500
501 for _, n := range []int{2, 3, 5, 8, 16, 32, 100} {
502 needle := fill(n, uint64(n)+29)
503 info := SelectRareBytes(needle)
504 // The reported bytes really sit at the reported indices, at the
505 // first occurrence of each value (memmemFallback's resume-point
506 // argument depends on the first-occurrence part).
507 require.Equal(t, bytes.IndexByte(needle, info.Byte1), info.Index1, "needle %q", needle)
508 require.Equal(t, bytes.IndexByte(needle, info.Byte2), info.Index2, "needle %q", needle)
509 // Byte1 is a rarest byte of the whole needle.
510 for _, b := range needle {
511 require.LessOrEqual(t, ByteRank(info.Byte1), ByteRank(b), "needle %q", needle)
512 }
513 require.LessOrEqual(t, ByteRank(info.Byte1), ByteRank(info.Byte2))
514 // Any needle with two distinct values must yield distinct bytes,
515 // and Byte2 must be a rarest value among those distinct from
516 // Byte1 (ties allowed) — the "rarest distinct second anchor"
517 // clause of the documented contract.
518 if bytes.Count(needle, needle[:1]) != len(needle) {
519 require.NotEqual(t, info.Byte1, info.Byte2, "needle %q", needle)
520 }
521 for _, b := range needle {
522 if b != info.Byte1 {
523 require.LessOrEqual(t, ByteRank(info.Byte2), ByteRank(b), "needle %q", needle)
524 }
525 }
526 }
527
528 // All-identical needle: no distinct second byte exists, and both
529 // slots collapse to the same first occurrence.
530 info = SelectRareBytes(bytes.Repeat([]byte{'a'}, 10))
531 require.Equal(t, byte('a'), info.Byte1)
532 require.Equal(t, byte('a'), info.Byte2)
533 require.Equal(t, 0, info.Index1)
534 require.Equal(t, 0, info.Index2)
535 }
536
537 func Test_ByteRank(t *testing.T) {
538 t.Parallel()
539 require.Equal(t, byteFrequencies['e'], ByteRank('e'))
540 require.Less(t, ByteRank('z'), ByteRank('e'))
541 require.Equal(t, byte(255), ByteRank(' '))
542 }
543
544 func checkMemmem(t *testing.T, h, needle []byte) {
545 t.Helper()
546 require.Equal(t, bytes.Index(h, needle), Memmem(h, needle), "haystack %d bytes, needle %q", len(h), needle)
547 }
548
549 func Test_Memmem(t *testing.T) {
550 t.Parallel()
551 // bytes.Index contract on edge cases.
552 require.Equal(t, 0, Memmem(nil, nil))
553 require.Equal(t, 0, Memmem([]byte("abc"), nil))
554 require.Equal(t, -1, Memmem(nil, []byte("a")))
555 require.Equal(t, -1, Memmem([]byte("ab"), []byte("abc")))
556 checkMemmem(t, []byte("hello world"), []byte("world"))
557 checkMemmem(t, []byte("hello world"), []byte("xyz"))
558 checkMemmem(t, []byte("aaaaaabaaaa"), []byte("aab"))
559
560 needles := [][]byte{
561 []byte("z"), []byte("zq"), []byte("abc"), []byte("q7z"),
562 []byte("aaa"), []byte("aab"), []byte("the quick brown fox"),
563 []byte("\x00\x01"), []byte("\xff\xfe\xfd"),
564 bytes.Repeat([]byte{'a'}, 33),
565 append(bytes.Repeat([]byte{'a'}, 40), 'b'),
566 }
567 for _, n := range testSizes {
568 // Text-like haystack (lowercase letters) and full-range haystack.
569 text := make([]byte, n)
570 for i := range text {
571 text[i] = 'a' + byte((i*7)%26)
572 }
573 random := fill(n, uint64(n)+31)
574 for _, needle := range needles {
575 checkMemmem(t, text, needle)
576 checkMemmem(t, random, needle)
577 // Plant the needle at the start, middle, and end.
578 if len(needle) <= n {
579 for _, pos := range []int{0, (n - len(needle)) / 2, n - len(needle)} {
580 h := bytes.Clone(text)
581 copy(h[pos:], needle)
582 checkMemmem(t, h, needle)
583 }
584 }
585 }
586 // Needle equals the whole haystack.
587 if n > 0 {
588 checkMemmem(t, text, text)
589 }
590 }
591
592 // Repetitive data with many false candidates for the prefilter.
593 big := bytes.Repeat([]byte("ab"), 300)
594 checkMemmem(t, big, []byte("aba"))
595 checkMemmem(t, big, []byte("abb"))
596 checkMemmem(t, big, append(bytes.Repeat([]byte("ab"), 20), 'c'))
597 almost := bytes.Repeat([]byte{'a'}, 500)
598 almost[499] = 'b'
599 checkMemmem(t, almost, []byte("aaab"))
600 checkMemmem(t, almost, []byte("ab"))
601 }
602
603 // checkMemmemInternal drives the prefilter helpers directly, so they are
604 // covered on every platform regardless of the hasAVX2 / 128-byte routing
605 // inside Memmem.
606 func checkMemmemInternal(t *testing.T, h, needle []byte) {
607 t.Helper()
608 want := bytes.Index(h, needle)
609 info := SelectRareBytes(needle)
610 require.Equal(t, want, memmemSingle(h, needle, info.Byte1, info.Index1),
611 "memmemSingle(%d bytes, %q)", len(h), needle)
612 if info.Byte1 != info.Byte2 {
613 require.Equal(t, want, memmemPaired(h, needle, info),
614 "memmemPaired(%d bytes, %q)", len(h), needle)
615 }
616 }
617
618 func Test_Memmem_InternalPaths(t *testing.T) {
619 t.Parallel()
620 // Regular haystacks, planted needles.
621 for _, n := range testSizes {
622 if n == 0 {
623 continue
624 }
625 text := make([]byte, n)
626 for i := range text {
627 text[i] = 'a' + byte((i*7)%26)
628 }
629 for _, needle := range [][]byte{
630 []byte("zq"), []byte("q7z"), []byte("the quick brown fox"),
631 append(bytes.Repeat([]byte{'a'}, 40), 'b'),
632 } {
633 checkMemmemInternal(t, text, needle)
634 if len(needle) <= n {
635 h := bytes.Clone(text)
636 copy(h[n-len(needle):], needle)
637 checkMemmemInternal(t, h, needle)
638 }
639 }
640 }
641
642 // Miss-budget fallback: every position is a rare-byte anchor, so the
643 // loops exhaust memmemMaxMisses and must hand over to memmemFallback
644 // without missing a late match or returning one out of order.
645 anchors := bytes.Repeat([]byte{'z'}, 400)
646 checkMemmemInternal(t, anchors, append(bytes.Repeat([]byte{'z'}, 50), 'b')) // absent
647 late := bytes.Repeat([]byte{'z'}, 400)
648 copy(late[350:], "zzzzb")
649 checkMemmemInternal(t, late, []byte("zzzzb")) // found only after fallback
650 // Paired-path miss budget: a short needle with two distinct rare bytes
651 // over a haystack dense in false ('z','q')-at-offset-1 pairs, so
652 // memmemPaired itself must exhaust memmemMaxMisses and hand over to
653 // memmemFallback on every platform (the all-'z' needles above exercise
654 // only memmemSingle's budget).
655 pairs := bytes.Repeat([]byte("zqf"), 100)
656 checkMemmemInternal(t, pairs, []byte("zqe")) // absent
657 pairsLate := bytes.Repeat([]byte("zqf"), 100)
658 copy(pairsLate[len(pairsLate)-3:], "zqe")
659 checkMemmemInternal(t, pairsLate, []byte("zqe")) // found only after fallback
660 // Nonzero anchor index (rare byte 'q' at needle position 2) with the
661 // match found only by the fallback: pins memmemFallback's translation
662 // from its bytes.Index-relative result back to haystack coordinates.
663 // (The start-anchorIdx resume point itself is defensive — no match can
664 // start inside [start-anchorIdx, start), because start-1 is an anchor
665 // and anchorIdx is the rare byte's first occurrence in the needle.)
666 h := bytes.Repeat([]byte{'q'}, 300)
667 for i := range 40 {
668 h[i*2] = 'e' // 'e' is common; 'q' stays the rare anchor everywhere
669 }
670 copy(h[60:], "eeq")
671 checkMemmemInternal(t, h, []byte("eeq"))
672 }
673
674 func Test_Memmem_AdversarialBounded(t *testing.T) {
675 t.Parallel()
676 // The O(n*m) trap from the code review: rare byte everywhere, long
677 // almost-matching needle. The miss budget must keep this exact (equal
678 // to bytes.Index) — timing is covered by Benchmark_Memmem_Adversarial.
679 haystack := bytes.Repeat([]byte{'z'}, 1<<16)
680 needle := append(bytes.Repeat([]byte{'z'}, 999), 'b')
681 checkMemmem(t, haystack, needle)
682 checkMemmemInternal(t, haystack, needle)
683 // Same shape but with the needle present at the very end.
684 present := bytes.Repeat([]byte{'z'}, 1<<16)
685 present[len(present)-1] = 'b'
686 checkMemmem(t, present, needle)
687 checkMemmemInternal(t, present, needle)
688 }
689
690 func Test_Accelerated(t *testing.T) {
691 t.Parallel()
692 // Pin the detection source: on amd64 the package must mirror the
693 // x/sys/cpu feature flag it initializes from; everywhere else the
694 // kernels do not exist and Accelerated must report false.
695 if runtime.GOARCH == "amd64" {
696 require.Equal(t, cpu.X86.HasAVX2, Accelerated())
697 } else {
698 require.False(t, Accelerated())
699 }
700 t.Logf("simd.Accelerated() = %v", Accelerated())
701 // The Test workflow sets this so runners known to have AVX2 prove the
702 // assembly kernels are actually under test, instead of silently
703 // green-lighting a fallback-only run (QEMU, GOAMD64-baseline VMs,
704 // detection bugs). Non-amd64 builds ignore it: the fallbacks are the
705 // intended implementation there.
706 if runtime.GOARCH == "amd64" && os.Getenv("GOFIBER_SIMD_REQUIRE_AVX2") == "1" {
707 require.True(t, Accelerated(), "GOFIBER_SIMD_REQUIRE_AVX2=1 but AVX2 kernels are not active")
708 }
709 }
710
711 func Test_TestSizesCoverDispatchBoundaries(t *testing.T) {
712 t.Parallel()
713 // Guard the sweep against accidental edits: it must include sub-word,
714 // word-with-tail, exactly-one-vector, whole-and-partial 128-byte
715 // block, and beyond-crossover sizes. 129/130/200 are what exercise the
716 // kernels' block loop handing off to the 32-byte loop and then to the
717 // overlapping final window; 128 and 512 divide evenly and leave both
718 // of those untouched.
719 for _, must := range []int{0, 7, 8, 31, 32, 33, 63, 64, 127, 128, 129, 130, 200, 512} {
720 require.Contains(t, testSizes, must, strconv.Itoa(must))
721 }
722 }