-
-
Notifications
You must be signed in to change notification settings - Fork 148
/
indent.go
108 lines (106 loc) · 2.4 KB
/
indent.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
package json
import "bytes"
func encodeWithIndent(dst *bytes.Buffer, src []byte, prefix, indentStr string) error {
length := int64(len(src))
indentNum := 0
indentBytes := []byte(indentStr)
for cursor := int64(0); cursor < length; cursor++ {
c := src[cursor]
switch c {
case ' ', '\t', '\n', '\r':
continue
case '"':
if err := dst.WriteByte(c); err != nil {
return err
}
for {
cursor++
if err := dst.WriteByte(src[cursor]); err != nil {
return err
}
switch src[cursor] {
case '\\':
cursor++
if err := dst.WriteByte(src[cursor]); err != nil {
return err
}
case '"':
goto LOOP_END
case nul:
return errUnexpectedEndOfJSON("string", int64(length))
}
}
case '{':
if cursor+1 < length && src[cursor+1] == '}' {
if _, err := dst.Write([]byte{'{', '}'}); err != nil {
return err
}
cursor++
} else {
indentNum++
b := []byte{c, '\n'}
b = append(b, prefix...)
b = append(b, bytes.Repeat(indentBytes, indentNum)...)
if _, err := dst.Write(b); err != nil {
return err
}
}
case '}':
indentNum--
if indentNum < 0 {
return errInvalidCharacter('}', "}", cursor)
}
b := []byte{'\n'}
b = append(b, prefix...)
b = append(b, bytes.Repeat(indentBytes, indentNum)...)
b = append(b, c)
if _, err := dst.Write(b); err != nil {
return err
}
case '[':
if cursor+1 < length && src[cursor+1] == ']' {
if _, err := dst.Write([]byte{'[', ']'}); err != nil {
return err
}
cursor++
} else {
indentNum++
b := []byte{c, '\n'}
b = append(b, prefix...)
b = append(b, bytes.Repeat(indentBytes, indentNum)...)
if _, err := dst.Write(b); err != nil {
return err
}
}
case ']':
indentNum--
if indentNum < 0 {
return errInvalidCharacter(']', "]", cursor)
}
b := []byte{'\n'}
b = append(b, prefix...)
b = append(b, bytes.Repeat(indentBytes, indentNum)...)
b = append(b, c)
if _, err := dst.Write(b); err != nil {
return err
}
case ':':
if _, err := dst.Write([]byte{':', ' '}); err != nil {
return err
}
case ',':
b := []byte{',', '\n'}
b = append(b, prefix...)
b = append(b, bytes.Repeat(indentBytes, indentNum)...)
if _, err := dst.Write(b); err != nil {
return err
}
default:
if err := dst.WriteByte(c); err != nil {
return err
}
}
LOOP_END:
}
return nil
}