-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmapper.go
66 lines (49 loc) · 1.05 KB
/
mapper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package mapper
import (
"strings"
)
/*
mapper provides an alternative to the default sqlx field name mapper
(which is simply strings.ToLower()). This mapper converts Pascal-cased,
camel-cased, snake-cased and kebab-cased field names into lower-cased,
snake-cased names.
*/
func Mapper(name string) string {
const alphaOffset = 0x20
sb := strings.Builder{}
lastSep := true
lastUpper := true
for i := 0; i < len(name); i++ {
cin := name[i]
cout := cin | alphaOffset
if lastSep && isSeparator(cin) {
lastUpper = false
continue
}
if !lastSep && isSeparator(cin) {
sb.WriteByte('_')
lastSep = true
lastUpper = false
continue
}
if !isAlpha(cout) {
continue
}
if !lastUpper && !lastSep && isUpper(cin) {
sb.WriteByte('_')
}
lastSep = false
lastUpper = isUpper(cin)
sb.WriteByte(cout)
}
return strings.Trim(sb.String(), "_-")
}
func isAlpha(c byte) bool {
return c >= 'a' && c <= 'z'
}
func isSeparator(c byte) bool {
return c == '-' || c == '_'
}
func isUpper(c byte) bool {
return c >= 'A' && c <= 'Z'
}