1
0
mirror of https://github.com/golang/go synced 2024-11-24 15:00:14 -07:00

strings: faster equality check on simple cases

This commit is contained in:
miton18 2024-11-05 12:17:08 +01:00
parent bea9b91f0f
commit 32f452ad36

View File

@ -1185,9 +1185,13 @@ func ReplaceAll(s, old, new string) string {
// are equal under simple Unicode case-folding, which is a more general // are equal under simple Unicode case-folding, which is a more general
// form of case-insensitivity. // form of case-insensitivity.
func EqualFold(s, t string) bool { func EqualFold(s, t string) bool {
if len(s) != len(t) {
return false
}
// ASCII fast path // ASCII fast path
i := 0 i := 0
for ; i < len(s) && i < len(t); i++ { for ; i < len(s); i++ {
sr := s[i] sr := s[i]
tr := t[i] tr := t[i]
if sr|tr >= utf8.RuneSelf { if sr|tr >= utf8.RuneSelf {
@ -1205,22 +1209,15 @@ func EqualFold(s, t string) bool {
} }
// ASCII only, sr/tr must be upper/lower case // ASCII only, sr/tr must be upper/lower case
if 'A' <= sr && sr <= 'Z' && tr == sr+'a'-'A' { if 'A' <= sr && sr <= 'Z' && tr == sr+'a'-'A' {
continue return false
} }
return false
} }
// Check if we've exhausted both strings. return true
return len(s) == len(t)
hasUnicode: hasUnicode:
s = s[i:] s = s[i:]
t = t[i:] t = t[i:]
for _, sr := range s { for _, sr := range s {
// If t is exhausted the strings are not equal.
if len(t) == 0 {
return false
}
// Extract first rune from second string. // Extract first rune from second string.
var tr rune var tr rune
if t[0] < utf8.RuneSelf { if t[0] < utf8.RuneSelf {
@ -1256,14 +1253,12 @@ hasUnicode:
for r != sr && r < tr { for r != sr && r < tr {
r = unicode.SimpleFold(r) r = unicode.SimpleFold(r)
} }
if r == tr { if r != tr {
continue return false
} }
return false
} }
// First string is empty, so check if the second one is also empty. return true
return len(t) == 0
} }
// Index returns the index of the first instance of substr in s, or -1 if substr is not present in s. // Index returns the index of the first instance of substr in s, or -1 if substr is not present in s.