Debian Codegraph @

internal/bytealg/indexbyte_simd.go

raw
1 // Copyright 2023 Charlie Vieth. All rights reserved.
2 // Use of this source code is governed by the MIT license.
3
4 //go:build s390x || wasm || ppc64
5 // +build s390x wasm ppc64
6
7 // The below functions assume their corresponding functions in the standard
8 // library can search multiple bytes simultaneously (SIMD or whatever).
9 // Otherwise, a simple for loop should be used.
10 //
11 // NOTE(cev): The arch build tags included here were picked by me browsing the
12 // assembly implementations of indexbye_{GOARCH}.s and if it looked fancy and
13 // complicated I assume it used SIMD so included it here - so could be wrong.
14 //
15 // This list should be revisited when new versions of Go are released, or by
16 // anyone who either has access to the hardware or understands the assembly.
17
18 package bytealg
19
20 import (
21 "bytes"
22 "strings"
23 )
24
25 func isAlpha(c byte) bool {
26 return 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z'
27 }
28
29 func IndexByte(s []byte, c byte) int {
30 if len(s) == 0 {
31 return -1
32 }
33 n := bytes.IndexByte(s, c)
34 if n == 0 || !isAlpha(c) {
35 return n
36 }
37
38 c ^= ' ' // swap case
39 if s[0] == c {
40 return 0
41 }
42
43 // TODO: calculate the optimal cutoff
44 if n > 0 && len(s) >= 16 {
45 s = s[:n] // limit search space
46 }
47
48 if o := bytes.IndexByte(s, c); n == -1 || (o != -1 && o < n) {
49 n = o
50 }
51 return n
52 }
53
54 func IndexByteString(s string, c byte) int {
55 if len(s) == 0 {
56 return -1
57 }
58 n := strings.IndexByte(s, c)
59 if n == 0 || !isAlpha(c) {
60 return n
61 }
62
63 c ^= ' ' // swap case
64 if s[0] == c {
65 return 0
66 }
67
68 // TODO: calculate the optimal cutoff
69 if n > 0 && len(s) >= 16 {
70 s = s[:n] // limit search space
71 }
72
73 if o := strings.IndexByte(s, c); n == -1 || (o != -1 && o < n) {
74 n = o
75 }
76 return n
77 }