Debian Codegraph @

internal/decoder/struct_keys.go

raw
1 package decoder
2
3 import (
4 "bytes"
5 "encoding/binary"
6 "math/bits"
7 "unicode"
8 "unicode/utf8"
9 )
10
11 // structKeys finds the field of a struct which an object key is decoded into, as encoding/json does:
12 // the field whose key is the same, or else the first field whose key is the same by case folding.
13 //
14 // The fields are in a table keyed by their folded keys: the fields of a folded key are in one entry, so that
15 // a key is looked up once, whether it matches a field exactly or by folding. A key is looked up by two words:
16 // its first eight bytes, and its last eight bytes, which overlap the first ones for a key shorter than 16 bytes.
17 // These are all the bytes of a key of up to 16 bytes, so such a key is compared by its length and the two words
18 // only; a longer one is compared by the words between them as well. The words of a key of ASCII are folded in
19 // place, eight bytes at a time, and only a key which is not ASCII is folded rune by rune.
20 type structKeys struct {
21 entries []keyEntry
22 shift uint
23 // lengths has the bit of the length of every folded key ( 63 for the longer keys ):
24 // a key of another length matches no field, which is known without a lookup.
25 lengths uint64
26 // exact is a table of the keys which are not ASCII, by their bytes as they are ( see findExact ), and
27 // exactLengths has the bit of the length of every such key, as lengths does for the folded keys.
28 exact []keyEntry
29 exactShift uint
30 exactLengths uint64
31 // foldRunes has a bit for every rune which is not ASCII and which folds to a rune of a folded key, by the
32 // low byte of the rune ( see mayFold ).
33 foldRunes [4]uint64
34 // foldLeads has a bit for the first byte of the encoding of every rune of foldRunes ( see leadMayFold ).
35 foldLeads [4]uint64
36 // hasRuneError is set if a key has utf8.RuneError, which a byte of an object key which is not valid UTF-8
37 // is replaced by.
38 hasRuneError bool
39 }
40
41 type keyEntry struct {
42 // short is the word of the folded key if it is of less than 8 bytes, none of which is nul, and its field
43 // is the only one: a short key of ASCII whose folded word is the same is of that field, whatever its case.
44 // It is noShortKey for any other entry, which no such word is.
45 short uint64
46 // w0 and w1 are the words of the folded key, and n its length.
47 w0, w1 uint64
48 n int
49 folded []byte
50 // unique is the field of the folded key if it is the only one, which a key matches whichever its case.
51 unique *structFieldSet
52 // fields are the fields of the folded key in the order of the struct: the first one is the field of
53 // a key which matches none of them exactly.
54 fields []*structFieldSet
55 }
56
57 // hasLength reports whether a key of n bytes may match a field.
58 func (k *structKeys) hasLength(n int) bool {
59 return k.lengths&(1<<(uint(min(n, 63))&63)) != 0
60 }
61
62 // newStructKeys makes the table of the fields, which are in the order of the struct.
63 func newStructKeys(fields []*structFieldSet) *structKeys {
64 // the table is at most half full, so that a lookup ends after a few entries.
65 size := 8
66 for size < 2*len(fields) {
67 size *= 2
68 }
69 k := &structKeys{
70 entries: make([]keyEntry, size),
71 shift: uint(64 - bits.TrailingZeros(uint(size))),
72 }
73 for _, field := range fields {
74 folded := appendFoldedKey(nil, []byte(field.key))
75 if e := k.find(folded); e != nil {
76 e.fields = append(e.fields, field)
77 e.unique = nil
78 continue
79 }
80 k.insert(folded, field)
81 }
82 k.makeExact(fields)
83 k.makeFoldRunes(fields)
84 for i := range k.entries {
85 e := &k.entries[i]
86 e.short = noShortKey
87 if e.unique != nil && e.n < 8 && !bytes.Contains(e.folded, []byte{0}) {
88 e.short = e.w0
89 }
90 }
91 return k
92 }
93
94 // makeExact makes the table of the keys which are not ASCII, by their bytes as they are. A key which is not
95 // valid UTF-8 is not in it: an object key which is not valid UTF-8 is decoded with its bytes replaced first.
96 func (k *structKeys) makeExact(fields []*structFieldSet) {
97 var keys []*structFieldSet
98 for _, field := range fields {
99 if !isASCII(field.key) && utf8.ValidString(field.key) {
100 keys = append(keys, field)
101 }
102 }
103 if len(keys) == 0 {
104 return
105 }
106 size := 8
107 for size < 2*len(keys) {
108 size *= 2
109 }
110 k.exact = make([]keyEntry, size)
111 k.exactShift = uint(64 - bits.TrailingZeros(uint(size)))
112 for _, field := range keys {
113 key := []byte(field.key)
114 w0, w1 := keyWords(key)
115 h0, h1 := hashWords(w0, w1, len(key))
116 mask := len(k.exact) - 1
117 for i := indexOf(h0, h1, k.exactShift); ; i = (i + 1) & mask {
118 if k.exact[i].unique == nil {
119 k.exact[i] = keyEntry{w0: w0, w1: w1, n: len(key), folded: key, unique: field}
120 k.exactLengths |= 1 << (uint(min(len(key), 63)) & 63)
121 break
122 }
123 }
124 }
125 }
126
127 // findExact returns the field whose key is the same as the key, which is not ASCII and is in a buffer which
128 // has room for a word after it, or nil. w0 and w1 are the words of the key as keyWords makes them.
129 func (k *structKeys) findExact(key []byte, w0, w1 uint64) *structFieldSet {
130 n := len(key)
131 mask := len(k.exact) - 1
132 h0, h1 := hashWords(w0, w1, n)
133 for i := indexOf(h0, h1, k.exactShift); ; i = (i + 1) & mask {
134 e := &k.exact[i]
135 if e.unique == nil {
136 return nil
137 }
138 if e.n == n && e.w0 == w0 && e.w1 == w1 && (n <= 16 || equalMiddleWords(key, e.folded)) {
139 return e.unique
140 }
141 }
142 }
143
144 // hasExactLength reports whether a key of n bytes which is not ASCII may be the same as the key of a field.
145 func (k *structKeys) hasExactLength(n int) bool {
146 return k.exactLengths&(1<<(uint(min(n, 63))&63)) != 0
147 }
148
149 // equalMiddleWords reports whether two keys of the same length of more than 16 bytes, whose first and last eight
150 // bytes are known to be the same, have the same words between them.
151 func equalMiddleWords(a, b []byte) bool {
152 n := len(a)
153 if n != len(b) {
154 return false
155 }
156 for i := 8; i < n-8; i += 8 {
157 if binary.LittleEndian.Uint64(a[i:]) != binary.LittleEndian.Uint64(b[i:]) {
158 return false
159 }
160 }
161 return true
162 }
163
164 // makeFoldRunes sets the bits of the runes which are not ASCII and fold to a rune of a key: the runes of the
165 // fold orbits of the runes of the keys, which include the Kelvin sign for K and the long s for S.
166 func (k *structKeys) makeFoldRunes(fields []*structFieldSet) {
167 for _, field := range fields {
168 for _, r := range field.key {
169 if r == utf8.RuneError {
170 k.hasRuneError = true
171 }
172 for f := r; ; {
173 if f >= utf8.RuneSelf {
174 k.foldRunes[f&0xff>>6] |= 1 << (uint(f) & 63)
175 lead := utf8.AppendRune(nil, f)[0]
176 k.foldLeads[lead>>6] |= 1 << (lead & 63)
177 }
178 if f = unicode.SimpleFold(f); f == r {
179 break
180 }
181 }
182 }
183 }
184 }
185
186 // mayFold reports whether a key which is not ASCII may be of a field by case folding: every rune of it which
187 // is not ASCII folds to a rune of a key, which is told by the low byte of the rune. The low byte is taken from
188 // the last two bytes of the encoding of the rune, which is not decoded. A key which is not valid UTF-8 has its
189 // invalid bytes replaced by utf8.RuneError, so it may be of a field only if a key has utf8.RuneError: then
190 // the runes are decoded.
191 func (k *structKeys) mayFold(key []byte) bool {
192 if k.hasRuneError {
193 return k.mayFoldDecoded(key)
194 }
195 n := len(key)
196 for i := 0; i < n; {
197 c := key[i]
198 if c < utf8.RuneSelf {
199 i++
200 continue
201 }
202 size := 2
203 switch {
204 case c < 0xc0:
205 return false // a continuation byte without a first byte: not valid UTF-8
206 case c >= 0xf0:
207 size = 4
208 case c >= 0xe0:
209 size = 3
210 }
211 if i+size > n {
212 return false
213 }
214 low := key[i+size-2]&3<<6 | key[i+size-1]&0x3f
215 if k.foldRunes[low>>6]&(1<<(low&63)) == 0 {
216 return false
217 }
218 i += size
219 }
220 return true
221 }
222
223 // leadMayFold reports whether the first byte of the key which is not ASCII, if it is in the first word of the
224 // key, w0, may be the first byte of a rune which folds to a rune of a key, and else true. It is the cheapest
225 // check, which needs no load: most keys which are of no field are told so by it.
226 func (k *structKeys) leadMayFold(w0 uint64) bool {
227 high := w0 & msb
228 if high == 0 || k.hasRuneError {
229 return true
230 }
231 lead := byte(w0 >> (uint(bits.TrailingZeros64(high)) - 7))
232 return k.foldLeads[lead>>6]&(1<<(lead&63)) != 0
233 }
234
235 // firstRuneMayFold reports whether the first rune of the key which is not ASCII may fold to a rune of a key, if
236 // that rune begins in the first word of the key, w0, and else true: it tells mayFold for most keys, without a
237 // call. The low byte of the rune is taken from its bytes as mayFold does, and a key which may not be valid
238 // UTF-8 is left to mayFold.
239 func (k *structKeys) firstRuneMayFold(key []byte, w0 uint64) bool {
240 high := w0 & msb
241 if high == 0 || k.hasRuneError {
242 return true
243 }
244 i := bits.TrailingZeros64(high) / 8
245 c := key[i]
246 size := 2
247 switch {
248 case c < 0xc0:
249 return true
250 case c >= 0xf0:
251 size = 4
252 case c >= 0xe0:
253 size = 3
254 }
255 if i+size > len(key) {
256 return true
257 }
258 low := key[i+size-2]&3<<6 | key[i+size-1]&0x3f
259 return k.foldRunes[low>>6]&(1<<(low&63)) != 0
260 }
261
262 // mayFoldDecoded is mayFold by the decoded runes.
263 func (k *structKeys) mayFoldDecoded(key []byte) bool {
264 for i := 0; i < len(key); {
265 if key[i] < utf8.RuneSelf {
266 i++
267 continue
268 }
269 r, size := utf8.DecodeRune(key[i:])
270 if k.foldRunes[r&0xff>>6]&(1<<(uint(r)&63)) == 0 {
271 return false
272 }
273 i += size
274 }
275 return true
276 }
277
278 func isASCII(s string) bool {
279 for i := 0; i < len(s); i++ {
280 if s[i] >= utf8.RuneSelf {
281 return false
282 }
283 }
284 return true
285 }
286
287 // noShortKey is the short word of an entry which a short key is not found by: a word of ASCII has no byte of
288 // 0x80 or more.
289 const noShortKey = ^uint64(0)
290
291 // keyWords returns the words of a key: its first eight bytes and its last eight bytes, as little-endian
292 // numbers, which are zero where the key is shorter. The capacity of the key is read past its length when it
293 // has room, which is the rest of the buffer of the input.
294 func keyWords(key []byte) (uint64, uint64) {
295 n := len(key)
296 switch {
297 case n >= 8:
298 return binary.LittleEndian.Uint64(key), binary.LittleEndian.Uint64(key[n-8:])
299 case cap(key) >= 8:
300 return binary.LittleEndian.Uint64(key[:8]) & (1<<(8*uint(n)) - 1), 0
301 }
302 var w uint64
303 for i := n - 1; i >= 0; i-- {
304 w = w<<8 | uint64(key[i])
305 }
306 return w, 0
307 }
308
309 // index returns the first entry to look at for a key whose words are w0 and w1, with the bit 5 of their bytes
310 // set by hashWords: a letter of either case has the same index, so the index of a key is made from its bytes
311 // before they are folded. The product spreads the keys, which differ in a few bits.
312 func (k *structKeys) index(w0, w1 uint64) int {
313 return indexOf(w0, w1, k.shift)
314 }
315
316 func indexOf(w0, w1 uint64, shift uint) int {
317 h := (w0 ^ bits.RotateLeft64(w1, 29)) * 0x9E3779B97F4A7C15
318 return int(h >> shift)
319 }
320
321 // hashWords returns the words of a key of n bytes, or of its folded key, which index takes: the bit 5 of their
322 // bytes set, which folding a letter doesn't change, and the bytes after the key zero.
323 func hashWords(w0, w1 uint64, n int) (uint64, uint64) {
324 if n < 8 {
325 return (w0 | bit5) & (1<<(uint(n)*8&63) - 1), 0
326 }
327 return w0 | bit5, w1 | bit5
328 }
329
330 func (k *structKeys) insert(folded []byte, field *structFieldSet) {
331 w0, w1 := keyWords(folded)
332 mask := len(k.entries) - 1
333 for i := k.index(hashWords(w0, w1, len(folded))); ; i = (i + 1) & mask {
334 if k.entries[i].fields == nil {
335 k.entries[i] = keyEntry{w0: w0, w1: w1, n: len(folded), folded: folded, unique: field, fields: []*structFieldSet{field}}
336 k.lengths |= 1 << uint(min(len(folded), 63))
337 return
338 }
339 }
340 }
341
342 // find returns the entry of the folded key, or nil.
343 func (k *structKeys) find(folded []byte) *keyEntry {
344 w0, w1 := keyWords(folded)
345 n := len(folded)
346 mask := len(k.entries) - 1
347 for i := k.index(hashWords(w0, w1, n)); ; i = (i + 1) & mask {
348 e := &k.entries[i]
349 if e.fields == nil {
350 return nil
351 }
352 if e.n == n && e.w0 == w0 && e.w1 == w1 && (n <= 16 || string(e.folded) == string(folded)) {
353 return e
354 }
355 }
356 }
357
358 // field returns the field of the key among the fields of its folded key: the one whose key is the same,
359 // or the first one.
360 func (e *keyEntry) field(key []byte) *structFieldSet {
361 if len(e.fields) == 1 {
362 return e.fields[0]
363 }
364 for _, field := range e.fields {
365 if field.key == string(key) {
366 return field
367 }
368 }
369 return e.fields[0]
370 }
371
372 // findASCII returns the field of a key of ASCII without an escape, whose words are w0 and w1, or nil.
373 func (k *structKeys) findASCII(key []byte, w0, w1 uint64) *structFieldSet {
374 n := len(key)
375 start := k.index(hashWords(w0, w1, n))
376 w0, w1 = foldASCIIWord(w0), foldASCIIWord(w1)
377 mask := len(k.entries) - 1
378 for i := start; ; i = (i + 1) & mask {
379 e := &k.entries[i]
380 if e.fields == nil {
381 return nil
382 }
383 if e.n == n && e.w0 == w0 && e.w1 == w1 && (n <= 16 || equalFoldedASCII(key, e.folded)) {
384 if len(e.fields) == 1 {
385 return e.fields[0]
386 }
387 return e.field(key)
388 }
389 }
390 }
391
392 // foldASCIIWord folds the bytes of a word of ASCII as encoding/json does: a lower case letter to upper case.
393 func foldASCIIWord(w uint64) uint64 {
394 // the bytes are less than 0x80: adding to one never carries to the next.
395 ge := w + (0x80-'a')*lsb // 0x80 in the bytes from 'a'
396 gt := w + (0x80-'z'-1)*lsb // 0x80 in the bytes after 'z'
397 lower := (ge &^ gt) & msb // 0x80 in the lower case letters
398 return w &^ (lower >> 2) // clear 0x20 of them
399 }
400
401 // equalFoldedASCII reports whether the key of ASCII, of more than 16 bytes, folds to folded, whose first and
402 // last eight bytes are known to be the ones of the key folded: the words between them are compared.
403 func equalFoldedASCII(key, folded []byte) bool {
404 n := len(key)
405 if n != len(folded) {
406 return false
407 }
408 for i := 8; i < n-8; i += 8 {
409 if foldASCIIWord(binary.LittleEndian.Uint64(key[i:])) != binary.LittleEndian.Uint64(folded[i:]) {
410 return false
411 }
412 }
413 return true
414 }
415
416 // lookup returns the field of the key, or nil, and the key, which is decoded in place if it is escaped.
417 func (k *structKeys) lookup(key []byte, info stringInfo) (*structFieldSet, []byte) {
418 if info.firstEscape < 0 && !info.nonASCII {
419 if !k.hasLength(len(key)) {
420 return nil, key
421 }
422 w0, w1 := keyWords(key)
423 return k.findASCII(key, w0, w1), key
424 }
425 key = decodeLiteral(key, info)
426 var arr [64]byte
427 if e := k.find(appendFoldedKey(arr[:0], key)); e != nil {
428 return e.field(key), key
429 }
430 return nil, key
431 }
432
433 // appendFoldedKey appends the key folded as encoding/json folds a key to compare it case insensitively:
434 // a lower case ASCII letter to upper case, and any other rune to the smallest rune which folds to it.
435 func appendFoldedKey(out, key []byte) []byte {
436 for i := 0; i < len(key); {
437 if c := key[i]; c < utf8.RuneSelf {
438 if 'a' <= c && c <= 'z' {
439 c -= 'a' - 'A'
440 }
441 out = append(out, c)
442 i++
443 continue
444 }
445 r, n := utf8.DecodeRune(key[i:])
446 out = utf8.AppendRune(out, foldRune(r))
447 i += n
448 }
449 return out
450 }
451
452 // foldRune returns the smallest rune of the fold set of r.
453 func foldRune(r rune) rune {
454 for {
455 r2 := unicode.SimpleFold(r)
456 if r2 <= r {
457 return r2
458 }
459 r = r2
460 }
461 }