-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcollate_json.go
111 lines (99 loc) · 2.16 KB
/
collate_json.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
110
111
// transform json encoded value into collate encoding.
// cnf: NumberKind, arrayLenPrefix, propertyLenPrefix
package gson
func collate2json(code []byte, text []byte, config *Config) (int, int) {
if len(code) == 0 {
return 0, 0
}
var scratch [64]byte
n, m := 1, 0
switch code[0] {
case TypeMissing:
copy(text, MissingLiteral)
return n + 1, m + len(MissingLiteral)
case TypeNull:
copy(text, "null")
return n + 1, m + 4
case TypeTrue:
copy(text, "true")
return n + 1, m + 4
case TypeFalse:
copy(text, "false")
return n + 1, m + 5
case TypeNumber:
x := getDatum(code[n:])
y := collated2Json(code[n:n+x-1], text, config.nk)
return n + x, m + y
case TypeString:
var x int
bufn := config.bufferh.getbuffer(len(code[n:]) * 5)
scratch := bufn.data
scratch, x = collate2String(code[n:], scratch[:])
if config.strict {
config.buf.Reset()
if err := config.enc.Encode(bytes2str(scratch)); err != nil {
panic(err)
}
s := config.buf.Bytes()
m += copy(text[m:], s[:len(s)-1]) // -1 to strip \n
config.bufferh.putbuffer(bufn)
return n + x, m
}
remtxt, err := encodeString(scratch, text[m:m])
if err != nil {
panic(err)
}
config.bufferh.putbuffer(bufn)
return n + x, m + len(remtxt)
case TypeArray:
if config.arrayLenPrefix {
x := getDatum(code[n:])
collated2Int(code[n:n+x-1], scratch[:])
n += x
}
text[m] = '['
m++
for code[n] != Terminator {
x, y := collate2json(code[n:], text[m:], config)
n += x
m += y
text[m] = ','
m++
}
n++ // skip terminator
if text[m-1] == ',' {
text[m-1] = ']'
} else {
text[m] = ']'
m++
}
return n, m
case TypeObj:
if config.propertyLenPrefix {
x := getDatum(code[n:])
collated2Int(code[n:n+x-1], scratch[:])
n += x
}
text[m] = '{'
m++
for code[n] != Terminator {
x, y := collate2json(code[n:], text[m:], config)
n, m = n+x, m+y
text[m] = ':'
m++
x, y = collate2json(code[n:], text[m:], config)
n, m = n+x, m+y
text[m] = ','
m++
}
n++ // skip terminator
if text[m-1] == ',' {
text[m-1] = '}'
} else {
text[m] = '}'
m++
}
return n, m
}
panic("collate decode to json invalid binary")
}