Debian Codegraph @

simd/simd_test.go

raw
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 // Test_CountNonASCII_LargeDense crosses the amd64 kernel's accumulator
300 // flush boundary: it counts in vector byte lanes and must fold them into
301 // wider lanes before a lane can reach 256, which only dense non-ASCII data
302 // of more than 127 128-byte blocks (16256 bytes) can provoke. Every lane
303 // position sees a non-ASCII byte in every vector here, so a missing or
304 // late flush shows up as a count short by a multiple of 256.
305 func Test_CountNonASCII_LargeDense(t *testing.T) {
306 t.Parallel()
307 const block = 128
308 for _, n := range []int{
309 127*block - 1, 127 * block, 127*block + 1, 127*block + 32,
310 127*block + 33, 128 * block, 254 * block, 254*block + 100,
311 255 * block, 1 << 16, 100_003,
312 } {
313 dense := bytes.Repeat([]byte{0xff}, n)
314 require.Equal(t, n, CountNonASCII(dense), "all 0xff, size %d", n)
315 require.Equal(t, n, countNonASCIIGeneric(dense), "generic all 0xff, size %d", n)
316
317 // Every other byte non-ASCII, so lanes fill at half rate, plus a
318 // full-range pattern with a few ASCII holes.
319 half := make([]byte, n)
320 for i := range half {
321 half[i] = byte(i%2) << 7
322 }
323 require.Equal(t, refCountNonASCII(half), CountNonASCII(half), "alternating, size %d", n)
324 mixed := fill(n, uint64(n)+97)
325 require.Equal(t, refCountNonASCII(mixed), CountNonASCII(mixed), "mixed, size %d", n)
326 require.Equal(t, refCountNonASCII(mixed), countNonASCIIGeneric(mixed), "generic mixed, size %d", n)
327 }
328 }
329
330 func Test_MemchrDigit(t *testing.T) {
331 t.Parallel()
332 require.Equal(t, -1, MemchrDigit(nil))
333 // Every byte value alone: exactly '0'..'9' match.
334 for b := range 256 {
335 want := -1
336 if b >= '0' && b <= '9' {
337 want = 0
338 }
339 h := []byte{byte(b)}
340 require.Equal(t, want, MemchrDigit(h), "byte %#x", b)
341 require.Equal(t, want, memchrDigitGeneric(h), "generic byte %#x", b)
342 }
343 for _, n := range testSizes {
344 clean := bytes.Repeat([]byte{'x'}, n)
345 require.Equal(t, -1, MemchrDigit(clean), "size %d", n)
346 for pos := range n {
347 for _, d := range []byte{'0', '5', '9'} {
348 h := bytes.Repeat([]byte{'x'}, n)
349 h[pos] = d
350 require.Equal(t, pos, MemchrDigit(h), "size %d pos %d", n, pos)
351 require.Equal(t, pos, memchrDigitGeneric(h), "generic size %d pos %d", n, pos)
352 }
353 // Range neighbors must not match.
354 h := bytes.Repeat([]byte{'x'}, n)
355 h[pos] = '0' - 1 // '/'
356 require.Equal(t, -1, MemchrDigit(h))
357 h[pos] = '9' + 1 // ':'
358 require.Equal(t, -1, MemchrDigit(h))
359 h[pos] = 0xb5 // '5' with the high bit set: signed-compare trap
360 require.Equal(t, -1, MemchrDigit(h))
361 }
362 }
363 }
364
365 func Test_MemchrDigitAt(t *testing.T) {
366 t.Parallel()
367 h := []byte("abc123def456")
368 require.Equal(t, 3, MemchrDigitAt(h, 0))
369 require.Equal(t, 3, MemchrDigitAt(h, 3))
370 require.Equal(t, 5, MemchrDigitAt(h, 5))
371 require.Equal(t, 9, MemchrDigitAt(h, 6))
372 require.Equal(t, -1, MemchrDigitAt(h, 12))
373 require.Equal(t, -1, MemchrDigitAt(h, 100))
374 require.Equal(t, -1, MemchrDigitAt(h, -1))
375 require.Equal(t, -1, MemchrDigitAt(nil, 0))
376 // In-bounds start with no digit at or after it.
377 require.Equal(t, -1, MemchrDigitAt([]byte("abc123xyz"), 6))
378 }
379
380 func refIsWord(b byte) bool {
381 return b == '_' || (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '0' && b <= '9')
382 }
383
384 func Test_MemchrWord_NotWord(t *testing.T) {
385 t.Parallel()
386 require.Equal(t, -1, MemchrWord(nil))
387 require.Equal(t, -1, MemchrNotWord(nil))
388 // Every byte value alone, including the range boundaries and their
389 // unsigned-compare neighbors ('A'-1, 'Z'+1, 'a'-1, 'z'+1, '_'±1, 0x80+).
390 for b := range 256 {
391 h := []byte{byte(b)}
392 wantWord := -1
393 wantNot := 0
394 if refIsWord(byte(b)) {
395 wantWord = 0
396 wantNot = -1
397 }
398 require.Equal(t, wantWord, MemchrWord(h), "byte %#x", b)
399 require.Equal(t, wantNot, MemchrNotWord(h), "byte %#x", b)
400 }
401 // Every byte value again, this time inside a buffer long enough to
402 // reach the vector kernels (and past the 128-byte block loop), so the
403 // class table is checked for all 256 values and not just at length 1.
404 for b := range 256 {
405 for _, size := range []int{32, 33, 63, 64, 129, 200} {
406 for _, pos := range []int{0, 1, 31, 32, size - 1} {
407 if pos >= size {
408 continue
409 }
410 word := bytes.Repeat([]byte{' '}, size)
411 word[pos] = byte(b)
412 wantWord := -1
413 if refIsWord(byte(b)) {
414 wantWord = pos
415 }
416 require.Equal(t, wantWord, MemchrWord(word), "byte %#x size %d pos %d", b, size, pos)
417 require.Equal(t, wantWord, memchrWordGeneric(word), "generic byte %#x size %d pos %d", b, size, pos)
418
419 not := bytes.Repeat([]byte{'k'}, size)
420 not[pos] = byte(b)
421 wantNot := pos
422 if refIsWord(byte(b)) {
423 wantNot = -1
424 }
425 require.Equal(t, wantNot, MemchrNotWord(not), "byte %#x size %d pos %d", b, size, pos)
426 require.Equal(t, wantNot, memchrNotWordGeneric(not), "generic byte %#x size %d pos %d", b, size, pos)
427 }
428 }
429 }
430 for _, n := range testSizes {
431 nonWord := bytes.Repeat([]byte{' '}, n)
432 require.Equal(t, -1, MemchrWord(nonWord), "size %d", n)
433 allWord := bytes.Repeat([]byte{'k'}, n)
434 require.Equal(t, -1, MemchrNotWord(allWord), "size %d", n)
435 for pos := range n {
436 for _, w := range []byte{'A', 'Z', 'a', 'z', '0', '9', '_'} {
437 h := bytes.Repeat([]byte{' '}, n)
438 h[pos] = w
439 require.Equal(t, pos, MemchrWord(h), "size %d pos %d byte %q", n, pos, w)
440 require.Equal(t, pos, memchrWordGeneric(h), "generic size %d pos %d", n, pos)
441 }
442 for _, nw := range []byte{' ', '@', '[', '`', '{', '/', ':', 0x80, 0xff} {
443 h := bytes.Repeat([]byte{'k'}, n)
444 h[pos] = nw
445 require.Equal(t, pos, MemchrNotWord(h), "size %d pos %d byte %#x", n, pos, nw)
446 require.Equal(t, pos, memchrNotWordGeneric(h), "generic size %d pos %d", n, pos)
447 }
448 }
449 }
450 }
451
452 func Test_MemchrInTable_NotInTable(t *testing.T) {
453 t.Parallel()
454 require.Equal(t, -1, MemchrInTable([]byte("abc"), nil))
455 require.Equal(t, -1, MemchrNotInTable([]byte("abc"), nil))
456 require.Equal(t, -1, MemchrInTable(nil, &[256]bool{}))
457 require.Equal(t, -1, MemchrNotInTable(nil, &[256]bool{}))
458
459 var vowels [256]bool
460 for _, c := range []byte("aeiou") {
461 vowels[c] = true
462 }
463 require.Equal(t, 1, MemchrInTable([]byte("halo"), &vowels))
464 require.Equal(t, 0, MemchrNotInTable([]byte("halo"), &vowels))
465 require.Equal(t, -1, MemchrInTable([]byte("xyz"), &vowels))
466 require.Equal(t, -1, MemchrNotInTable([]byte("aeiou"), &vowels))
467
468 for _, n := range testSizes {
469 h := fill(n, uint64(n)+13)
470 var table [256]bool
471 inSet := make(map[byte]bool, 86)
472 for i := range table {
473 if i%3 == 0 {
474 table[i] = true
475 inSet[byte(i)] = true
476 }
477 }
478 wantIn, wantNot := -1, -1
479 for i, b := range h {
480 if inSet[b] && wantIn == -1 {
481 wantIn = i
482 }
483 if !inSet[b] && wantNot == -1 {
484 wantNot = i
485 }
486 }
487 require.Equal(t, wantIn, MemchrInTable(h, &table), "size %d", n)
488 require.Equal(t, wantNot, MemchrNotInTable(h, &table), "size %d", n)
489 }
490 }
491
492 func Test_SelectRareBytes(t *testing.T) {
493 t.Parallel()
494 require.Equal(t, RareByteInfo{}, SelectRareBytes(nil))
495 require.Equal(t, RareByteInfo{Byte1: 'q', Byte2: 'q'}, SelectRareBytes([]byte("q")))
496
497 // 'z' (rank 20) is rarer than 'e' (rank 245) and 'l' (rank 175).
498 info := SelectRareBytes([]byte("zeel"))
499 require.Equal(t, byte('z'), info.Byte1)
500 require.Equal(t, 0, info.Index1)
501 require.Equal(t, byte('l'), info.Byte2)
502 require.Equal(t, 3, info.Index2)
503
504 // Duplicated leading rare byte: the distinct-preference rule must pick
505 // the common 'e' over the second 'z' (regression: seeding Byte2 from
506 // needle[1] kept the duplicate 'z' and disqualified such needles from
507 // the paired prefilter).
508 info = SelectRareBytes([]byte("zze"))
509 require.Equal(t, byte('z'), info.Byte1)
510 require.Equal(t, 0, info.Index1)
511 require.Equal(t, byte('e'), info.Byte2)
512 require.Equal(t, 2, info.Index2)
513
514 // Late promotions: 'z' (rank 20) and then 'Z' (rank 10) displace Byte1
515 // in turn, and the direct case must still improve Byte2 to 'q' (rank
516 // 15) afterwards instead of freezing on the demoted 'z'.
517 info = SelectRareBytes([]byte("ezZq"))
518 require.Equal(t, byte('Z'), info.Byte1)
519 require.Equal(t, 2, info.Index1)
520 require.Equal(t, byte('q'), info.Byte2)
521 require.Equal(t, 3, info.Index2)
522
523 // Byte2's value repeating: Index2 must be its first occurrence. Every
524 // other case's Byte2 value appears exactly once in its needle, so this
525 // is the only case separating first from last occurrence.
526 info = SelectRareBytes([]byte("zzee"))
527 require.Equal(t, byte('z'), info.Byte1)
528 require.Equal(t, 0, info.Index1)
529 require.Equal(t, byte('e'), info.Byte2)
530 require.Equal(t, 2, info.Index2)
531
532 for _, n := range []int{2, 3, 5, 8, 16, 32, 100} {
533 needle := fill(n, uint64(n)+29)
534 info := SelectRareBytes(needle)
535 // The reported bytes really sit at the reported indices, at the
536 // first occurrence of each value (memmemFallback's resume-point
537 // argument depends on the first-occurrence part).
538 require.Equal(t, bytes.IndexByte(needle, info.Byte1), info.Index1, "needle %q", needle)
539 require.Equal(t, bytes.IndexByte(needle, info.Byte2), info.Index2, "needle %q", needle)
540 // Byte1 is a rarest byte of the whole needle.
541 for _, b := range needle {
542 require.LessOrEqual(t, ByteRank(info.Byte1), ByteRank(b), "needle %q", needle)
543 }
544 require.LessOrEqual(t, ByteRank(info.Byte1), ByteRank(info.Byte2))
545 // Any needle with two distinct values must yield distinct bytes,
546 // and Byte2 must be a rarest value among those distinct from
547 // Byte1 (ties allowed) — the "rarest distinct second anchor"
548 // clause of the documented contract.
549 if bytes.Count(needle, needle[:1]) != len(needle) {
550 require.NotEqual(t, info.Byte1, info.Byte2, "needle %q", needle)
551 }
552 for _, b := range needle {
553 if b != info.Byte1 {
554 require.LessOrEqual(t, ByteRank(info.Byte2), ByteRank(b), "needle %q", needle)
555 }
556 }
557 }
558
559 // All-identical needle: no distinct second byte exists, and both
560 // slots collapse to the same first occurrence.
561 info = SelectRareBytes(bytes.Repeat([]byte{'a'}, 10))
562 require.Equal(t, byte('a'), info.Byte1)
563 require.Equal(t, byte('a'), info.Byte2)
564 require.Equal(t, 0, info.Index1)
565 require.Equal(t, 0, info.Index2)
566 }
567
568 func Test_ByteRank(t *testing.T) {
569 t.Parallel()
570 require.Equal(t, byteFrequencies['e'], ByteRank('e'))
571 require.Less(t, ByteRank('z'), ByteRank('e'))
572 require.Equal(t, byte(255), ByteRank(' '))
573 }
574
575 func checkMemmem(t *testing.T, h, needle []byte) {
576 t.Helper()
577 require.Equal(t, bytes.Index(h, needle), Memmem(h, needle), "haystack %d bytes, needle %q", len(h), needle)
578 }
579
580 func Test_Memmem(t *testing.T) {
581 t.Parallel()
582 // bytes.Index contract on edge cases.
583 require.Equal(t, 0, Memmem(nil, nil))
584 require.Equal(t, 0, Memmem([]byte("abc"), nil))
585 require.Equal(t, -1, Memmem(nil, []byte("a")))
586 require.Equal(t, -1, Memmem([]byte("ab"), []byte("abc")))
587 checkMemmem(t, []byte("hello world"), []byte("world"))
588 checkMemmem(t, []byte("hello world"), []byte("xyz"))
589 checkMemmem(t, []byte("aaaaaabaaaa"), []byte("aab"))
590
591 needles := [][]byte{
592 []byte("z"), []byte("zq"), []byte("abc"), []byte("q7z"),
593 []byte("aaa"), []byte("aab"), []byte("the quick brown fox"),
594 []byte("\x00\x01"), []byte("\xff\xfe\xfd"),
595 bytes.Repeat([]byte{'a'}, 33),
596 append(bytes.Repeat([]byte{'a'}, 40), 'b'),
597 }
598 for _, n := range testSizes {
599 // Text-like haystack (lowercase letters) and full-range haystack.
600 text := make([]byte, n)
601 for i := range text {
602 text[i] = 'a' + byte((i*7)%26)
603 }
604 random := fill(n, uint64(n)+31)
605 for _, needle := range needles {
606 checkMemmem(t, text, needle)
607 checkMemmem(t, random, needle)
608 // Plant the needle at the start, middle, and end.
609 if len(needle) <= n {
610 for _, pos := range []int{0, (n - len(needle)) / 2, n - len(needle)} {
611 h := bytes.Clone(text)
612 copy(h[pos:], needle)
613 checkMemmem(t, h, needle)
614 }
615 }
616 }
617 // Needle equals the whole haystack.
618 if n > 0 {
619 checkMemmem(t, text, text)
620 }
621 }
622
623 // Repetitive data with many false candidates for the prefilter.
624 big := bytes.Repeat([]byte("ab"), 300)
625 checkMemmem(t, big, []byte("aba"))
626 checkMemmem(t, big, []byte("abb"))
627 checkMemmem(t, big, append(bytes.Repeat([]byte("ab"), 20), 'c'))
628 almost := bytes.Repeat([]byte{'a'}, 500)
629 almost[499] = 'b'
630 checkMemmem(t, almost, []byte("aaab"))
631 checkMemmem(t, almost, []byte("ab"))
632 }
633
634 // checkMemmemInternal drives the prefilter helpers directly, so they are
635 // covered on every platform regardless of the hasAVX2 / 128-byte routing
636 // inside Memmem.
637 func checkMemmemInternal(t *testing.T, h, needle []byte) {
638 t.Helper()
639 want := bytes.Index(h, needle)
640 info := SelectRareBytes(needle)
641 require.Equal(t, want, memmemSingle(h, needle, info.Byte1, info.Index1),
642 "memmemSingle(%d bytes, %q)", len(h), needle)
643 if info.Byte1 != info.Byte2 {
644 require.Equal(t, want, memmemPaired(h, needle, info),
645 "memmemPaired(%d bytes, %q)", len(h), needle)
646 }
647 }
648
649 func Test_Memmem_InternalPaths(t *testing.T) {
650 t.Parallel()
651 // Regular haystacks, planted needles.
652 for _, n := range testSizes {
653 if n == 0 {
654 continue
655 }
656 text := make([]byte, n)
657 for i := range text {
658 text[i] = 'a' + byte((i*7)%26)
659 }
660 for _, needle := range [][]byte{
661 []byte("zq"), []byte("q7z"), []byte("the quick brown fox"),
662 append(bytes.Repeat([]byte{'a'}, 40), 'b'),
663 } {
664 checkMemmemInternal(t, text, needle)
665 if len(needle) <= n {
666 h := bytes.Clone(text)
667 copy(h[n-len(needle):], needle)
668 checkMemmemInternal(t, h, needle)
669 }
670 }
671 }
672
673 // Miss-budget fallback: every position is a rare-byte anchor, so the
674 // loops exhaust memmemMaxMisses and must hand over to memmemFallback
675 // without missing a late match or returning one out of order.
676 anchors := bytes.Repeat([]byte{'z'}, 400)
677 checkMemmemInternal(t, anchors, append(bytes.Repeat([]byte{'z'}, 50), 'b')) // absent
678 late := bytes.Repeat([]byte{'z'}, 400)
679 copy(late[350:], "zzzzb")
680 checkMemmemInternal(t, late, []byte("zzzzb")) // found only after fallback
681 // Paired-path miss budget: a short needle with two distinct rare bytes
682 // over a haystack dense in false ('z','q')-at-offset-1 pairs, so
683 // memmemPaired itself must exhaust memmemMaxMisses and hand over to
684 // memmemFallback on every platform (the all-'z' needles above exercise
685 // only memmemSingle's budget).
686 pairs := bytes.Repeat([]byte("zqf"), 100)
687 checkMemmemInternal(t, pairs, []byte("zqe")) // absent
688 pairsLate := bytes.Repeat([]byte("zqf"), 100)
689 copy(pairsLate[len(pairsLate)-3:], "zqe")
690 checkMemmemInternal(t, pairsLate, []byte("zqe")) // found only after fallback
691 // Nonzero anchor index (rare byte 'q' at needle position 2) with the
692 // match found only by the fallback: pins memmemFallback's translation
693 // from its bytes.Index-relative result back to haystack coordinates.
694 // (The start-anchorIdx resume point itself is defensive — no match can
695 // start inside [start-anchorIdx, start), because start-1 is an anchor
696 // and anchorIdx is the rare byte's first occurrence in the needle.)
697 h := bytes.Repeat([]byte{'q'}, 300)
698 for i := range 40 {
699 h[i*2] = 'e' // 'e' is common; 'q' stays the rare anchor everywhere
700 }
701 copy(h[60:], "eeq")
702 checkMemmemInternal(t, h, []byte("eeq"))
703 }
704
705 func Test_Memmem_AdversarialBounded(t *testing.T) {
706 t.Parallel()
707 // The O(n*m) trap from the code review: rare byte everywhere, long
708 // almost-matching needle. The miss budget must keep this exact (equal
709 // to bytes.Index) — timing is covered by Benchmark_Memmem_Adversarial.
710 haystack := bytes.Repeat([]byte{'z'}, 1<<16)
711 needle := append(bytes.Repeat([]byte{'z'}, 999), 'b')
712 checkMemmem(t, haystack, needle)
713 checkMemmemInternal(t, haystack, needle)
714 // Same shape but with the needle present at the very end.
715 present := bytes.Repeat([]byte{'z'}, 1<<16)
716 present[len(present)-1] = 'b'
717 checkMemmem(t, present, needle)
718 checkMemmemInternal(t, present, needle)
719 }
720
721 func Test_Accelerated(t *testing.T) {
722 t.Parallel()
723 // Pin the detection source: on amd64 the package must mirror the
724 // x/sys/cpu feature flag it initializes from; everywhere else the
725 // kernels do not exist and Accelerated must report false.
726 if runtime.GOARCH == "amd64" {
727 require.Equal(t, cpu.X86.HasAVX2, Accelerated())
728 } else {
729 require.False(t, Accelerated())
730 }
731 t.Logf("simd.Accelerated() = %v", Accelerated())
732 // The Test workflow sets this so runners known to have AVX2 prove the
733 // assembly kernels are actually under test, instead of silently
734 // green-lighting a fallback-only run (QEMU, GOAMD64-baseline VMs,
735 // detection bugs). Non-amd64 builds ignore it: the fallbacks are the
736 // intended implementation there.
737 if runtime.GOARCH == "amd64" && os.Getenv("GOFIBER_SIMD_REQUIRE_AVX2") == "1" {
738 require.True(t, Accelerated(), "GOFIBER_SIMD_REQUIRE_AVX2=1 but AVX2 kernels are not active")
739 }
740 }
741
742 func Test_TestSizesCoverDispatchBoundaries(t *testing.T) {
743 t.Parallel()
744 // Guard the sweep against accidental edits: it must include sub-word,
745 // word-with-tail, exactly-one-vector, whole-and-partial 128-byte
746 // block, and beyond-crossover sizes. 129/130/200 are what exercise the
747 // kernels' block loop handing off to the 32-byte loop and then to the
748 // overlapping final window; 128 and 512 divide evenly and leave both
749 // of those untouched.
750 for _, must := range []int{0, 7, 8, 31, 32, 33, 63, 64, 127, 128, 129, 130, 200, 512} {
751 require.Contains(t, testSizes, must, strconv.Itoa(must))
752 }
753 }