Debian Codegraph @

internal/encoder/vm/util.go

raw
1 package vm
2
3 import (
4 "encoding/json"
5 "fmt"
6 "math"
7 "unsafe"
8
9 "github.com/goccy/go-json/internal/encoder"
10 "github.com/goccy/go-json/internal/runtime"
11 )
12
13 // The functions which the template calls as appendInt, appendString and so on are the ones of the encoder
14 // package here, and the generator makes the VM call them directly: a call through a function variable is a load
15 // and an indirect call, for every value the VM appends. appendScalar has them as variables for its own calls.
16 var (
17 appendInt = encoder.AppendInt
18 appendUint = encoder.AppendUint
19 appendFloat64 = encoder.AppendFloat64
20 appendString = encoder.AppendString
21 appendByteSlice = encoder.AppendByteSlice
22 appendNumber = encoder.AppendNumber
23 errUnsupportedFloat = encoder.ErrUnsupportedFloat
24 )
25
26 type emptyInterface struct {
27 typ unsafe.Pointer
28 ptr unsafe.Pointer
29 }
30
31 func errUnimplementedOp(op encoder.OpType) error {
32 return fmt.Errorf("encoder: opcode %s has not been implemented", op)
33 }
34
35 // load / store are for the half of a slot for a pointer, and loadInt / storeInt are for the other half.
36 // A pointer is stored as uintptr, which needs no write barrier: see encoder.Slot.
37
38 func load(base unsafe.Pointer, idx uint32) unsafe.Pointer {
39 return *(*unsafe.Pointer)(unsafe.Add(base, idx))
40 }
41
42 func store(base unsafe.Pointer, idx uint32, p unsafe.Pointer) {
43 *(*uintptr)(unsafe.Add(base, idx)) = uintptr(p)
44 }
45
46 func loadInt(base unsafe.Pointer, idx uint32) uintptr {
47 return *(*uintptr)(unsafe.Add(base, idx))
48 }
49
50 func storeInt(base unsafe.Pointer, idx uint32, v uintptr) {
51 *(*uintptr)(unsafe.Add(base, idx)) = v
52 }
53
54 func ptrToUint64(p unsafe.Pointer, bitSize uint8) uint64 {
55 switch bitSize {
56 case 8:
57 return uint64(*(*uint8)(p))
58 case 16:
59 return uint64(*(*uint16)(p))
60 case 32:
61 return uint64(*(*uint32)(p))
62 case 64:
63 return *(*uint64)(p)
64 }
65 return 0
66 }
67 func ptrToFloat32(p unsafe.Pointer) float32 { return *(*float32)(p) }
68
69 // isInfOrNaN is whether the float is not finite, which encoding/json refuses: the exponent is all ones.
70 // math.IsInf is not inlined into Run, which is a big function to the inliner; this is.
71 func isInfOrNaN(v float64) bool {
72 const exponent = 0x7ff << 52
73 return math.Float64bits(v)&exponent == exponent
74 }
75
76 // appendFloat32 appends the float, or returns the error for one which is not finite as encoding/json does.
77 func appendFloat32(ctx *encoder.RuntimeContext, b []byte, v float32) ([]byte, error) {
78 if isInfOrNaN(float64(v)) {
79 return nil, errUnsupportedFloat(float64(v))
80 }
81 return encoder.AppendFloat32(ctx, b, v), nil
82 }
83 func ptrToFloat64(p unsafe.Pointer) float64 { return *(*float64)(p) }
84 func ptrToBool(p unsafe.Pointer) bool { return *(*bool)(p) }
85 func ptrToBytes(p unsafe.Pointer) []byte { return *(*[]byte)(p) }
86 func ptrToNumber(p unsafe.Pointer) json.Number { return *(*json.Number)(p) }
87 func ptrToString(p unsafe.Pointer) string { return *(*string)(p) }
88 func ptrToSlice(p unsafe.Pointer) *runtime.SliceHeader { return (*runtime.SliceHeader)(p) }
89 func ptrToPtr(p unsafe.Pointer) unsafe.Pointer { return *(*unsafe.Pointer)(p) }
90
91 // ptrToNPtr follows the pointer ptrNum times, or up to a nil one. It is written to be inlined into Run,
92 // which is a big function: only a function whose cost is 20 or less is inlined into it.
93 func ptrToNPtr(p unsafe.Pointer, ptrNum uint8) unsafe.Pointer {
94 for ; ptrNum > 0 && p != nil; ptrNum-- {
95 p = *(*unsafe.Pointer)(p)
96 }
97 return p
98 }
99
100 func ptrToInterface(code *encoder.Opcode, p unsafe.Pointer) any {
101 return *(*any)(unsafe.Pointer(&emptyInterface{
102 typ: code.Type,
103 ptr: p,
104 }))
105 }
106
107 func appendBool(_ *encoder.RuntimeContext, b []byte, v bool) []byte {
108 if v {
109 return append(b, "true"...)
110 }
111 return append(b, "false"...)
112 }
113
114 func appendNull(_ *encoder.RuntimeContext, b []byte) []byte {
115 return append(b, "null"...)
116 }
117
118 func appendComma(_ *encoder.RuntimeContext, b []byte) []byte {
119 return append(b, ',')
120 }
121
122 func appendNullComma(_ *encoder.RuntimeContext, b []byte) []byte {
123 return append(b, "null,"...)
124 }
125
126 func appendColon(_ *encoder.RuntimeContext, b []byte) []byte {
127 last := len(b) - 1
128 b[last] = ':'
129 return b
130 }
131
132 func appendMapKeyValue(_ *encoder.RuntimeContext, _ *encoder.Opcode, b, key, value []byte) []byte {
133 b = append(b, key...)
134 b[len(b)-1] = ':'
135 return append(b, value...)
136 }
137
138 func appendMapEnd(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte {
139 b[len(b)-1] = '}'
140 b = append(b, ',')
141 return b
142 }
143
144 func appendMarshalJSON(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte, p unsafe.Pointer) ([]byte, error) {
145 return encoder.AppendMarshalJSON(ctx, code, b, p)
146 }
147
148 func appendMarshalText(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte, p unsafe.Pointer) ([]byte, error) {
149 return encoder.AppendMarshalText(ctx, code, b, p)
150 }
151
152 func appendArrayHead(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte {
153 return append(b, '[')
154 }
155
156 func appendArrayEnd(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte {
157 last := len(b) - 1
158 b[last] = ']'
159 return append(b, ',')
160 }
161
162 func appendEmptyArray(_ *encoder.RuntimeContext, b []byte) []byte {
163 return append(b, '[', ']', ',')
164 }
165
166 func appendEmptyObject(_ *encoder.RuntimeContext, b []byte) []byte {
167 return append(b, '{', '}', ',')
168 }
169
170 func appendObjectEnd(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte {
171 last := len(b) - 1
172 b[last] = '}'
173 return append(b, ',')
174 }
175
176 func appendStructHead(_ *encoder.RuntimeContext, b []byte) []byte {
177 return append(b, '{')
178 }
179
180 // appendStructKey appends a key which is up to a chunk long, by two copies of a half chunk each: the key is
181 // followed by its padding in memory ( encoder.PaddedKey ), and the length is cut back to the key after.
182 // A copy of a half chunk is inlined by the compiler on amd64 and arm64; a call of memmove, or of this
183 // function, makes the VM spill and restore its registers, which costs more than the copy of a key.
184 //
185 // Run is a big function to the inliner, which inlines into it only a function whose cost is 20 or less:
186 // this one costs 19. A key longer than a chunk is written by appendLongStructKey, by the generic field opcode.
187 func appendStructKey(_ *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte {
188 const half = encoder.KeyChunkSize / 2
189 return append(append(b, code.KeyChunk[:half]...), code.KeyChunk[half:]...)[:len(b)+len(code.Key)]
190 }
191
192 // appendLongStructKey appends a key of any length.
193 func appendLongStructKey(_ *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte {
194 return append(b, code.Key...)
195 }
196
197 func appendStructEnd(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte {
198 return append(b, '}', ',')
199 }
200
201 // commaAtEnd is 1 for a comma: what appendStructEndSkipLast cuts from the end.
202 var commaAtEnd = [256]uint8{',': 1}
203
204 // appendStructEndSkipLast ends the struct, over the comma after its last field if there is one: there is none
205 // after an empty struct or when every field is omitted. The comma is cut by a table, not a branch, so that
206 // the function costs 18 to the inliner and is inlined into Run ( see appendStructKey ).
207 func appendStructEndSkipLast(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte {
208 return append(b[:len(b)-int(commaAtEnd[b[len(b)-1]])], '}', ',')
209 }
210
211 func appendMapKeyIndent(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { return b }
212 func appendArrayElemIndent(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { return b }
213
214 // appendScalar appends the value at p by the opcode of a scalar, with the comma: what the VM does for the opcode.
215 // It is for a scalar held by an interface value, which is encoded without a frame.
216 //
217 //go:noinline
218 func appendScalar(ctx *encoder.RuntimeContext, b []byte, code *encoder.Opcode, p unsafe.Pointer) ([]byte, error) {
219 switch code.Op {
220 case encoder.OpInt:
221 b = appendInt(ctx, b, p, code)
222 case encoder.OpUint:
223 b = appendUint(ctx, b, p, code)
224 case encoder.OpFloat32:
225 bb, err := appendFloat32(ctx, b, ptrToFloat32(p))
226 if err != nil {
227 return nil, err
228 }
229 b = bb
230 case encoder.OpFloat64:
231 v := ptrToFloat64(p)
232 if isInfOrNaN(v) {
233 return nil, errUnsupportedFloat(v)
234 }
235 b = appendFloat64(ctx, b, v)
236 case encoder.OpString:
237 b = appendString(ctx, b, ptrToString(p))
238 case encoder.OpBool:
239 b = appendBool(ctx, b, ptrToBool(p))
240 case encoder.OpBytes:
241 b = appendByteSlice(ctx, b, ptrToBytes(p))
242 case encoder.OpNumber:
243 bb, err := appendNumber(ctx, b, ptrToNumber(p))
244 if err != nil {
245 return nil, err
246 }
247 b = bb
248 default:
249 return nil, errUnimplementedOp(code.Op)
250 }
251 return appendComma(ctx, b), nil
252 }