| 1 |
package strings |
| 2 |
|
| 3 |
import "unicode/utf8" |
| 4 |
|
| 5 |
// IndexNotByte is similar with strings.IndexByte but showing the opposite behavior. |
| 6 |
func IndexNotByte(s string, c byte) int { |
| 7 |
n := len(s) |
| 8 |
for i := 0; i < n; i++ { |
| 9 |
if s[i] != c { |
| 10 |
return i |
| 11 |
} |
| 12 |
} |
| 13 |
return -1 |
| 14 |
} |
| 15 |
|
| 16 |
// LastIndexNotByte is similar with strings.LastIndexByte but showing the opposite behavior. |
| 17 |
func LastIndexNotByte(s string, c byte) int { |
| 18 |
for i := len(s) - 1; i >= 0; i-- { |
| 19 |
if s[i] != c { |
| 20 |
return i |
| 21 |
} |
| 22 |
} |
| 23 |
return -1 |
| 24 |
} |
| 25 |
|
| 26 |
type asciiSet [8]uint32 |
| 27 |
|
| 28 |
func (as *asciiSet) notContains(c byte) bool { |
| 29 |
return (as[c>>5] & (1 << uint(c&31))) == 0 |
| 30 |
} |
| 31 |
|
| 32 |
func makeASCIISet(chars string) (as asciiSet, ok bool) { |
| 33 |
for i := 0; i < len(chars); i++ { |
| 34 |
c := chars[i] |
| 35 |
if c >= utf8.RuneSelf { |
| 36 |
return as, false |
| 37 |
} |
| 38 |
as[c>>5] |= 1 << uint(c&31) |
| 39 |
} |
| 40 |
return as, true |
| 41 |
} |
| 42 |
|
| 43 |
// IndexNotAny is similar with strings.IndexAny but showing the opposite behavior. |
| 44 |
func IndexNotAny(s, chars string) int { |
| 45 |
if len(chars) > 0 { |
| 46 |
if len(s) > 8 { |
| 47 |
if as, isASCII := makeASCIISet(chars); isASCII { |
| 48 |
for i := 0; i < len(s); i++ { |
| 49 |
if as.notContains(s[i]) { |
| 50 |
return i |
| 51 |
} |
| 52 |
} |
| 53 |
return -1 |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
LabelFirstLoop: |
| 58 |
for i, c := range s { |
| 59 |
for j, m := range chars { |
| 60 |
if c != m && j == len(chars)-1 { |
| 61 |
return i |
| 62 |
} else if c != m { |
| 63 |
continue |
| 64 |
} else { |
| 65 |
continue LabelFirstLoop |
| 66 |
} |
| 67 |
} |
| 68 |
} |
| 69 |
} |
| 70 |
return -1 |
| 71 |
} |
| 72 |
|
| 73 |
// LastIndexNotAny is similar with strings.LastIndexAny but showing the opposite behavior. |
| 74 |
func LastIndexNotAny(s, chars string) int { |
| 75 |
if len(chars) > 0 { |
| 76 |
if len(s) > 8 { |
| 77 |
if as, isASCII := makeASCIISet(chars); isASCII { |
| 78 |
for i := len(s) - 1; i >= 0; i-- { |
| 79 |
if as.notContains(s[i]) { |
| 80 |
return i |
| 81 |
} |
| 82 |
} |
| 83 |
return -1 |
| 84 |
} |
| 85 |
} |
| 86 |
LabelFirstLoop: |
| 87 |
for i := len(s); i > 0; { |
| 88 |
r, size := utf8.DecodeLastRuneInString(s[:i]) |
| 89 |
i -= size |
| 90 |
for j, m := range chars { |
| 91 |
if r != m && j == len(chars)-1 { |
| 92 |
return i |
| 93 |
} else if r != m { |
| 94 |
continue |
| 95 |
} else { |
| 96 |
continue LabelFirstLoop |
| 97 |
} |
| 98 |
} |
| 99 |
} |
| 100 |
} |
| 101 |
return -1 |
| 102 |
} |