Debian Codegraph @

search.go

raw
1 package utils
2
3 import (
4 "github.com/gofiber/utils/v2/internal/caseconv"
5 "github.com/gofiber/utils/v2/internal/unsafeconv"
6 "github.com/gofiber/utils/v2/simd"
7 "github.com/gofiber/utils/v2/swar"
8 )
9
10 // Multi-needle and case-insensitive searching, built on swar.ZeroLanes
11 // first-match masks with needle broadcasts hoisted out of the word loops.
12 // IndexAny2/IndexAny3 scan words while i+8 <= n and finish 8+ byte inputs
13 // with one overlapping word at n-8 (pure loads; already-scanned lanes are
14 // known non-matching, so the first set lane falls in the new bytes).
15 // IndexFold instead scans candidate start positions only up to n-k, so its
16 // word loop hands the final partial word to a scalar remainder; the
17 // overlapping-window trick appears there only inside the verify reads.
18 // Inputs shorter than a word use scalar loops throughout.
19
20 // IndexAny2 returns the index of the first occurrence in s of either a or b,
21 // or -1 if neither is present. On amd64 CPUs with AVX2, inputs of 32+ bytes
22 // dispatch to package simd instead.
23 func IndexAny2[S byteSeq](s S, a, b byte) int {
24 n := len(s)
25 if n >= simd.MinLen && simd.Accelerated() {
26 return simd.Memchr2(unsafeconv.Bytes(s), a, b)
27 }
28 if n >= 8 {
29 // The needle broadcasts are hoisted here so sub-word inputs never
30 // pay for the multiplies.
31 bcA := swar.Broadcast(a)
32 bcB := swar.Broadcast(b)
33 i := 0
34 // Two words per branch: the masks compute independently, and if only
35 // the second word matched, its first set lane is still exact.
36 for ; i+16 <= n; i += 16 {
37 w0 := swar.Load8(s, i)
38 w1 := swar.Load8(s, i+8)
39 m0 := swar.ZeroLanes(w0^bcA) | swar.ZeroLanes(w0^bcB)
40 m1 := swar.ZeroLanes(w1^bcA) | swar.ZeroLanes(w1^bcB)
41 if m0|m1 != 0 {
42 if m0 != 0 {
43 return i + swar.FirstLane(m0)
44 }
45 return i + 8 + swar.FirstLane(m1)
46 }
47 }
48 for ; i+8 <= n; i += 8 {
49 w := swar.Load8(s, i)
50 if m := swar.ZeroLanes(w^bcA) | swar.ZeroLanes(w^bcB); m != 0 {
51 return i + swar.FirstLane(m)
52 }
53 }
54 if i == n {
55 return -1
56 }
57 w := swar.Load8(s, n-8)
58 if m := swar.ZeroLanes(w^bcA) | swar.ZeroLanes(w^bcB); m != 0 {
59 return n - 8 + swar.FirstLane(m)
60 }
61 return -1
62 }
63 for i := range n {
64 if s[i] == a || s[i] == b {
65 return i
66 }
67 }
68 return -1
69 }
70
71 // IndexAny3 returns the index of the first occurrence in s of a, b, or c,
72 // or -1 if none is present. On amd64 CPUs with AVX2, inputs of 32+ bytes
73 // dispatch to package simd instead.
74 func IndexAny3[S byteSeq](s S, a, b, c byte) int {
75 n := len(s)
76 if n >= simd.MinLen && simd.Accelerated() {
77 return simd.Memchr3(unsafeconv.Bytes(s), a, b, c)
78 }
79 if n >= 8 {
80 bcA := swar.Broadcast(a)
81 bcB := swar.Broadcast(b)
82 bcC := swar.Broadcast(c)
83 i := 0
84 // Two words per branch; see IndexAny2.
85 for ; i+16 <= n; i += 16 {
86 w0 := swar.Load8(s, i)
87 w1 := swar.Load8(s, i+8)
88 m0 := swar.ZeroLanes(w0^bcA) | swar.ZeroLanes(w0^bcB) | swar.ZeroLanes(w0^bcC)
89 m1 := swar.ZeroLanes(w1^bcA) | swar.ZeroLanes(w1^bcB) | swar.ZeroLanes(w1^bcC)
90 if m0|m1 != 0 {
91 if m0 != 0 {
92 return i + swar.FirstLane(m0)
93 }
94 return i + 8 + swar.FirstLane(m1)
95 }
96 }
97 for ; i+8 <= n; i += 8 {
98 w := swar.Load8(s, i)
99 if m := swar.ZeroLanes(w^bcA) | swar.ZeroLanes(w^bcB) | swar.ZeroLanes(w^bcC); m != 0 {
100 return i + swar.FirstLane(m)
101 }
102 }
103 if i == n {
104 return -1
105 }
106 w := swar.Load8(s, n-8)
107 if m := swar.ZeroLanes(w^bcA) | swar.ZeroLanes(w^bcB) | swar.ZeroLanes(w^bcC); m != 0 {
108 return n - 8 + swar.FirstLane(m)
109 }
110 return -1
111 }
112 for i := range n {
113 if s[i] == a || s[i] == b || s[i] == c {
114 return i
115 }
116 }
117 return -1
118 }
119
120 // IndexFold returns the index of the first ASCII case-insensitive occurrence
121 // of needle in s, or -1 if absent. An empty needle matches at index 0. Only
122 // 'A'..'Z'/'a'..'z' fold; every other byte (including >= 0x80) must match
123 // exactly, so e.g. "no\rcache" does NOT match the needle "no-cache".
124 // The needle is a plain string by design: call sites pass constant tokens,
125 // and a []byte needle would cost its callers a conversion either way.
126 func IndexFold[S byteSeq](s S, needle string) int {
127 n, k := len(s), len(needle)
128 if k == 0 {
129 return 0
130 }
131 if k > n {
132 return -1
133 }
134
135 table := caseconv.ToLowerTable
136 first := table[needle[0]]
137 last := n - k // last valid start position
138
139 if n >= 8 {
140 // Scan candidate positions 8 at a time by matching the needle's
141 // first byte in both case variants (no need to fold the haystack),
142 // then verify each candidate. Approximate-mask false positives just
143 // cost a verify; the candidate order stays low-to-high, so the
144 // pos > last cutoff remains a valid global exit.
145 bc1 := swar.Broadcast(first)
146 bc2 := bc1
147 if first >= 'a' && first <= 'z' {
148 bc2 = swar.Broadcast(first - 0x20)
149 }
150
151 // For needles up to one word the verify is a single masked word
152 // compare against the folded needle, built lazily on the first
153 // candidate; longer needles fold-compare word-at-a-time. The lazy
154 // build is load-bearing: building eagerly costs the no-candidate
155 // path +44% on 8-byte misses and +13% to +17% on 32-64B misses
156 // (benchstat -count=10, Go 1.25, Apple M2 Pro). foldPrep keeps the
157 // pair computation in one place for both build sites below.
158 var fn foldedNeedle
159 built := false
160
161 i := 0
162 for ; i+8 <= n; i += 8 {
163 w := swar.Load8(s, i)
164 cand := swar.ZeroLanes(w^bc1) | swar.ZeroLanes(w^bc2)
165 for cand != 0 {
166 pos := i + swar.FirstLane(cand)
167 if pos > last {
168 return -1
169 }
170 if k <= 8 {
171 if !built {
172 fn = foldPrep(needle)
173 built = true
174 }
175 if foldedWindowAt(s, pos, fn.mask) == fn.word {
176 return pos
177 }
178 } else if foldEqualAt(s, pos, needle) {
179 return pos
180 }
181 cand &= cand - 1
182 }
183 }
184 // Candidate starts in the final partial word: positions [i, last].
185 // Here i is the word loop's exit index n - n%8, so this region is
186 // non-empty only when k <= n%8 <= 7 — the needle always fits in one
187 // word and only the short-needle verify can apply.
188 for ; i <= last; i++ {
189 if table[s[i]] == first {
190 if !built {
191 fn = foldPrep(needle)
192 built = true
193 }
194 if foldedWindowAt(s, i, fn.mask) == fn.word {
195 return i
196 }
197 }
198 }
199 return -1
200 }
201
202 // Scalar path: s shorter than a word (so k <= n < 8).
203 outer:
204 for i := 0; i <= last; i++ {
205 if table[s[i]] != first {
206 continue
207 }
208 for j := 1; j < k; j++ {
209 if table[s[i+j]] != table[needle[j]] {
210 continue outer
211 }
212 }
213 return i
214 }
215 return -1
216 }
217
218 // foldedNeedle is the short-needle (k <= 8) verify state: the needle
219 // lower-cased into one word plus the mask covering its lanes.
220 type foldedNeedle struct {
221 word, mask uint64
222 }
223
224 // foldPrep builds the foldedNeedle pair; it exists so IndexFold's two lazy
225 // build sites share one definition.
226 func foldPrep(needle string) foldedNeedle {
227 return foldedNeedle{foldNeedle(needle), ^uint64(0) >> ((8 - len(needle)) * 8)}
228 }
229
230 // foldNeedle returns needle lower-cased into one little-endian word, lane 0
231 // holding needle[0]. len(needle) must be 1..8; lanes past the needle are
232 // zero, matching the ^uint64(0) >> ((8-k)*8) mask callers apply to windows.
233 func foldNeedle(needle string) uint64 {
234 k := len(needle)
235 if k == 8 {
236 return swar.ToLowerWord(swar.Load8(needle, 0))
237 }
238 table := caseconv.ToLowerTable
239 var word uint64
240 for j := k - 1; j >= 0; j-- {
241 word = word<<8 | uint64(table[needle[j]])
242 }
243 return word
244 }
245
246 // foldedWindowAt returns the lower-cased window of s starting at pos, masked
247 // to the needle length. Requires len(s) >= 8 and the window to fit in s;
248 // windows running past len(s)-8 are read through one overlapping load at
249 // len(s)-8 and shifted so lane 0 is s[pos].
250 func foldedWindowAt[S byteSeq](s S, pos int, lenMask uint64) uint64 {
251 if pos+8 <= len(s) {
252 return swar.ToLowerWord(swar.Load8(s, pos)) & lenMask
253 }
254 from := len(s) - 8
255 w := swar.ToLowerWord(swar.Load8(s, from)) >> (8 * (pos - from))
256 return w & lenMask
257 }
258
259 // foldEqualAt reports whether s[pos:pos+len(needle)] equals needle ASCII
260 // case-insensitively. len(needle) must be >= 8 and pos+len(needle) must be
261 // within s; the tail is one overlapping word compare.
262 func foldEqualAt[S byteSeq](s S, pos int, needle string) bool {
263 k := len(needle)
264 i := 0
265 for ; i+8 <= k; i += 8 {
266 if swar.ToLowerWord(swar.Load8(s, pos+i)) != swar.ToLowerWord(swar.Load8(needle, i)) {
267 return false
268 }
269 }
270 if i == k {
271 return true
272 }
273 return swar.ToLowerWord(swar.Load8(s, pos+k-8)) == swar.ToLowerWord(swar.Load8(needle, k-8))
274 }
275
276 // ContainsFold reports whether s contains needle, ASCII case-insensitively.
277 func ContainsFold[S byteSeq](s S, needle string) bool {
278 return IndexFold(s, needle) >= 0
279 }
280
281 // HasPrefixFold reports whether s begins with prefix, ASCII
282 // case-insensitively: only 'A'..'Z'/'a'..'z' fold, every other byte
283 // (including >= 0x80) must match exactly, mirroring IndexFold. An empty
284 // prefix matches any s. Like the other Fold helpers the needle is a plain
285 // string, since call sites pass constant tokens.
286 func HasPrefixFold[S byteSeq](s S, prefix string) bool {
287 k := len(prefix)
288 if len(s) < k {
289 return false
290 }
291 table := caseconv.ToLowerTable
292 if k >= 8 {
293 // First-byte pre-check: typical misses differ immediately, and two
294 // table loads reject them without the word-compare setup.
295 if table[s[0]] != table[prefix[0]] {
296 return false
297 }
298 return foldEqualAt(s, 0, prefix)
299 }
300 for j := range k {
301 if table[s[j]] != table[prefix[j]] {
302 return false
303 }
304 }
305 return true
306 }
307
308 // HasSuffixFold reports whether s ends with suffix, ASCII
309 // case-insensitively, under the same folding contract as HasPrefixFold.
310 // An empty suffix matches any s.
311 func HasSuffixFold[S byteSeq](s S, suffix string) bool {
312 k := len(suffix)
313 n := len(s)
314 if n < k {
315 return false
316 }
317 table := caseconv.ToLowerTable
318 if k >= 8 {
319 // Pre-check the last byte; see HasPrefixFold.
320 if table[s[n-1]] != table[suffix[k-1]] {
321 return false
322 }
323 return foldEqualAt(s, n-k, suffix)
324 }
325 for j := range k {
326 if table[s[n-k+j]] != table[suffix[j]] {
327 return false
328 }
329 }
330 return true
331 }