-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnames.go
109 lines (96 loc) · 2.15 KB
/
names.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package namecase
import (
"bytes"
"unicode/utf8"
"unsafe"
)
// namecase is a namecase made up of words
type namecase []word
// parseNamecase parse the namecase string
func parseNamecase(name string) namecase {
if name == "" {
return nil
}
names := make([]word, 0, len(name)/2+1)
wordCase := otherWordCase
prevRuneCase := otherRuneCase
currRuneCase := otherRuneCase
prevWordIndex := 0
currRuneIndex := 0
appends := func() {
if prevWordIndex != currRuneIndex {
names = append(names, word{
kind: wordCase,
word: name[prevWordIndex:currRuneIndex],
})
prevWordIndex = currRuneIndex
}
}
for currRuneIndex != len(name) {
r, s := utf8.DecodeRuneInString(name[currRuneIndex:])
currRuneCase = getKind(r)
switch currRuneCase {
case splitRuneCase, otherRuneCase:
if prevRuneCase != currRuneCase {
appends()
}
wordCase = wordKind(currRuneCase)
case upperRuneCase:
if prevRuneCase != currRuneCase {
appends()
wordCase = wordKind(currRuneCase)
}
case lowerRuneCase:
switch prevRuneCase {
case otherRuneCase, splitRuneCase, eofRuneCase:
appends()
wordCase = wordKind(currRuneCase)
}
switch wordCase {
case upperWordCase:
wordCase = titleWordCase
}
}
prevRuneCase = currRuneCase
currRuneIndex += s
}
appends()
return names
}
// FormatSnake returns format to snake
func (n namecase) FormatSnake(wordKind wordKind, split string) string {
if len(n) == 0 {
return ""
}
buf := bytes.NewBuffer(nil)
for _, word := range n {
if word.kind == splitWordCase {
continue
}
if buf.Len() != 0 {
buf.WriteString(split)
}
buf.WriteString(word.convert(wordKind))
}
bytes := buf.Bytes()
return *(*string)(unsafe.Pointer(&bytes))
}
// FormatCamel returns format to camel
func (n namecase) FormatCamel(firstKind wordKind, otherKind wordKind) string {
if len(n) == 0 {
return ""
}
buf := bytes.NewBuffer(nil)
for _, word := range n {
if word.kind == splitWordCase {
continue
}
if buf.Len() == 0 {
buf.WriteString(word.convert(firstKind))
} else {
buf.WriteString(word.convert(otherKind))
}
}
bytes := buf.Bytes()
return *(*string)(unsafe.Pointer(&bytes))
}