Skip to content
Myr

Add SIMD indexByteTwo/lastIndexByteTwo for faster prefiltering

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Use SIMD to search for two bytes simultaneously, replacing the two-pass bytes.IndexByte approach in trySkip and the scalar backward loop in asciiFuzzyIndex. AVX2+SSE2 on amd64, NEON on arm64, with scalar fallback for other architectures. === query: 'l' === [all] baseline: 100.61ms current: 98.88ms (+1.7%) matches: 5069891 (94.78%) [1T] baseline: 889.28ms current: 852.71ms (+4.1%) matches: 5069891 (94.78%) === query: 'lin' === [all] baseline: 281.31ms current: 269.35ms (+4.3%) matches: 3516507 (65.74%) [1T] baseline: 2266.51ms current: 2238.24ms (+1.2%) matches: 3516507 (65.74%) === query: 'linux' === [all] baseline: 69.94ms current: 68.33ms (+2.3%) matches: 307229 (5.74%) [1T] baseline: 642.66ms current: 589.10ms (+8.3%) matches: 307229 (5.74%) === query: 'linuxlinux' === [all] baseline: 39.56ms current: 35.48ms (+10.3%) matches: 12230 (0.23%) [1T] baseline: 367.88ms current: 333.49ms (+9.3%) matches: 12230 (0.23%) === query: 'linuxlinuxlinux' === [all] baseline: 36.22ms current: 31.59ms (+12.8%) matches: 865 (0.02%) [1T] baseline: 339.48ms current: 293.02ms (+13.7%) matches: 865 (0.02%)

authored by Junegunn Choi · committed by Junegunn Choi · parent 4866c34 · Browse files · 7 files+975 added−20 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+975 added−20 removed

  • other:+975 added−20 removed

7 files+975 added−20 removed

