-
Notifications
You must be signed in to change notification settings - Fork 10
/
snakecase.go
84 lines (68 loc) · 1.48 KB
/
snakecase.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package conf
import "strings"
func snakecaseLower(s string) string {
return strings.ToLower(snakecase(s))
}
func snakecaseUpper(s string) string {
return strings.ToUpper(snakecase(s))
}
func snakecase(s string) string {
b := make([]byte, 0, 64)
i := len(s) - 1
// search sequences, starting from the end of the string
for i >= 0 {
switch {
case isLower(s[i]): // sequence of lowercase, maybe starting with an uppercase
for i >= 0 && !isSeparator(s[i]) && !isUpper(s[i]) {
b = append(b, s[i])
i--
}
if i >= 0 {
b = append(b, snakebyte(s[i]))
i--
if isSeparator(s[i+1]) { // avoid double underscore if we have "_word"
continue
}
}
if i >= 0 && !isSeparator(s[i]) { // avoid double underscores if we have "_Word"
b = append(b, '_')
}
case isUpper(s[i]): // sequence of uppercase
for i >= 0 && !isSeparator(s[i]) && !isLower(s[i]) {
b = append(b, s[i])
i--
}
if i >= 0 {
if isSeparator(s[i]) {
i--
}
b = append(b, '_')
}
default: // not a letter, it'll be part of the next sequence
b = append(b, snakebyte(s[i]))
i--
}
}
// reverse
for i, j := 0, len(b)-1; i < j; {
b[i], b[j] = b[j], b[i]
i++
j--
}
return string(b)
}
func snakebyte(b byte) byte {
if isSeparator(b) {
return '_'
}
return b
}
func isSeparator(c byte) bool {
return c == '_' || c == '-'
}
func isUpper(c byte) bool {
return c >= 'A' && c <= 'Z'
}
func isLower(c byte) bool {
return c >= 'a' && c <= 'z'
}