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
50 changes: 27 additions & 23 deletions lib/fs/folding.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,41 +9,45 @@ package fs
import (
"strings"
"unicode"
"unicode/utf8"

"golang.org/x/text/unicode/norm"
)

type caseType int

const (
asciiLower caseType = iota
asciiMixed
nonAscii
bt90 marked this conversation as resolved.
Show resolved Hide resolved
)

// 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)
if i == -1 {
return norm.NFC.String(s)
switch checkCase(s) {
case asciiLower:
return s
case asciiMixed:
return strings.ToLower(s)
default:
return norm.NFC.String(strings.Map(toLower, s))
}
}

var rs strings.Builder
// WriteRune always reserves utf8.UTFMax bytes for non-ASCII runes,
// even if it doesn't need all that space. Overallocate now to prevent
// it from ever triggering a reallocation.
rs.Grow(utf8.UTFMax - 1 + len(s))
rs.WriteString(s[:i])

for _, r := range s[i:] {
rs.WriteRune(unicode.ToLower(unicode.ToUpper(r)))
}
return norm.NFC.String(rs.String())
func toLower(r rune) rune {
return unicode.ToLower(unicode.ToUpper(r))
}

// Byte index of the first rune r s.t. lower(upper(r)) != r.
func firstCaseChange(s string) int {
for i, r := range s {
if r <= unicode.MaxASCII && (r < 'A' || r > 'Z') {
continue
func checkCase(s string) caseType {
c := asciiLower
for i := 0; i < len(s); i++ {
b := s[i]
if b > unicode.MaxASCII {
return nonAscii
}
if unicode.ToLower(unicode.ToUpper(r)) != r {
return i
if 'A' <= b && b <= 'Z' {
c = asciiMixed
}
}
return -1
return c
}
Loading