| 1 |
package encoder |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"sync" |
| 6 |
"unsafe" |
| 7 |
|
| 8 |
"github.com/goccy/go-json/internal/runtime" |
| 9 |
) |
| 10 |
|
| 11 |
type compileContext struct { |
| 12 |
opcodeIndex uint32 |
| 13 |
ptrIndex int |
| 14 |
indent uint32 |
| 15 |
escapeKey bool |
| 16 |
structTypeToCodes map[uintptr]Opcodes |
| 17 |
recursiveCodes *Opcodes |
| 18 |
} |
| 19 |
|
| 20 |
func (c *compileContext) incIndent() { |
| 21 |
c.indent++ |
| 22 |
} |
| 23 |
|
| 24 |
func (c *compileContext) decIndent() { |
| 25 |
c.indent-- |
| 26 |
} |
| 27 |
|
| 28 |
func (c *compileContext) incIndex() { |
| 29 |
c.incOpcodeIndex() |
| 30 |
c.incPtrIndex() |
| 31 |
} |
| 32 |
|
| 33 |
func (c *compileContext) decIndex() { |
| 34 |
c.decOpcodeIndex() |
| 35 |
c.decPtrIndex() |
| 36 |
} |
| 37 |
|
| 38 |
func (c *compileContext) incOpcodeIndex() { |
| 39 |
c.opcodeIndex++ |
| 40 |
} |
| 41 |
|
| 42 |
func (c *compileContext) decOpcodeIndex() { |
| 43 |
c.opcodeIndex-- |
| 44 |
} |
| 45 |
|
| 46 |
func (c *compileContext) incPtrIndex() { |
| 47 |
c.ptrIndex++ |
| 48 |
} |
| 49 |
|
| 50 |
func (c *compileContext) decPtrIndex() { |
| 51 |
c.ptrIndex-- |
| 52 |
} |
| 53 |
|
| 54 |
const ( |
| 55 |
bufSize = 1024 |
| 56 |
) |
| 57 |
|
| 58 |
var ( |
| 59 |
runtimeContextPool = sync.Pool{ |
| 60 |
New: func() any { |
| 61 |
return &RuntimeContext{ |
| 62 |
Buf: make([]byte, 0, bufSize), |
| 63 |
Slots: make([]uintptr, 128*slotWords), |
| 64 |
Option: &Option{}, |
| 65 |
} |
| 66 |
}, |
| 67 |
} |
| 68 |
) |
| 69 |
|
| 70 |
// Slot is the layout of a slot of the VM. The opcodes refer to a half of a slot by its offset from the head of |
| 71 |
// the frame: Ptr is for a pointer ( the address of a value, the context of a map, the opcode to return to ) and |
| 72 |
// Int is for the other values ( an index, a length, the offset of a frame, an indent ). |
| 73 |
// |
| 74 |
// The slots are in the heap, and both halves are stored as uintptr there: a store of a pointer to the heap goes |
| 75 |
// through the write barrier while the GC is marking, which made the encoding of a struct about 50% slower during |
| 76 |
// that time. So the GC doesn't see the slots, and what they refer to is kept alive by others: |
| 77 |
// - the value passed to Marshal is kept alive by its caller, and so is everything reachable from it |
| 78 |
// - the value copied from an interface value is referred to by RuntimeContext |
| 79 |
// - the context of a map is referred to by RuntimeContext |
| 80 |
// |
| 81 |
// The opcodes are never freed. |
| 82 |
type Slot struct { |
| 83 |
Ptr unsafe.Pointer |
| 84 |
Int uintptr |
| 85 |
} |
| 86 |
|
| 87 |
// slotWords is the number of the words of a slot. |
| 88 |
const slotWords = 2 |
| 89 |
|
| 90 |
const ( |
| 91 |
// recentCodeSetSets is the number of the sets of the recent opcodes, of recentCodeSetWays entries each. |
| 92 |
// The set of a type is the top bits of the product of its address with an odd constant, which spreads |
| 93 |
// the addresses of the types, which are close to each other, over the sets. |
| 94 |
// |
| 95 |
// The shape of the table is by BenchmarkVariant_RecentCodeSets and by the encoding of values whose types |
| 96 |
// are of the same set, on arm64 and on the amd64 machines of the CI: |
| 97 |
// - a lookup which hits costs the same whatever the number of the sets ( 16 to 128 ), and a miss |
| 98 |
// costs the lookup of the shared table on top: 4 ns on arm64, 8 ns on amd64; |
| 99 |
// - two entries per set cost the same as one when the first entry hits, and a third and a fourth |
| 100 |
// entry cost a nanosecond for every value of interface{} on arm64, whether they hit or not; |
| 101 |
// - more sets only make it rarer for three types encoded by turns to be of one set: it is the case |
| 102 |
// for some three of six types, which a document of map[string]interface{} has, in 8% of the |
| 103 |
// binaries with 16 sets and in 2% with 32. That is not worth the memory of every context: 64 sets, |
| 104 |
// 1 KB, measured +1% on the whole on amd64, and 32 sets measured nothing. |
| 105 |
// So the table is 256 B: 16 sets of two entries. |
| 106 |
recentCodeSetSets = 16 |
| 107 |
recentCodeSetHashShift = 64 - 4 |
| 108 |
// recentCodeSetWays is the number of the types a set holds: the ones hashed to it which were encoded |
| 109 |
// last. Two types encoded by turns, such as the type passed to Marshal and the type held by its values |
| 110 |
// of interface{}, never evict each other then, whatever their addresses are. With one entry per set, |
| 111 |
// they did whenever their addresses hashed to the same entry, which depends on where the binary has the |
| 112 |
// types, and every Marshal of them cost two lookups of the table shared by every goroutine: 20% of the |
| 113 |
// encoding of a small value, present or absent by the build. Three types of a set encoded by turns still |
| 114 |
// evict each other, which costs those lookups, not the result. |
| 115 |
recentCodeSetWays = 2 |
| 116 |
) |
| 117 |
|
| 118 |
type recentCodeSet struct { |
| 119 |
typeptr uintptr |
| 120 |
codeSet *OpcodeSet |
| 121 |
} |
| 122 |
|
| 123 |
// recentCodeSetSet is the entries of a set, the one encoded last first. |
| 124 |
type recentCodeSetSet [recentCodeSetWays]recentCodeSet |
| 125 |
|
| 126 |
type RuntimeContext struct { |
| 127 |
Context context.Context |
| 128 |
Buf []byte |
| 129 |
MarshalBuf []byte |
| 130 |
Slots []uintptr |
| 131 |
SeenPtr []unsafe.Pointer |
| 132 |
BaseIndent uint32 |
| 133 |
// RecursiveLevel and SlotOffset are the state of the VM which only the opcodes of an interface value and of |
| 134 |
// a recursive type use. They are here, not in the variables of the VM: the VM keeps its variables in the |
| 135 |
// registers across the opcodes, and it has to restore every one of them after each call in an opcode. |
| 136 |
RecursiveLevel int |
| 137 |
SlotOffset uintptr |
| 138 |
// TailLevels is the number of the values of a recursive type which are being encoded in the current frame, |
| 139 |
// one after the other as the last field of the previous, without a frame of their own: see |
| 140 |
// EnterTailRecursive. Their braces are closed one by one when the last of them ends. |
| 141 |
TailLevels uint32 |
| 142 |
Prefix []byte |
| 143 |
IndentStr []byte |
| 144 |
Option *Option |
| 145 |
// mapContexts are the contexts of the maps nested in each other, one for each level, and mapDepth is the |
| 146 |
// number of the maps being encoded. |
| 147 |
mapContexts []*MapContext |
| 148 |
mapDepth int |
| 149 |
// nested is whether a frame was added by ReserveSlots: only such a frame uses SeenPtr. |
| 150 |
nested bool |
| 151 |
// topValue holds the value passed to Marshal when it is stored directly in its interface value: the |
| 152 |
// interface value is an argument, whose address may change with the stack, so the value is copied here. |
| 153 |
topValue unsafe.Pointer |
| 154 |
// recentCodeSets are the opcodes of the types encoded last, in the sets indexed by the address of the type. |
| 155 |
recentCodeSets [recentCodeSetSets]recentCodeSetSet |
| 156 |
// value is a zero value of the type of valueCodeSet in the heap, which MarshalOf copies its argument to. |
| 157 |
// It is zeroed again after the encoding. |
| 158 |
valueCodeSet *OpcodeSet |
| 159 |
value unsafe.Pointer |
| 160 |
} |
| 161 |
|
| 162 |
// ValueAddr returns the address of the value passed to Marshal, which the data word of its interface value |
| 163 |
// represents. |
| 164 |
// |
| 165 |
// The opcodes always take the address of a value. The data word of an interface value is the address |
| 166 |
// for most of the types, but it is the value itself if the type is stored directly ( a pointer, a map, |
| 167 |
// a struct of a single pointer, ... ). Such a value is copied to the context, and the address of the copy |
| 168 |
// is returned. |
| 169 |
func (c *RuntimeContext) ValueAddr(codeSet *OpcodeSet, dataWord unsafe.Pointer) unsafe.Pointer { |
| 170 |
if codeSet.DataWordIsAddr { |
| 171 |
return dataWord |
| 172 |
} |
| 173 |
c.topValue = dataWord |
| 174 |
return unsafe.Pointer(&c.topValue) |
| 175 |
} |
| 176 |
|
| 177 |
func (c *RuntimeContext) Init(p unsafe.Pointer, codelen int) { |
| 178 |
if len(c.Slots) < codelen*slotWords { |
| 179 |
c.Slots = make([]uintptr, codelen*slotWords) |
| 180 |
} |
| 181 |
c.Slots[0] = uintptr(p) |
| 182 |
c.SeenPtr = c.SeenPtr[:0] |
| 183 |
c.BaseIndent = 0 |
| 184 |
c.RecursiveLevel = 0 |
| 185 |
c.SlotOffset = 0 |
| 186 |
c.TailLevels = 0 |
| 187 |
} |
| 188 |
|
| 189 |
// ReserveSlots makes the context have the slots of the frames up to the length. |
| 190 |
func (c *RuntimeContext) ReserveSlots(length uintptr) { |
| 191 |
c.nested = true |
| 192 |
if uintptr(len(c.Slots)) < length*slotWords { |
| 193 |
c.growSlots(length) |
| 194 |
} |
| 195 |
} |
| 196 |
|
| 197 |
//go:noinline |
| 198 |
func (c *RuntimeContext) growSlots(length uintptr) { |
| 199 |
c.Slots = append(c.Slots, make([]uintptr, int(length)*slotWords-len(c.Slots))...) |
| 200 |
} |
| 201 |
|
| 202 |
// Ptr returns the pointer to the slots. |
| 203 |
// It is unsafe.Pointer, not uintptr, so that the address of a slot is calculated by unsafe.Add, |
| 204 |
// which the compiler folds into the addressing mode of the load / store of the slot. |
| 205 |
func (c *RuntimeContext) Ptr() unsafe.Pointer { |
| 206 |
header := (*runtime.SliceHeader)(unsafe.Pointer(&c.Slots)) |
| 207 |
return header.Data |
| 208 |
} |
| 209 |
|
| 210 |
func TakeRuntimeContext() *RuntimeContext { |
| 211 |
return runtimeContextPool.Get().(*RuntimeContext) |
| 212 |
} |
| 213 |
|
| 214 |
func ReleaseRuntimeContext(ctx *RuntimeContext) { |
| 215 |
// The context of a call must neither be kept by the pool nor be seen by the next call, |
| 216 |
// which may not be given a context at all. |
| 217 |
ctx.Option.Context = nil |
| 218 |
ctx.releaseValues() |
| 219 |
runtimeContextPool.Put(ctx) |
| 220 |
} |
| 221 |
|
| 222 |
// releaseValues clears every pointer to the values which were encoded, so that the pool doesn't keep them alive. |
| 223 |
func (c *RuntimeContext) releaseValues() { |
| 224 |
c.topValue = nil |
| 225 |
c.mapDepth = 0 |
| 226 |
if c.nested { |
| 227 |
// what only the frames of an interface value and of a recursive type use. |
| 228 |
clear(c.SeenPtr[:cap(c.SeenPtr)]) |
| 229 |
c.nested = false |
| 230 |
} |
| 231 |
} |
| 232 |
|
| 233 |
// marshalerContext returns the context to call MarshalJSON(context.Context) with. |
| 234 |
// It is never nil, also for a call which is not given a context. |
| 235 |
func (c *RuntimeContext) marshalerContext() context.Context { |
| 236 |
if c.Option.Context == nil { |
| 237 |
return context.Background() |
| 238 |
} |
| 239 |
return c.Option.Context |
| 240 |
} |