Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lib/fs: Add ASCII fastpath for normalization #9365

Draft
wants to merge 18 commits into
base: main
Choose a base branch
from
36 changes: 27 additions & 9 deletions lib/fs/folding.go
Expand Up @@ -17,7 +17,13 @@ import (
// UnicodeLowercaseNormalized returns the Unicode lower case variant of s,
// having also normalized it to normalization form C.
func UnicodeLowercaseNormalized(s string) string {
i := firstCaseChange(s)
i, isASCII := firstCaseChange(s)
if isASCII {
if i == -1 {
return s
}
return strings.ToLower(s)
}
if i == -1 {
return norm.NFC.String(s)
}
Expand All @@ -30,20 +36,32 @@ func UnicodeLowercaseNormalized(s string) string {
rs.WriteString(s[:i])

for _, r := range s[i:] {
rs.WriteRune(unicode.ToLower(unicode.ToUpper(r)))
r = unicode.ToLower(unicode.ToUpper(r))
if r < utf8.RuneSelf {
rs.WriteByte(byte(r))
} else {
rs.WriteRune(r)
}
}
return norm.NFC.String(rs.String())
}

// Byte index of the first rune r s.t. lower(upper(r)) != r.
func firstCaseChange(s string) int {
// Boolean indicating if the whole string consists of ASCII characters.
func firstCaseChange(s string) (int, bool) {
bt90 marked this conversation as resolved.
Show resolved Hide resolved
index := -1
isASCII := true
for i, r := range s {
if r <= unicode.MaxASCII && (r < 'A' || r > 'Z') {
continue
}
if unicode.ToLower(unicode.ToUpper(r)) != r {
return i
if r <= unicode.MaxASCII {
if index == -1 && 'A' <= r && r <= 'Z' {
index = i
}
} else {
if index == -1 && unicode.ToLower(unicode.ToUpper(r)) != r {
index = i
}
isASCII = false
}
}
return -1
return index, isASCII
}