x/model: simplify Name.CompareFold

This commit is contained in:
Blake Mizerany 2024-04-06 16:08:11 -07:00
parent 712eaa4b09
commit c84f9b07b0

View File

@ -349,30 +349,20 @@ func (r Name) EqualFold(o Name) bool {
// //
// For simple equality checks, use [Name.EqualFold]. // For simple equality checks, use [Name.EqualFold].
func (r Name) CompareFold(o Name) int { func (r Name) CompareFold(o Name) int {
for i := range r.parts { return slices.CompareFunc(r.parts[:], o.parts[:], compareFold)
if n := compareFold(r.parts[i], o.parts[i]); n != 0 {
return n
}
}
return 0
} }
func compareFold(a, b string) int { func compareFold(a, b string) int {
// fast-path for unequal lengths return slices.CompareFunc([]rune(a), []rune(b), func(a, b rune) int {
for i := 0; i < len(a) && i < len(b); i++ { return cmp.Compare(downcase(a), downcase(b))
ca, cb := downcase(a[i]), downcase(b[i]) })
if n := cmp.Compare(ca, cb); n != 0 {
return n
}
}
return cmp.Compare(len(a), len(b))
} }
func downcase(c byte) byte { func downcase(r rune) rune {
if c >= 'A' && c <= 'Z' { if r >= 'A' && r <= 'Z' {
return c + 'a' - 'A' return r - 'A' + 'a'
} }
return c return r
} }
// TODO(bmizerany): driver.Value? (MarshalText etc should be enough) // TODO(bmizerany): driver.Value? (MarshalText etc should be enough)