33 lines
675 B
Go
33 lines
675 B
Go
package util
|
|
|
|
// https://github.com/go-pg/pg/blob/7c2d9d39a5cfc18a422c88a9f5f39d8d2cd10030/internal/underscore.go
|
|
|
|
func isUpper(c byte) bool {
|
|
return c >= 'A' && c <= 'Z'
|
|
}
|
|
|
|
func isLower(c byte) bool {
|
|
return !isUpper(c)
|
|
}
|
|
|
|
func toLower(c byte) byte {
|
|
return c + 32
|
|
}
|
|
|
|
// Underscore converts "CamelCasedString" to "camel_cased_string".
|
|
func Underscore(s string) string {
|
|
r := make([]byte, 0, len(s))
|
|
for i := 0; i < len(s); i++ {
|
|
c := s[i]
|
|
if isUpper(c) {
|
|
if i > 0 && i+1 < len(s) && (isLower(s[i-1]) || isLower(s[i+1])) {
|
|
r = append(r, '_', toLower(c))
|
|
} else {
|
|
r = append(r, toLower(c))
|
|
}
|
|
} else {
|
|
r = append(r, c)
|
|
}
|
|
}
|
|
return string(r)
|
|
}
|