-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecommenter.go
76 lines (71 loc) · 1.49 KB
/
decommenter.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
package betterjson
func decomment(data []byte) []byte {
const (
OUTSIDE = iota
SINGLE_LINE
MULTI_LINE
MULTI_LINE_ENDING
IN_STRING
)
state := OUTSIDE
result := make([]byte, len(data))
copy(result, data)
stateHandlers := []func(int, []byte, []byte) int{
// OUTSIDE
func(i int, data, result []byte) int {
if data[i] == '/' && i+1 < len(data) {
if result[i+1] == '/' {
state = SINGLE_LINE
result[i] = ' '
result[i+1] = ' '
return i + 1 // skip the next character
} else if data[i+1] == '*' {
state = MULTI_LINE
result[i] = ' '
result[i+1] = ' '
return i + 1 // skip the next character
}
} else if data[i] == '"' {
state = IN_STRING
}
return i
},
// SINGLE_LINE
func(i int, data, result []byte) int {
if data[i] == '\n' {
state = OUTSIDE
} else {
result[i] = ' '
}
return i
},
// MULTI_LINE
func(i int, data, result []byte) int {
if data[i] == '*' && i+1 < len(result) && data[i+1] == '/' {
state = MULTI_LINE_ENDING
result[i] = ' '
result[i+1] = ' '
return i + 1 // skip the next character
} else if result[i] != '\n' {
result[i] = ' '
}
return i
},
// MULTI_LINE_ENDING
func(i int, data, result []byte) int {
state = OUTSIDE
return i
},
// IN_STRING
func(i int, data, result []byte) int {
if data[i] == '"' {
state = OUTSIDE
}
return i
},
}
for i := 0; i < len(result); i++ {
i = stateHandlers[state](i, data, result)
}
return result
}