| 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 |
"github.com/gofiber/utils/v2/swar" |
| 9 |
) |
| 10 |
|
| 11 |
// MemchrDigit returns the index of the first ASCII digit '0'..'9' in |
| 12 |
// haystack, or -1 if no digit is present. Only ASCII digits match; Unicode |
| 13 |
// digit characters do not. |
| 14 |
// |
| 15 |
// On amd64 with AVX2 the range check runs on 32 bytes per vector, four |
| 16 |
// vectors per iteration, which is useful for locating numeric fields |
| 17 |
// (ports, lengths, IP octets) in request data. |
| 18 |
func MemchrDigit(haystack []byte) int { |
| 19 |
if len(haystack) == 0 { |
| 20 |
return -1 |
| 21 |
} |
| 22 |
return memchrDigitImpl(haystack) |
| 23 |
} |
| 24 |
|
| 25 |
// MemchrDigitAt is MemchrDigit(haystack[at:]) with the result translated |
| 26 |
// back to an absolute index in haystack. It returns -1 when no digit is |
| 27 |
// found or when at is out of bounds. |
| 28 |
func MemchrDigitAt(haystack []byte, at int) int { |
| 29 |
if at < 0 || at >= len(haystack) { |
| 30 |
return -1 |
| 31 |
} |
| 32 |
pos := MemchrDigit(haystack[at:]) |
| 33 |
if pos < 0 { |
| 34 |
return -1 |
| 35 |
} |
| 36 |
return pos + at |
| 37 |
} |
| 38 |
|
| 39 |
// memchrDigitGeneric is the portable SWAR fallback for MemchrDigit: a |
| 40 |
// MatchRangeMask first-match scan (exact per lane; bytes >= 0x80 never |
| 41 |
// match), two words per branch, finishing 8+ byte inputs with one |
| 42 |
// overlapping word at n-8. |
| 43 |
func memchrDigitGeneric(haystack []byte) int { |
| 44 |
n := len(haystack) |
| 45 |
if n < swar.WordLen { |
| 46 |
for i, b := range haystack { |
| 47 |
if b >= '0' && b <= '9' { |
| 48 |
return i |
| 49 |
} |
| 50 |
} |
| 51 |
return -1 |
| 52 |
} |
| 53 |
i := 0 |
| 54 |
for ; i+2*swar.WordLen <= n; i += 2 * swar.WordLen { |
| 55 |
// Pinned window: see the note above isASCIIGeneric in ascii.go for |
| 56 |
// why the loads use constant offsets into it. |
| 57 |
w := haystack[i : i+2*swar.WordLen : i+2*swar.WordLen] |
| 58 |
m0 := swar.MatchRangeMask(swar.Load8(w, 0), '0', '9') |
| 59 |
m1 := swar.MatchRangeMask(swar.Load8(w, swar.WordLen), '0', '9') |
| 60 |
if m0|m1 != 0 { |
| 61 |
if m0 != 0 { |
| 62 |
return i + swar.FirstLane(m0) |
| 63 |
} |
| 64 |
return i + swar.WordLen + swar.FirstLane(m1) |
| 65 |
} |
| 66 |
} |
| 67 |
for ; i+swar.WordLen <= n; i += swar.WordLen { |
| 68 |
if m := swar.MatchRangeMask(swar.Load8(haystack, i), '0', '9'); m != 0 { |
| 69 |
return i + swar.FirstLane(m) |
| 70 |
} |
| 71 |
} |
| 72 |
if i == n { |
| 73 |
return -1 |
| 74 |
} |
| 75 |
if m := swar.MatchRangeMask(swar.Load8(haystack, n-swar.WordLen), '0', '9'); m != 0 { |
| 76 |
return n - swar.WordLen + swar.FirstLane(m) |
| 77 |
} |
| 78 |
return -1 |
| 79 |
} |