-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjsonc.go
More file actions
90 lines (82 loc) · 1.61 KB
/
Copy pathjsonc.go
File metadata and controls
90 lines (82 loc) · 1.61 KB
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
package jsonc
import (
"encoding/json"
)
func Unmarshal(data []byte, v interface{}) error {
processedData := stripComments(data)
return json.Unmarshal(processedData, v)
}
func stripComments(data []byte) []byte {
const (
OUTSIDE = iota
SINGLE_LINE
MULTI_LINE
IN_STRING
)
state := OUTSIDE
hasComment := false
scanLoop:
for i := 0; i < len(data); i++ {
switch state {
case OUTSIDE:
if data[i] == '/' && i+1 < len(data) && (data[i+1] == '/' || data[i+1] == '*') {
hasComment = true
break scanLoop
}
if data[i] == '"' {
state = IN_STRING
}
case IN_STRING:
if data[i] == '\\' && i+1 < len(data) {
i++
} else if data[i] == '"' {
state = OUTSIDE
}
}
}
if !hasComment {
return data
}
state = OUTSIDE
result := make([]byte, 0, len(data))
for i := 0; i < len(data); i++ {
switch state {
case OUTSIDE:
if data[i] == '/' && i+1 < len(data) {
if data[i+1] == '/' {
state = SINGLE_LINE
i++
} else if data[i+1] == '*' {
state = MULTI_LINE
i++
} else {
result = append(result, data[i])
}
} else {
if data[i] == '"' {
state = IN_STRING
}
result = append(result, data[i])
}
case SINGLE_LINE:
if data[i] == '\n' {
state = OUTSIDE
result = append(result, '\n')
}
case MULTI_LINE:
if data[i] == '*' && i+1 < len(data) && data[i+1] == '/' {
state = OUTSIDE
i++
}
case IN_STRING:
result = append(result, data[i])
if data[i] == '\\' && i+1 < len(data) {
i++
result = append(result, data[i])
} else if data[i] == '"' {
state = OUTSIDE
}
}
}
return result
}