Debian Codegraph @

internal/encoder/map_collect.go

raw
1 package encoder
2
3 import (
4 "encoding/binary"
5 "reflect"
6 "unsafe"
7
8 "github.com/goccy/go-json/internal/runtime"
9 )
10
11 // The entries of a map are read into the map context before they are encoded: the keys and the values are
12 // copied, so that the VM encodes them from the context, in the order of the map or sorted by the keys.
13 //
14 // The runtime has no public function which gives the entries of a map of a type known only at run time
15 // without an allocation: reflect.MapIter copies a key and a value with a call of ten nanoseconds each, and
16 // go-json read them through linknames of the runtime for years. Instead, a map with keys of a string kind is
17 // ranged over as a map of the same layout: the layout of a map depends only on the size and the alignment of
18 // the key and of the value, and the hash depends only on the key. So map[K]V, with K of a string kind and
19 // V of up to 256 bytes, is read as map[string][n]uint64 by the code the compiler makes for a range: no
20 // allocation, no call for an entry, and no dependence on the runtime beyond the layout of a map being what
21 // its type says. A map of another key is read by reflect.MapIter, which is slower but is the public way.
22
23 // MapLayout is how the VM reads the entries of a map of a type, decided when the type is compiled.
24 type MapLayout struct {
25 // collect reads the entries of the map at p into the context.
26 collect func(p unsafe.Pointer, c *MapContext)
27 // StringKey is whether the keys are of a string kind: then they are in MapContext.Keys.
28 StringKey bool
29 // A map whose entries are not sorted is written by the VM as it reads the map, when its keys are of a
30 // string kind and the values are written by one opcode of a scalar ( ScalarValue: the map is ranged over
31 // as a map of a value of ValueWords words, appendMapScalarValues ), or when the values are of interface{},
32 // the map of a JSON object as a value of interface{} ( InterfaceValue: the values which hold a scalar are
33 // written, and the others are read into the context, appendMapAsRead ).
34 ScalarValue bool
35 InterfaceValue bool
36 // ValueWords is the number of the words of a value when the map is ranged over as a map of the same layout,
37 // or -1 when it is read by reflect.
38 ValueWords int
39 keySize uintptr
40 valueSize uintptr
41 // KeysMayEscape is whether an encoded key may have an escape, which puts it out of the order of its name
42 // ( see Mapslice.Sort ): the keys of a kind other than a string or an integer are texts.
43 KeysMayEscape bool
44 }
45
46 // MapScalarValueWords is the largest ValueWords of a value written by one opcode of a scalar: a slice of bytes.
47 const MapScalarValueWords = 3
48
49 // mapValueWords is the number of the words of a value up to which a map is ranged over as a map of the same
50 // layout. A value of more than 128 bytes is stored out of the map by the runtime, but so is the value of the
51 // map[string][n]uint64 of its size, so the layouts are still the same. Each size is a function of about a
52 // kilobyte of code, so the sizes stop at twice that one of the runtime; a larger value is read by reflect.
53 const mapValueWords = 32
54
55 // NewMapLayout returns how the VM reads a map of the type.
56 func NewMapLayout(typ reflect.Type) *MapLayout {
57 l := &MapLayout{
58 StringKey: typ.Key().Kind() == reflect.String,
59 keySize: typ.Key().Size(),
60 valueSize: typ.Elem().Size(),
61 }
62 switch typ.Key().Kind() {
63 case reflect.String, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
64 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
65 // a key of a string kind is sorted by its string, unless it has MarshalText, and an integer has no escape.
66 l.KeysMayEscape = typ.Key().Implements(marshalTextType) || reflect.PointerTo(typ.Key()).Implements(marshalTextType)
67 default:
68 l.KeysMayEscape = true
69 }
70 words := (l.valueSize + 7) / 8
71 if l.StringKey && words <= mapValueWords && (mapValueIsWords || l.valueSize%8 == 0) {
72 l.collect = stringKeyCollectors[words]
73 l.valueSize = words * 8
74 l.ValueWords = int(words)
75 l.InterfaceValue = typ.Elem().Kind() == reflect.Interface && typ.Elem().NumMethod() == 0
76 } else {
77 l.collect = newReflectCollector(typ)
78 l.ValueWords = -1
79 }
80 return l
81 }
82
83 // collectStringKeys reads the map at p, as a map[string]V, into the context.
84 func collectStringKeys[V any](p unsafe.Pointer, c *MapContext) {
85 for k, v := range *(*map[string]V)(unsafe.Pointer(&p)) {
86 c.Keys = append(c.Keys, k)
87 c.Values = append(c.Values, unsafe.Slice((*byte)(unsafe.Pointer(&v)), unsafe.Sizeof(v))...)
88 }
89 }
90
91 // stringKeyCollectors are the functions which read a map with keys of a string kind, by the words of a value.
92 var stringKeyCollectors = [mapValueWords + 1]func(unsafe.Pointer, *MapContext){
93 collectStringKeys[[0]uint64],
94 collectStringKeys[[1]uint64],
95 collectStringKeys[[2]uint64],
96 collectStringKeys[[3]uint64],
97 collectStringKeys[[4]uint64],
98 collectStringKeys[[5]uint64],
99 collectStringKeys[[6]uint64],
100 collectStringKeys[[7]uint64],
101 collectStringKeys[[8]uint64],
102 collectStringKeys[[9]uint64],
103 collectStringKeys[[10]uint64],
104 collectStringKeys[[11]uint64],
105 collectStringKeys[[12]uint64],
106 collectStringKeys[[13]uint64],
107 collectStringKeys[[14]uint64],
108 collectStringKeys[[15]uint64],
109 collectStringKeys[[16]uint64],
110 collectStringKeys[[17]uint64],
111 collectStringKeys[[18]uint64],
112 collectStringKeys[[19]uint64],
113 collectStringKeys[[20]uint64],
114 collectStringKeys[[21]uint64],
115 collectStringKeys[[22]uint64],
116 collectStringKeys[[23]uint64],
117 collectStringKeys[[24]uint64],
118 collectStringKeys[[25]uint64],
119 collectStringKeys[[26]uint64],
120 collectStringKeys[[27]uint64],
121 collectStringKeys[[28]uint64],
122 collectStringKeys[[29]uint64],
123 collectStringKeys[[30]uint64],
124 collectStringKeys[[31]uint64],
125 collectStringKeys[[32]uint64],
126 }
127
128 // newReflectCollector returns the function which reads a map of the type by reflect.MapIter: the key and the
129 // value of an entry are set to interface values, which then refer to them in the map, or hold them if they
130 // are of a pointer shape, without an allocation.
131 func newReflectCollector(typ reflect.Type) func(unsafe.Pointer, *MapContext) {
132 keyType, valueType := typ.Key(), typ.Elem()
133 if keyType.Kind() == reflect.Interface {
134 return newInterfaceKeyCollector(typ)
135 }
136 stringKey := keyType.Kind() == reflect.String
137 keySize, valueSize := keyType.Size(), valueType.Size()
138 keyDirect, valueDirect := !runtime.IfaceIndir(keyType), !runtime.IfaceIndir(valueType)
139 // a value which is an interface value is copied to the interface value as it is: the value is the words.
140 valueIsIface := valueType.Kind() == reflect.Interface
141 typPtr := runtime.TypePtr(typ)
142 return func(p unsafe.Pointer, c *MapContext) {
143 // the map as a value which is not addressable: SetIterKey copies the key of an addressable map.
144 var mapIface any
145 *(*emptyInterface)(unsafe.Pointer(&mapIface)) = emptyInterface{typ: typPtr, ptr: p}
146 m := reflect.ValueOf(mapIface)
147 key := reflect.ValueOf(&c.keyIface).Elem()
148 value := reflect.ValueOf(&c.valueIface).Elem()
149 it := &c.iter
150 it.Reset(m)
151 for it.Next() {
152 key.SetIterKey(it)
153 value.SetIterValue(it)
154 k := ifaceData(&c.keyIface, keyDirect)
155 if stringKey {
156 c.Keys = append(c.Keys, *(*string)(k))
157 } else {
158 c.RawKeys = append(c.RawKeys, unsafe.Slice((*byte)(k), keySize)...)
159 }
160 v := ifaceData(&c.valueIface, valueDirect)
161 if valueIsIface {
162 v = unsafe.Pointer(&c.valueIface)
163 }
164 c.Values = append(c.Values, unsafe.Slice((*byte)(v), valueSize)...)
165 }
166 it.Reset(reflect.Value{})
167 c.keyIface, c.valueIface = nil, nil
168 }
169 }
170
171 // newInterfaceKeyCollector is newReflectCollector for a map whose keys are of an interface type: a key is the
172 // words of the interface{} it is set to, whatever its interface type is ( see appendInterfaceMapKey ).
173 func newInterfaceKeyCollector(typ reflect.Type) func(unsafe.Pointer, *MapContext) {
174 valueType := typ.Elem()
175 valueSize := valueType.Size()
176 valueDirect := !runtime.IfaceIndir(valueType)
177 valueIsIface := valueType.Kind() == reflect.Interface
178 typPtr := runtime.TypePtr(typ)
179 return func(p unsafe.Pointer, c *MapContext) {
180 var mapIface any
181 *(*emptyInterface)(unsafe.Pointer(&mapIface)) = emptyInterface{typ: typPtr, ptr: p}
182 m := reflect.ValueOf(mapIface)
183 key := reflect.ValueOf(&c.keyIface).Elem()
184 value := reflect.ValueOf(&c.valueIface).Elem()
185 it := &c.iter
186 it.Reset(m)
187 for it.Next() {
188 key.SetIterKey(it)
189 value.SetIterValue(it)
190 c.RawKeys = append(c.RawKeys, unsafe.Slice((*byte)(unsafe.Pointer(&c.keyIface)), unsafe.Sizeof(c.keyIface))...)
191 v := ifaceData(&c.valueIface, valueDirect)
192 if valueIsIface {
193 v = unsafe.Pointer(&c.valueIface)
194 }
195 c.Values = append(c.Values, unsafe.Slice((*byte)(v), valueSize)...)
196 }
197 it.Reset(reflect.Value{})
198 c.keyIface, c.valueIface = nil, nil
199 }
200 }
201
202 // ifaceData returns the address of the value held by the interface value: the data word if the value is stored
203 // in it, which is the case for a value of a pointer shape, or what the data word points to.
204 func ifaceData(iface *any, direct bool) unsafe.Pointer {
205 data := &(*emptyInterface)(unsafe.Pointer(iface)).ptr
206 if direct {
207 return unsafe.Pointer(data)
208 }
209 return *data
210 }
211
212 // Reset empties the context for the entries of a map of the layout.
213 func (l *MapLayout) Reset(c *MapContext) {
214 c.Keys, c.RawKeys, c.Values = c.Keys[:0], c.RawKeys[:0], c.Values[:0]
215 c.layout = l
216 }
217
218 // Collect reads the entries of the map at p into the context, and returns their number.
219 func (l *MapLayout) Collect(p unsafe.Pointer, c *MapContext) int {
220 l.Reset(c)
221 l.collect(p, c)
222 if l.StringKey {
223 c.Len = len(c.Keys)
224 } else {
225 c.Len = len(c.RawKeys) / int(l.keySize)
226 }
227 return c.Len
228 }
229
230 // MapLen returns the number of the entries of the map at p. The length of a map is in its header, whatever
231 // its type, so the map is read as one of any type.
232 func MapLen(p unsafe.Pointer) int {
233 return len(*(*map[struct{}]struct{})(unsafe.Pointer(&p)))
234 }
235
236 // KeyAt returns the address of the key of the entry: the string in Keys, or the bytes in RawKeys.
237 func (c *MapContext) KeyAt(i int) unsafe.Pointer {
238 if c.layout.StringKey {
239 return unsafe.Pointer(&c.Keys[i])
240 }
241 return unsafe.Pointer(&c.RawKeys[uintptr(i)*c.layout.keySize])
242 }
243
244 // ValueAt returns the address of the value of the entry. A value of no size has an address all the same: the
245 // opcode of a struct takes a nil one for a nil pointer.
246 func (c *MapContext) ValueAt(i int) unsafe.Pointer {
247 if c.layout.valueSize == 0 {
248 return unsafe.Pointer(&c.Len)
249 }
250 return unsafe.Pointer(&c.Values[uintptr(i)*c.layout.valueSize])
251 }
252
253 // SortKeys sorts the entries by their keys, which are strings, as encoding/json does: Order is the entries in
254 // that order.
255 //
256 // A comparison of two keys is by their first eight bytes as one number first, which decides it for most of
257 // the keys of a JSON object, and by the strings only when those are the same: a comparison of strings is a
258 // call which costs more than the rest of a sort of a small map. The sort is written here, so that the
259 // comparisons are inlined into it: a sort which takes the comparison as a function, as slices.SortFunc does,
260 // calls it for every one.
261 func (c *MapContext) SortKeys() {
262 n := len(c.Keys)
263 if cap(c.Order) < n {
264 c.Order = make([]int32, n)
265 c.prefixes = make([]uint64, n)
266 }
267 order, prefixes, keys := c.Order[:n], c.prefixes[:n], c.Keys
268 for i, key := range keys {
269 order[i] = int32(i)
270 prefixes[i] = keyPrefix(key)
271 }
272 if n > maxItemsOfInsertionSort {
273 sortKeyOrder(order, prefixes, keys)
274 } else {
275 insertionSortKeyOrder(order, prefixes, keys)
276 }
277 c.Order = order
278 }
279
280 // keyLess is whether the key of the entry a comes before the one of b.
281 func keyLess(a, b int32, prefixes []uint64, keys []string) bool {
282 if pa, pb := prefixes[a], prefixes[b]; pa != pb {
283 return pa < pb
284 }
285 return keys[a] < keys[b]
286 }
287
288 // sortKeyOrder sorts the entries of order by their keys: by quicksort, with the median of three entries as the
289 // pivot, down to the parts of up to maxItemsOfInsertionSort entries, which are sorted by insertion. The smaller
290 // part is sorted first, and the larger one by the loop, so that the depth is logarithmic.
291 func sortKeyOrder(order []int32, prefixes []uint64, keys []string) {
292 for len(order) > maxItemsOfInsertionSort {
293 last := len(order) - 1
294 mid := last / 2
295 // the median of the first, the middle and the last entries, at the middle
296 if keyLess(order[mid], order[0], prefixes, keys) {
297 order[0], order[mid] = order[mid], order[0]
298 }
299 if keyLess(order[last], order[mid], prefixes, keys) {
300 order[mid], order[last] = order[last], order[mid]
301 if keyLess(order[mid], order[0], prefixes, keys) {
302 order[0], order[mid] = order[mid], order[0]
303 }
304 }
305 pivot := order[mid]
306 // Hoare's partition: the keys are distinct, so an entry equals the pivot only if it is the pivot.
307 i, j := 0, last
308 for {
309 for keyLess(order[i], pivot, prefixes, keys) {
310 i++
311 }
312 for keyLess(pivot, order[j], prefixes, keys) {
313 j--
314 }
315 if i >= j {
316 break
317 }
318 order[i], order[j] = order[j], order[i]
319 i++
320 j--
321 }
322 if j+1 < len(order)-j-1 {
323 sortKeyOrder(order[:j+1], prefixes, keys)
324 order = order[j+1:]
325 } else {
326 sortKeyOrder(order[j+1:], prefixes, keys)
327 order = order[:j+1]
328 }
329 }
330 insertionSortKeyOrder(order, prefixes, keys)
331 }
332
333 // insertionSortKeyOrder sorts the entries of order by their keys by insertion, which is the fastest sort of a few
334 // entries.
335 func insertionSortKeyOrder(order []int32, prefixes []uint64, keys []string) {
336 for i := 1; i < len(order); i++ {
337 e := order[i]
338 if !keyLess(e, order[i-1], prefixes, keys) {
339 continue
340 }
341 j := i
342 for ; j > 0 && keyLess(e, order[j-1], prefixes, keys); j-- {
343 order[j] = order[j-1]
344 }
345 order[j] = e
346 }
347 }
348
349 // keyPrefix returns the first eight bytes of the key as a number which compares as the bytes do, with zeros
350 // after a shorter key: a shorter key compares as less, as it should, unless the other has zeros there, and then
351 // the strings are compared.
352 func keyPrefix(key string) uint64 {
353 if len(key) >= 8 {
354 return binary.BigEndian.Uint64(unsafe.Slice(unsafe.StringData(key), 8))
355 }
356 var b [8]byte
357 copy(b[:], key)
358 return binary.BigEndian.Uint64(b[:])
359 }