modified:src/algo/algo.go+16 added-20 removed
319 unmodified lines
320type Algo func(caseSensitive bool, normalize bool, forward bool, input *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int)321322func trySkip(input *util.Chars, caseSensitive bool, b byte, from int) int {323 byteArray := input.Bytes()[from:]324 idx := bytes.IndexByte(byteArray, b)325 if idx == 0 {326 // Can't skip any further327 return from328 }329 // We may need to search for the uppercase letter again. We don't have to330 // consider normalization as we can be sure that this is an ASCII string.324 // For case-insensitive search of a letter, search for both cases in one pass325 if !caseSensitive && b >= 'a' && b <= 'z' {332 if idx > 0 {333 byteArray = byteArray[:idx]326 idx := indexByteTwo(byteArray, b, b-32)327 if idx < 0 {328 return -1329 }335 uidx := bytes.IndexByte(byteArray, b-32)336 if uidx >= 0 {337 idx = uidx338 }330 return from + idx331 }332 idx := bytes.IndexByte(byteArray, b)333 if idx < 0 {334 return -1335 }336 return from + idx
35 unmodified lines
372 idx++373 }374375 // Find the last appearance of the last character of the pattern to limit the search scope383 bu := b384 if !caseSensitive && b >= 'a' && b <= 'z' {385 bu = b - 32386 }376 scope := input.Bytes()[lastIdx:]388 for offset := len(scope) - 1; offset > 0; offset-- {389 if scope[offset] == b || scope[offset] == bu {390 return firstIdx, lastIdx + offset + 1377 if len(scope) > 1 {378 tail := scope[1:]379 var end int380 if !caseSensitive && b >= 'a' && b <= 'z' {381 end = lastIndexByteTwo(tail, b, b-32)382 } else {383 end = bytes.LastIndexByte(tail, b)384 }385 if end >= 0 {386 return firstIdx, lastIdx + 1 + end + 1387 }388 }389 return firstIdx, lastIdx + 1390}391
639 unmodified lines
added:src/algo/indexbyte2_amd64.go+24 added
1//go:build amd6423package algo45var _useAVX2 bool67func init() {8 _useAVX2 = cpuHasAVX2()9}1011//go:noescape12func cpuHasAVX2() bool1314// indexByteTwo returns the index of the first occurrence of b1 or b2 in s,15// or -1 if neither is present. Uses AVX2 when available, SSE2 otherwise.16//17//go:noescape18func indexByteTwo(s []byte, b1, b2 byte) int1920// lastIndexByteTwo returns the index of the last occurrence of b1 or b2 in s,21// or -1 if neither is present. Uses AVX2 when available, SSE2 otherwise.22//23//go:noescape24func lastIndexByteTwo(s []byte, b1, b2 byte) int
added:src/algo/indexbyte2_amd64.s+377 added
1#include "textflag.h"23// func cpuHasAVX2() bool4//5// Checks CPUID and XGETBV for AVX2 + OS YMM support.6TEXT ·cpuHasAVX2(SB),NOSPLIT,$0-17 MOVQ BX, R8 // save BX (callee-saved, clobbered by CPUID)89 // Check max CPUID leaf >= 710 MOVL $0, AX11 CPUID12 CMPL AX, $713 JL cpuid_no1415 // Check OSXSAVE (CPUID.1:ECX bit 27)16 MOVL $1, AX17 CPUID18 TESTL $(1<<27), CX19 JZ cpuid_no2021 // Check AVX2 (CPUID.7.0:EBX bit 5)22 MOVL $7, AX23 MOVL $0, CX24 CPUID25 TESTL $(1<<5), BX26 JZ cpuid_no2728 // Check OS YMM state support via XGETBV29 MOVL $0, CX30 BYTE $0x0F; BYTE $0x01; BYTE $0xD0 // XGETBV → EDX:EAX31 ANDL $6, AX // bits 1 (XMM) and 2 (YMM)32 CMPL AX, $633 JNE cpuid_no3435 MOVQ R8, BX // restore BX36 MOVB $1, ret+0(FP)37 RET3839cpuid_no:40 MOVQ R8, BX41 MOVB $0, ret+0(FP)42 RET4344// func indexByteTwo(s []byte, b1, b2 byte) int45//46// Returns the index of the first occurrence of b1 or b2 in s, or -1.47// Uses AVX2 (32 bytes/iter) when available, SSE2 (16 bytes/iter) otherwise.48TEXT ·indexByteTwo(SB),NOSPLIT,$0-4049 MOVQ s_base+0(FP), SI50 MOVQ s_len+8(FP), BX51 MOVBLZX b1+24(FP), AX52 MOVBLZX b2+25(FP), CX53 LEAQ ret+32(FP), R85455 TESTQ BX, BX56 JEQ fwd_failure5758 // Try AVX2 for inputs >= 32 bytes59 CMPQ BX, $3260 JLT fwd_sse261 CMPB ·_useAVX2(SB), $162 JNE fwd_sse26364 // ====== AVX2 forward search ======65 MOVD AX, X066 VPBROADCASTB X0, Y0 // Y0 = splat(b1)67 MOVD CX, X168 VPBROADCASTB X1, Y1 // Y1 = splat(b2)6970 MOVQ SI, DI71 LEAQ -32(SI)(BX*1), AX // AX = last valid 32-byte chunk72 JMP fwd_avx2_entry7374fwd_avx2_loop:75 VMOVDQU (DI), Y276 VPCMPEQB Y0, Y2, Y377 VPCMPEQB Y1, Y2, Y478 VPOR Y3, Y4, Y379 VPMOVMSKB Y3, DX80 BSFL DX, DX81 JNZ fwd_avx2_success82 ADDQ $32, DI8384fwd_avx2_entry:85 CMPQ DI, AX86 JB fwd_avx2_loop8788 // Last 32-byte chunk (may overlap with previous)89 MOVQ AX, DI90 VMOVDQU (AX), Y291 VPCMPEQB Y0, Y2, Y392 VPCMPEQB Y1, Y2, Y493 VPOR Y3, Y4, Y394 VPMOVMSKB Y3, DX95 BSFL DX, DX96 JNZ fwd_avx2_success9798 MOVQ $-1, (R8)99 VZEROUPPER100 RET101102fwd_avx2_success:103 SUBQ SI, DI104 ADDQ DX, DI105 MOVQ DI, (R8)106 VZEROUPPER107 RET108109 // ====== SSE2 forward search (< 32 bytes or no AVX2) ======110111fwd_sse2:112 // Broadcast b1 into X0113 MOVD AX, X0114 PUNPCKLBW X0, X0115 PUNPCKLBW X0, X0116 PSHUFL $0, X0, X0117118 // Broadcast b2 into X4119 MOVD CX, X4120 PUNPCKLBW X4, X4121 PUNPCKLBW X4, X4122 PSHUFL $0, X4, X4123124 CMPQ BX, $16125 JLT fwd_small126127 MOVQ SI, DI128 LEAQ -16(SI)(BX*1), AX129 JMP fwd_sseloopentry130131fwd_sseloop:132 MOVOU (DI), X1133 MOVOU X1, X2134 PCMPEQB X0, X1135 PCMPEQB X4, X2136 POR X2, X1137 PMOVMSKB X1, DX138 BSFL DX, DX139 JNZ fwd_ssesuccess140 ADDQ $16, DI141142fwd_sseloopentry:143 CMPQ DI, AX144 JB fwd_sseloop145146 // Search the last 16-byte chunk (may overlap)147 MOVQ AX, DI148 MOVOU (AX), X1149 MOVOU X1, X2150 PCMPEQB X0, X1151 PCMPEQB X4, X2152 POR X2, X1153 PMOVMSKB X1, DX154 BSFL DX, DX155 JNZ fwd_ssesuccess156157fwd_failure:158 MOVQ $-1, (R8)159 RET160161fwd_ssesuccess:162 SUBQ SI, DI163 ADDQ DX, DI164 MOVQ DI, (R8)165 RET166167fwd_small:168 // Check if loading 16 bytes from SI would cross a page boundary169 LEAQ 16(SI), AX170 TESTW $0xff0, AX171 JEQ fwd_endofpage172173 MOVOU (SI), X1174 MOVOU X1, X2175 PCMPEQB X0, X1176 PCMPEQB X4, X2177 POR X2, X1178 PMOVMSKB X1, DX179 BSFL DX, DX180 JZ fwd_failure181 CMPL DX, BX182 JAE fwd_failure183 MOVQ DX, (R8)184 RET185186fwd_endofpage:187 MOVOU -16(SI)(BX*1), X1188 MOVOU X1, X2189 PCMPEQB X0, X1190 PCMPEQB X4, X2191 POR X2, X1192 PMOVMSKB X1, DX193 MOVL BX, CX194 SHLL CX, DX195 SHRL $16, DX196 BSFL DX, DX197 JZ fwd_failure198 MOVQ DX, (R8)199 RET200201// func lastIndexByteTwo(s []byte, b1, b2 byte) int202//203// Returns the index of the last occurrence of b1 or b2 in s, or -1.204// Uses AVX2 (32 bytes/iter) when available, SSE2 (16 bytes/iter) otherwise.205TEXT ·lastIndexByteTwo(SB),NOSPLIT,$0-40206 MOVQ s_base+0(FP), SI207 MOVQ s_len+8(FP), BX208 MOVBLZX b1+24(FP), AX209 MOVBLZX b2+25(FP), CX210 LEAQ ret+32(FP), R8211212 TESTQ BX, BX213 JEQ back_failure214215 // Try AVX2 for inputs >= 32 bytes216 CMPQ BX, $32217 JLT back_sse2218 CMPB ·_useAVX2(SB), $1219 JNE back_sse2220221 // ====== AVX2 backward search ======222 MOVD AX, X0223 VPBROADCASTB X0, Y0224 MOVD CX, X1225 VPBROADCASTB X1, Y1226227 // DI = start of last 32-byte chunk228 LEAQ -32(SI)(BX*1), DI229230back_avx2_loop:231 CMPQ DI, SI232 JBE back_avx2_first233234 VMOVDQU (DI), Y2235 VPCMPEQB Y0, Y2, Y3236 VPCMPEQB Y1, Y2, Y4237 VPOR Y3, Y4, Y3238 VPMOVMSKB Y3, DX239 BSRL DX, DX240 JNZ back_avx2_success241 SUBQ $32, DI242 JMP back_avx2_loop243244back_avx2_first:245 // First 32 bytes (DI <= SI, load from SI)246 VMOVDQU (SI), Y2247 VPCMPEQB Y0, Y2, Y3248 VPCMPEQB Y1, Y2, Y4249 VPOR Y3, Y4, Y3250 VPMOVMSKB Y3, DX251 BSRL DX, DX252 JNZ back_avx2_firstsuccess253254 MOVQ $-1, (R8)255 VZEROUPPER256 RET257258back_avx2_success:259 SUBQ SI, DI260 ADDQ DX, DI261 MOVQ DI, (R8)262 VZEROUPPER263 RET264265back_avx2_firstsuccess:266 MOVQ DX, (R8)267 VZEROUPPER268 RET269270 // ====== SSE2 backward search (< 32 bytes or no AVX2) ======271272back_sse2:273 // Broadcast b1 into X0274 MOVD AX, X0275 PUNPCKLBW X0, X0276 PUNPCKLBW X0, X0277 PSHUFL $0, X0, X0278279 // Broadcast b2 into X4280 MOVD CX, X4281 PUNPCKLBW X4, X4282 PUNPCKLBW X4, X4283 PSHUFL $0, X4, X4284285 CMPQ BX, $16286 JLT back_small287288 // DI = start of last 16-byte chunk289 LEAQ -16(SI)(BX*1), DI290291back_sseloop:292 CMPQ DI, SI293 JBE back_ssefirst294295 MOVOU (DI), X1296 MOVOU X1, X2297 PCMPEQB X0, X1298 PCMPEQB X4, X2299 POR X2, X1300 PMOVMSKB X1, DX301 BSRL DX, DX302 JNZ back_ssesuccess303 SUBQ $16, DI304 JMP back_sseloop305306back_ssefirst:307 // First 16 bytes (DI <= SI, load from SI)308 MOVOU (SI), X1309 MOVOU X1, X2310 PCMPEQB X0, X1311 PCMPEQB X4, X2312 POR X2, X1313 PMOVMSKB X1, DX314 BSRL DX, DX315 JNZ back_ssefirstsuccess316317back_failure:318 MOVQ $-1, (R8)319 RET320321back_ssesuccess:322 SUBQ SI, DI323 ADDQ DX, DI324 MOVQ DI, (R8)325 RET326327back_ssefirstsuccess:328 // DX = byte offset from base329 MOVQ DX, (R8)330 RET331332back_small:333 // Check page boundary334 LEAQ 16(SI), AX335 TESTW $0xff0, AX336 JEQ back_endofpage337338 MOVOU (SI), X1339 MOVOU X1, X2340 PCMPEQB X0, X1341 PCMPEQB X4, X2342 POR X2, X1343 PMOVMSKB X1, DX344 // Mask to first BX bytes: keep bits 0..BX-1345 MOVL $1, AX346 MOVL BX, CX347 SHLL CX, AX348 DECL AX349 ANDL AX, DX350 BSRL DX, DX351 JZ back_failure352 MOVQ DX, (R8)353 RET354355back_endofpage:356 // Load 16 bytes ending at base+n357 MOVOU -16(SI)(BX*1), X1358 MOVOU X1, X2359 PCMPEQB X0, X1360 PCMPEQB X4, X2361 POR X2, X1362 PMOVMSKB X1, DX363 // Bits correspond to bytes [base+n-16, base+n).364 // We want original bytes [0, n), which are bits [16-n, 16).365 // Mask: keep bits (16-n) through 15.366 MOVL $16, CX367 SUBL BX, CX368 SHRL CX, DX369 SHLL CX, DX370 BSRL DX, DX371 JZ back_failure372 // DX is the bit position in the loaded chunk.373 // Original byte index = DX - (16 - n) = DX + n - 16374 ADDL BX, DX375 SUBL $16, DX376 MOVQ DX, (R8)377 RET
added:src/algo/indexbyte2_arm64.go+17 added
1//go:build arm6423package algo45// indexByteTwo returns the index of the first occurrence of b1 or b2 in s,6// or -1 if neither is present. Implemented in assembly using ARM64 NEON7// to search for both bytes in a single pass.8//9//go:noescape10func indexByteTwo(s []byte, b1, b2 byte) int1112// lastIndexByteTwo returns the index of the last occurrence of b1 or b2 in s,13// or -1 if neither is present. Implemented in assembly using ARM64 NEON,14// scanning backward.15//16//go:noescape17func lastIndexByteTwo(s []byte, b1, b2 byte) int
added:src/algo/indexbyte2_arm64.s+249 added
1#include "textflag.h"23// func indexByteTwo(s []byte, b1, b2 byte) int4//5// Returns the index of the first occurrence of b1 or b2 in s, or -1.6// Uses ARM64 NEON to search for both bytes in a single pass over the data.7// Adapted from Go's internal/bytealg/indexbyte_arm64.s (single-byte version).8TEXT ·indexByteTwo(SB),NOSPLIT,$0-409 MOVD s_base+0(FP), R010 MOVD s_len+8(FP), R211 MOVBU b1+24(FP), R112 MOVBU b2+25(FP), R713 MOVD $ret+32(FP), R81415 // Core algorithm:16 // For each 32-byte chunk we calculate a 64-bit syndrome value,17 // with two bits per byte. We compare against both b1 and b2,18 // OR the results, then use the same syndrome extraction as19 // Go's IndexByte.2021 CBZ R2, fail22 MOVD R0, R1123 // Magic constant 0x40100401 allows us to identify which lane matches.24 // Each byte in the group of 4 gets a distinct bit: 1, 4, 16, 64.25 MOVD $0x40100401, R526 VMOV R1, V0.B16 // V0 = splat(b1)27 VMOV R7, V7.B16 // V7 = splat(b2)28 // Work with aligned 32-byte chunks29 BIC $0x1f, R0, R330 VMOV R5, V5.S431 ANDS $0x1f, R0, R932 AND $0x1f, R2, R1033 BEQ loop3435 // Input string is not 32-byte aligned. Process the first36 // aligned 32-byte block and mask off bytes before our start.37 VLD1.P (R3), [V1.B16, V2.B16]38 SUB $0x20, R9, R439 ADDS R4, R2, R240 // Compare against both needles41 VCMEQ V0.B16, V1.B16, V3.B16 // b1 vs first 16 bytes42 VCMEQ V7.B16, V1.B16, V8.B16 // b2 vs first 16 bytes43 VORR V8.B16, V3.B16, V3.B16 // combine44 VCMEQ V0.B16, V2.B16, V4.B16 // b1 vs second 16 bytes45 VCMEQ V7.B16, V2.B16, V9.B16 // b2 vs second 16 bytes46 VORR V9.B16, V4.B16, V4.B16 // combine47 // Build syndrome48 VAND V5.B16, V3.B16, V3.B1649 VAND V5.B16, V4.B16, V4.B1650 VADDP V4.B16, V3.B16, V6.B1651 VADDP V6.B16, V6.B16, V6.B1652 VMOV V6.D[0], R653 // Clear the irrelevant lower bits54 LSL $1, R9, R455 LSR R4, R6, R656 LSL R4, R6, R657 // The first block can also be the last58 BLS masklast59 // Have we found something already?60 CBNZ R6, tail6162loop:63 VLD1.P (R3), [V1.B16, V2.B16]64 SUBS $0x20, R2, R265 // Compare against both needles, OR results66 VCMEQ V0.B16, V1.B16, V3.B1667 VCMEQ V7.B16, V1.B16, V8.B1668 VORR V8.B16, V3.B16, V3.B1669 VCMEQ V0.B16, V2.B16, V4.B1670 VCMEQ V7.B16, V2.B16, V9.B1671 VORR V9.B16, V4.B16, V4.B1672 // If we're out of data we finish regardless of the result73 BLS end74 // Fast check: OR both halves and check for any match75 VORR V4.B16, V3.B16, V6.B1676 VADDP V6.D2, V6.D2, V6.D277 VMOV V6.D[0], R678 CBZ R6, loop7980end:81 // Found something or out of data — build full syndrome82 VAND V5.B16, V3.B16, V3.B1683 VAND V5.B16, V4.B16, V4.B1684 VADDP V4.B16, V3.B16, V6.B1685 VADDP V6.B16, V6.B16, V6.B1686 VMOV V6.D[0], R687 // Only mask for the last block88 BHS tail8990masklast:91 // Clear irrelevant upper bits92 ADD R9, R10, R493 AND $0x1f, R4, R494 SUB $0x20, R4, R495 NEG R4<<1, R496 LSL R4, R6, R697 LSR R4, R6, R69899tail:100 CBZ R6, fail101 RBIT R6, R6102 SUB $0x20, R3, R3103 CLZ R6, R6104 ADD R6>>1, R3, R0105 SUB R11, R0, R0106 MOVD R0, (R8)107 RET108109fail:110 MOVD $-1, R0111 MOVD R0, (R8)112 RET113114// func lastIndexByteTwo(s []byte, b1, b2 byte) int115//116// Returns the index of the last occurrence of b1 or b2 in s, or -1.117// Scans backward using ARM64 NEON.118TEXT ·lastIndexByteTwo(SB),NOSPLIT,$0-40119 MOVD s_base+0(FP), R0120 MOVD s_len+8(FP), R2121 MOVBU b1+24(FP), R1122 MOVBU b2+25(FP), R7123 MOVD $ret+32(FP), R8124125 CBZ R2, lfail126 MOVD R0, R11 // save base127 ADD R0, R2, R12 // R12 = end = base + len128 MOVD $0x40100401, R5129 VMOV R1, V0.B16 // V0 = splat(b1)130 VMOV R7, V7.B16 // V7 = splat(b2)131 VMOV R5, V5.S4132133 // Align: find the aligned block containing the last byte134 SUB $1, R12, R3135 BIC $0x1f, R3, R3 // R3 = start of aligned block containing last byte136137 // --- Process tail block ---138 VLD1 (R3), [V1.B16, V2.B16]139 VCMEQ V0.B16, V1.B16, V3.B16140 VCMEQ V7.B16, V1.B16, V8.B16141 VORR V8.B16, V3.B16, V3.B16142 VCMEQ V0.B16, V2.B16, V4.B16143 VCMEQ V7.B16, V2.B16, V9.B16144 VORR V9.B16, V4.B16, V4.B16145 VAND V5.B16, V3.B16, V3.B16146 VAND V5.B16, V4.B16, V4.B16147 VADDP V4.B16, V3.B16, V6.B16148 VADDP V6.B16, V6.B16, V6.B16149 VMOV V6.D[0], R6150151 // Mask upper bits (bytes past end of slice)152 // tail_bytes = end - R3 (1..32)153 SUB R3, R12, R10 // R10 = tail_bytes154 MOVD $64, R4155 SUB R10<<1, R4, R4 // R4 = 64 - 2*tail_bytes156 LSL R4, R6, R6157 LSR R4, R6, R6158159 // Is this also the head block?160 CMP R11, R3 // R3 - R11161 BLO lmaskfirst // R3 < base: head+tail in same block162 BEQ ltailonly // R3 == base: single aligned block163164 // R3 > base: more blocks before this one165 CBNZ R6, llast166 B lbacksetup167168ltailonly:169 // Single block, already masked upper bits170 CBNZ R6, llast171 B lfail172173lmaskfirst:174 // Mask lower bits (bytes before start of slice)175 SUB R3, R11, R4 // R4 = base - R3176 LSL $1, R4, R4177 LSR R4, R6, R6178 LSL R4, R6, R6179 CBNZ R6, llast180 B lfail181182lbacksetup:183 SUB $0x20, R3184185lbackloop:186 VLD1 (R3), [V1.B16, V2.B16]187 VCMEQ V0.B16, V1.B16, V3.B16188 VCMEQ V7.B16, V1.B16, V8.B16189 VORR V8.B16, V3.B16, V3.B16190 VCMEQ V0.B16, V2.B16, V4.B16191 VCMEQ V7.B16, V2.B16, V9.B16192 VORR V9.B16, V4.B16, V4.B16193 // Quick check: any match in this block?194 VORR V4.B16, V3.B16, V6.B16195 VADDP V6.D2, V6.D2, V6.D2196 VMOV V6.D[0], R6197198 // Is this a head block? (R3 < base)199 CMP R11, R3200 BLO lheadblock201202 // Full block (R3 >= base)203 CBNZ R6, lbackfound204 // More blocks?205 BEQ lfail // R3 == base, no more206 SUB $0x20, R3207 B lbackloop208209lbackfound:210 // Build full syndrome211 VAND V5.B16, V3.B16, V3.B16212 VAND V5.B16, V4.B16, V4.B16213 VADDP V4.B16, V3.B16, V6.B16214 VADDP V6.B16, V6.B16, V6.B16215 VMOV V6.D[0], R6216 B llast217218lheadblock:219 // R3 < base. Build full syndrome if quick check had a match.220 CBZ R6, lfail221 VAND V5.B16, V3.B16, V3.B16222 VAND V5.B16, V4.B16, V4.B16223 VADDP V4.B16, V3.B16, V6.B16224 VADDP V6.B16, V6.B16, V6.B16225 VMOV V6.D[0], R6226 // Mask lower bits227 SUB R3, R11, R4 // R4 = base - R3228 LSL $1, R4, R4229 LSR R4, R6, R6230 LSL R4, R6, R6231 CBZ R6, lfail232233llast:234 // Find last match: highest set bit in syndrome235 // Syndrome has bit 2i set for matching byte i.236 // CLZ gives leading zeros; byte_offset = (63 - CLZ) / 2.237 CLZ R6, R6238 MOVD $63, R4239 SUB R6, R4, R6 // R6 = 63 - CLZ = bit position240 LSR $1, R6 // R6 = byte offset within block241 ADD R3, R6, R0 // R0 = absolute address242 SUB R11, R0, R0 // R0 = slice index243 MOVD R0, (R8)244 RET245246lfail:247 MOVD $-1, R0248 MOVD R0, (R8)249 RET
added:src/algo/indexbyte2_other.go+33 added
1//go:build !arm64 && !amd6423package algo45import "bytes"67// indexByteTwo returns the index of the first occurrence of b1 or b2 in s,8// or -1 if neither is present.9func indexByteTwo(s []byte, b1, b2 byte) int {10 i1 := bytes.IndexByte(s, b1)11 if i1 == 0 {12 return 013 }14 scope := s15 if i1 > 0 {16 scope = s[:i1]17 }18 if i2 := bytes.IndexByte(scope, b2); i2 >= 0 {19 return i220 }21 return i122}2324// lastIndexByteTwo returns the index of the last occurrence of b1 or b2 in s,25// or -1 if neither is present.26func lastIndexByteTwo(s []byte, b1, b2 byte) int {27 for i := len(s) - 1; i >= 0; i-- {28 if s[i] == b1 || s[i] == b2 {29 return i30 }31 }32 return -133}
added:src/algo/indexbyte2_test.go+259 added
1package algo23import (4 "bytes"5 "testing"6)78func TestIndexByteTwo(t *testing.T) {9 tests := []struct {10 name string11 s string12 b1 byte13 b2 byte14 want int15 }{16 {"empty", "", 'a', 'b', -1},17 {"single_b1", "a", 'a', 'b', 0},18 {"single_b2", "b", 'a', 'b', 0},19 {"single_none", "c", 'a', 'b', -1},20 {"b1_first", "xaxb", 'a', 'b', 1},21 {"b2_first", "xbxa", 'a', 'b', 1},22 {"same_byte", "xxa", 'a', 'a', 2},23 {"at_end", "xxxxa", 'a', 'b', 4},24 {"not_found", "xxxxxxxx", 'a', 'b', -1},25 {"long_b1_at_3000", string(make([]byte, 3000)) + "a" + string(make([]byte, 1000)), 'a', 'b', 3000},26 {"long_b2_at_3000", string(make([]byte, 3000)) + "b" + string(make([]byte, 1000)), 'a', 'b', 3000},27 }2829 for _, tt := range tests {30 t.Run(tt.name, func(t *testing.T) {31 got := indexByteTwo([]byte(tt.s), tt.b1, tt.b2)32 if got != tt.want {33 t.Errorf("indexByteTwo(%q, %c, %c) = %d, want %d", tt.s[:min(len(tt.s), 40)], tt.b1, tt.b2, got, tt.want)34 }35 })36 }3738 // Exhaustive test: compare against loop reference for various lengths,39 // including sizes around SIMD block boundaries (16, 32, 64).40 for n := 0; n <= 256; n++ {41 data := make([]byte, n)42 for i := range data {43 data[i] = byte('c' + (i % 20))44 }45 // Test with match at every position46 for pos := 0; pos < n; pos++ {47 for _, b := range []byte{'A', 'B'} {48 data[pos] = b49 got := indexByteTwo(data, 'A', 'B')50 want := loopIndexByteTwo(data, 'A', 'B')51 if got != want {52 t.Fatalf("indexByteTwo(len=%d, match=%c@%d) = %d, want %d", n, b, pos, got, want)53 }54 data[pos] = byte('c' + (pos % 20))55 }56 }57 // Test with no match58 got := indexByteTwo(data, 'A', 'B')59 if got != -1 {60 t.Fatalf("indexByteTwo(len=%d, no match) = %d, want -1", n, got)61 }62 // Test with both bytes present63 if n >= 2 {64 data[n/3] = 'A'65 data[n*2/3] = 'B'66 got := indexByteTwo(data, 'A', 'B')67 want := loopIndexByteTwo(data, 'A', 'B')68 if got != want {69 t.Fatalf("indexByteTwo(len=%d, both@%d,%d) = %d, want %d", n, n/3, n*2/3, got, want)70 }71 data[n/3] = byte('c' + ((n / 3) % 20))72 data[n*2/3] = byte('c' + ((n * 2 / 3) % 20))73 }74 }75}7677func TestLastIndexByteTwo(t *testing.T) {78 tests := []struct {79 name string80 s string81 b1 byte82 b2 byte83 want int84 }{85 {"empty", "", 'a', 'b', -1},86 {"single_b1", "a", 'a', 'b', 0},87 {"single_b2", "b", 'a', 'b', 0},88 {"single_none", "c", 'a', 'b', -1},89 {"b1_last", "xbxa", 'a', 'b', 3},90 {"b2_last", "xaxb", 'a', 'b', 3},91 {"same_byte", "axx", 'a', 'a', 0},92 {"at_start", "axxxx", 'a', 'b', 0},93 {"both_present", "axbx", 'a', 'b', 2},94 {"not_found", "xxxxxxxx", 'a', 'b', -1},95 {"long_b1_at_3000", string(make([]byte, 3000)) + "a" + string(make([]byte, 1000)), 'a', 'b', 3000},96 {"long_b2_at_end", string(make([]byte, 4000)) + "b", 'a', 'b', 4000},97 }9899 for _, tt := range tests {100 t.Run(tt.name, func(t *testing.T) {101 got := lastIndexByteTwo([]byte(tt.s), tt.b1, tt.b2)102 if got != tt.want {103 t.Errorf("lastIndexByteTwo(%q, %c, %c) = %d, want %d", tt.s[:min(len(tt.s), 40)], tt.b1, tt.b2, got, tt.want)104 }105 })106 }107108 // Exhaustive test against loop reference109 for n := 0; n <= 256; n++ {110 data := make([]byte, n)111 for i := range data {112 data[i] = byte('c' + (i % 20))113 }114 for pos := 0; pos < n; pos++ {115 for _, b := range []byte{'A', 'B'} {116 data[pos] = b117 got := lastIndexByteTwo(data, 'A', 'B')118 want := refLastIndexByteTwo(data, 'A', 'B')119 if got != want {120 t.Fatalf("lastIndexByteTwo(len=%d, match=%c@%d) = %d, want %d", n, b, pos, got, want)121 }122 data[pos] = byte('c' + (pos % 20))123 }124 }125 // No match126 got := lastIndexByteTwo(data, 'A', 'B')127 if got != -1 {128 t.Fatalf("lastIndexByteTwo(len=%d, no match) = %d, want -1", n, got)129 }130 // Both bytes present131 if n >= 2 {132 data[n/3] = 'A'133 data[n*2/3] = 'B'134 got := lastIndexByteTwo(data, 'A', 'B')135 want := refLastIndexByteTwo(data, 'A', 'B')136 if got != want {137 t.Fatalf("lastIndexByteTwo(len=%d, both@%d,%d) = %d, want %d", n, n/3, n*2/3, got, want)138 }139 data[n/3] = byte('c' + ((n / 3) % 20))140 data[n*2/3] = byte('c' + ((n * 2 / 3) % 20))141 }142 }143}144145func FuzzIndexByteTwo(f *testing.F) {146 f.Add([]byte("hello world"), byte('o'), byte('l'))147 f.Add([]byte(""), byte('a'), byte('b'))148 f.Add([]byte("aaa"), byte('a'), byte('a'))149 f.Fuzz(func(t *testing.T, data []byte, b1, b2 byte) {150 got := indexByteTwo(data, b1, b2)151 want := loopIndexByteTwo(data, b1, b2)152 if got != want {153 t.Errorf("indexByteTwo(len=%d, b1=%d, b2=%d) = %d, want %d", len(data), b1, b2, got, want)154 }155 })156}157158func FuzzLastIndexByteTwo(f *testing.F) {159 f.Add([]byte("hello world"), byte('o'), byte('l'))160 f.Add([]byte(""), byte('a'), byte('b'))161 f.Add([]byte("aaa"), byte('a'), byte('a'))162 f.Fuzz(func(t *testing.T, data []byte, b1, b2 byte) {163 got := lastIndexByteTwo(data, b1, b2)164 want := refLastIndexByteTwo(data, b1, b2)165 if got != want {166 t.Errorf("lastIndexByteTwo(len=%d, b1=%d, b2=%d) = %d, want %d", len(data), b1, b2, got, want)167 }168 })169}170171// Reference implementations for correctness checking172func refIndexByteTwo(s []byte, b1, b2 byte) int {173 i1 := bytes.IndexByte(s, b1)174 if i1 == 0 {175 return 0176 }177 scope := s178 if i1 > 0 {179 scope = s[:i1]180 }181 if i2 := bytes.IndexByte(scope, b2); i2 >= 0 {182 return i2183 }184 return i1185}186187func loopIndexByteTwo(s []byte, b1, b2 byte) int {188 for i, b := range s {189 if b == b1 || b == b2 {190 return i191 }192 }193 return -1194}195196func refLastIndexByteTwo(s []byte, b1, b2 byte) int {197 for i := len(s) - 1; i >= 0; i-- {198 if s[i] == b1 || s[i] == b2 {199 return i200 }201 }202 return -1203}204205func benchIndexByteTwo(b *testing.B, size int, pos int) {206 data := make([]byte, size)207 for i := range data {208 data[i] = byte('a' + (i % 20))209 }210 data[pos] = 'Z'211212 type impl struct {213 name string214 fn func([]byte, byte, byte) int215 }216 impls := []impl{217 {"asm", indexByteTwo},218 {"2xIndexByte", refIndexByteTwo},219 {"loop", loopIndexByteTwo},220 }221 for _, im := range impls {222 b.Run(im.name, func(b *testing.B) {223 for i := 0; i < b.N; i++ {224 im.fn(data, 'Z', 'z')225 }226 })227 }228}229230func benchLastIndexByteTwo(b *testing.B, size int, pos int) {231 data := make([]byte, size)232 for i := range data {233 data[i] = byte('a' + (i % 20))234 }235 data[pos] = 'Z'236237 type impl struct {238 name string239 fn func([]byte, byte, byte) int240 }241 impls := []impl{242 {"asm", lastIndexByteTwo},243 {"loop", refLastIndexByteTwo},244 }245 for _, im := range impls {246 b.Run(im.name, func(b *testing.B) {247 for i := 0; i < b.N; i++ {248 im.fn(data, 'Z', 'z')249 }250 })251 }252}253254func BenchmarkIndexByteTwo_10(b *testing.B) { benchIndexByteTwo(b, 10, 8) }255func BenchmarkIndexByteTwo_100(b *testing.B) { benchIndexByteTwo(b, 100, 80) }256func BenchmarkIndexByteTwo_1000(b *testing.B) { benchIndexByteTwo(b, 1000, 800) }257func BenchmarkLastIndexByteTwo_10(b *testing.B) { benchLastIndexByteTwo(b, 10, 2) }258func BenchmarkLastIndexByteTwo_100(b *testing.B) { benchLastIndexByteTwo(b, 100, 20) }259func BenchmarkLastIndexByteTwo_1000(b *testing.B) { benchLastIndexByteTwo(b, 1000, 200) }