1
2
3
4
5
6
7 package json
8
9 import (
10 "bytes"
11 "fmt"
12 "reflect"
13 "sort"
14 "strings"
15 "sync"
16 "unicode"
17 "unicode/utf8"
18 )
19
20 const (
21 patchStrategyTagKey = "patchStrategy"
22 patchMergeKeyTagKey = "patchMergeKey"
23 )
24
25
26
27
28
29 func LookupPatchMetadataForStruct(t reflect.Type, jsonField string) (
30 elemType reflect.Type, patchStrategies []string, patchMergeKey string, e error) {
31 if t.Kind() == reflect.Pointer {
32 t = t.Elem()
33 }
34
35 if t.Kind() != reflect.Struct {
36 e = fmt.Errorf("merging an object in json but data type is not struct, instead is: %s",
37 t.Kind().String())
38 return
39 }
40 jf := []byte(jsonField)
41
42 var f *field
43 fields := cachedTypeFields(t)
44 for i := range fields {
45 ff := &fields[i]
46 if bytes.Equal(ff.nameBytes, jf) {
47 f = ff
48 break
49 }
50
51 if f == nil && ff.equalFold(ff.nameBytes, jf) {
52 f = ff
53 }
54 }
55 if f != nil {
56
57 tjf := t.Field(f.index[0])
58
59 for i := 1; i < len(f.index); i++ {
60 tjf = tjf.Type.Field(f.index[i])
61 }
62 patchStrategy := tjf.Tag.Get(patchStrategyTagKey)
63 patchMergeKey = tjf.Tag.Get(patchMergeKeyTagKey)
64 patchStrategies = strings.Split(patchStrategy, ",")
65 elemType = tjf.Type
66 return
67 }
68 e = fmt.Errorf("unable to find api field in struct %s for the json field %q", t.Name(), jsonField)
69 return
70 }
71
72
73 type field struct {
74 name string
75 nameBytes []byte
76 equalFold func(s, t []byte) bool
77
78 tag bool
79
80
81
82 index []int
83 typ reflect.Type
84 omitEmpty bool
85 quoted bool
86 }
87
88 func (f field) String() string {
89 return fmt.Sprintf("{name: %s, type: %v, tag: %v, index: %v, omitEmpty: %v, quoted: %v}", f.name, f.typ, f.tag, f.index, f.omitEmpty, f.quoted)
90 }
91
92 func fillField(f field) field {
93 f.nameBytes = []byte(f.name)
94 f.equalFold = foldFunc(f.nameBytes)
95 return f
96 }
97
98
99
100
101 type byName []field
102
103 func (x byName) Len() int { return len(x) }
104
105 func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
106
107 func (x byName) Less(i, j int) bool {
108 if x[i].name != x[j].name {
109 return x[i].name < x[j].name
110 }
111 if len(x[i].index) != len(x[j].index) {
112 return len(x[i].index) < len(x[j].index)
113 }
114 if x[i].tag != x[j].tag {
115 return x[i].tag
116 }
117 return byIndex(x).Less(i, j)
118 }
119
120
121 type byIndex []field
122
123 func (x byIndex) Len() int { return len(x) }
124
125 func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
126
127 func (x byIndex) Less(i, j int) bool {
128 for k, xik := range x[i].index {
129 if k >= len(x[j].index) {
130 return false
131 }
132 if xik != x[j].index[k] {
133 return xik < x[j].index[k]
134 }
135 }
136 return len(x[i].index) < len(x[j].index)
137 }
138
139
140
141
142 func typeFields(t reflect.Type) []field {
143
144 current := []field{}
145 next := []field{{typ: t}}
146
147
148 count := map[reflect.Type]int{}
149 nextCount := map[reflect.Type]int{}
150
151
152 visited := map[reflect.Type]bool{}
153
154
155 var fields []field
156
157 for len(next) > 0 {
158 current, next = next, current[:0]
159 count, nextCount = nextCount, map[reflect.Type]int{}
160
161 for _, f := range current {
162 if visited[f.typ] {
163 continue
164 }
165 visited[f.typ] = true
166
167
168 for i := 0; i < f.typ.NumField(); i++ {
169 sf := f.typ.Field(i)
170 if sf.PkgPath != "" {
171 continue
172 }
173 tag := sf.Tag.Get("json")
174 if tag == "-" {
175 continue
176 }
177 name, opts := parseTag(tag)
178 if !isValidTag(name) {
179 name = ""
180 }
181 index := make([]int, len(f.index)+1)
182 copy(index, f.index)
183 index[len(f.index)] = i
184
185 ft := sf.Type
186 if ft.Name() == "" && ft.Kind() == reflect.Pointer {
187
188 ft = ft.Elem()
189 }
190
191
192 if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct {
193 tagged := name != ""
194 if name == "" {
195 name = sf.Name
196 }
197 fields = append(fields, fillField(field{
198 name: name,
199 tag: tagged,
200 index: index,
201 typ: ft,
202 omitEmpty: opts.Contains("omitempty"),
203 quoted: opts.Contains("string"),
204 }))
205 if count[f.typ] > 1 {
206
207
208
209
210 fields = append(fields, fields[len(fields)-1])
211 }
212 continue
213 }
214
215
216 nextCount[ft]++
217 if nextCount[ft] == 1 {
218 next = append(next, fillField(field{name: ft.Name(), index: index, typ: ft}))
219 }
220 }
221 }
222 }
223
224 sort.Sort(byName(fields))
225
226
227
228
229
230
231
232 out := fields[:0]
233 for advance, i := 0, 0; i < len(fields); i += advance {
234
235
236 fi := fields[i]
237 name := fi.name
238 for advance = 1; i+advance < len(fields); advance++ {
239 fj := fields[i+advance]
240 if fj.name != name {
241 break
242 }
243 }
244 if advance == 1 {
245 out = append(out, fi)
246 continue
247 }
248 dominant, ok := dominantField(fields[i : i+advance])
249 if ok {
250 out = append(out, dominant)
251 }
252 }
253
254 fields = out
255 sort.Sort(byIndex(fields))
256
257 return fields
258 }
259
260
261
262
263
264
265
266 func dominantField(fields []field) (field, bool) {
267
268
269
270 length := len(fields[0].index)
271 tagged := -1
272 for i, f := range fields {
273 if len(f.index) > length {
274 fields = fields[:i]
275 break
276 }
277 if f.tag {
278 if tagged >= 0 {
279
280
281 return field{}, false
282 }
283 tagged = i
284 }
285 }
286 if tagged >= 0 {
287 return fields[tagged], true
288 }
289
290
291
292 if len(fields) > 1 {
293 return field{}, false
294 }
295 return fields[0], true
296 }
297
298 var fieldCache struct {
299 sync.RWMutex
300 m map[reflect.Type][]field
301 }
302
303
304 func cachedTypeFields(t reflect.Type) []field {
305 fieldCache.RLock()
306 f := fieldCache.m[t]
307 fieldCache.RUnlock()
308 if f != nil {
309 return f
310 }
311
312
313
314 f = typeFields(t)
315 if f == nil {
316 f = []field{}
317 }
318
319 fieldCache.Lock()
320 if fieldCache.m == nil {
321 fieldCache.m = map[reflect.Type][]field{}
322 }
323 fieldCache.m[t] = f
324 fieldCache.Unlock()
325 return f
326 }
327
328 func isValidTag(s string) bool {
329 if s == "" {
330 return false
331 }
332 for _, c := range s {
333 switch {
334 case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c):
335
336
337
338 default:
339 if !unicode.IsLetter(c) && !unicode.IsDigit(c) {
340 return false
341 }
342 }
343 }
344 return true
345 }
346
347 const (
348 caseMask = ^byte(0x20)
349 kelvin = '\u212a'
350 smallLongEss = '\u017f'
351 )
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368 func foldFunc(s []byte) func(s, t []byte) bool {
369 nonLetter := false
370 special := false
371 for _, b := range s {
372 if b >= utf8.RuneSelf {
373 return bytes.EqualFold
374 }
375 upper := b & caseMask
376 if upper < 'A' || upper > 'Z' {
377 nonLetter = true
378 } else if upper == 'K' || upper == 'S' {
379
380 special = true
381 }
382 }
383 if special {
384 return equalFoldRight
385 }
386 if nonLetter {
387 return asciiEqualFold
388 }
389 return simpleLetterEqualFold
390 }
391
392
393
394
395
396 func equalFoldRight(s, t []byte) bool {
397 for _, sb := range s {
398 if len(t) == 0 {
399 return false
400 }
401 tb := t[0]
402 if tb < utf8.RuneSelf {
403 if sb != tb {
404 sbUpper := sb & caseMask
405 if 'A' <= sbUpper && sbUpper <= 'Z' {
406 if sbUpper != tb&caseMask {
407 return false
408 }
409 } else {
410 return false
411 }
412 }
413 t = t[1:]
414 continue
415 }
416
417
418 tr, size := utf8.DecodeRune(t)
419 switch sb {
420 case 's', 'S':
421 if tr != smallLongEss {
422 return false
423 }
424 case 'k', 'K':
425 if tr != kelvin {
426 return false
427 }
428 default:
429 return false
430 }
431 t = t[size:]
432
433 }
434 if len(t) > 0 {
435 return false
436 }
437 return true
438 }
439
440
441
442
443
444 func asciiEqualFold(s, t []byte) bool {
445 if len(s) != len(t) {
446 return false
447 }
448 for i, sb := range s {
449 tb := t[i]
450 if sb == tb {
451 continue
452 }
453 if ('a' <= sb && sb <= 'z') || ('A' <= sb && sb <= 'Z') {
454 if sb&caseMask != tb&caseMask {
455 return false
456 }
457 } else {
458 return false
459 }
460 }
461 return true
462 }
463
464
465
466
467
468 func simpleLetterEqualFold(s, t []byte) bool {
469 if len(s) != len(t) {
470 return false
471 }
472 for i, b := range s {
473 if b&caseMask != t[i]&caseMask {
474 return false
475 }
476 }
477 return true
478 }
479
480
481
482 type tagOptions string
483
484
485
486 func parseTag(tag string) (string, tagOptions) {
487 if idx := strings.Index(tag, ","); idx != -1 {
488 return tag[:idx], tagOptions(tag[idx+1:])
489 }
490 return tag, tagOptions("")
491 }
492
493
494
495
496 func (o tagOptions) Contains(optionName string) bool {
497 if len(o) == 0 {
498 return false
499 }
500 s := string(o)
501 for s != "" {
502 var next string
503 i := strings.Index(s, ",")
504 if i >= 0 {
505 s, next = s[:i], s[i+1:]
506 }
507 if s == optionName {
508 return true
509 }
510 s = next
511 }
512 return false
513 }
514
View as plain text