summaryrefslogtreecommitdiff
path: root/struct.go
blob: ee2bbf360149b3c348317bad54f2a047307e68c8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
// Copyright (C) 2022  Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later

package lowmemjson

import (
	"reflect"
)

type structField struct {
	Name      string
	Path      []int
	Tagged    bool
	OmitEmpty bool
	Quote     bool
}

type structIndex struct {
	byPos  []structField
	byName map[string]int
}

func indexStruct(typ reflect.Type) structIndex {
	var byPos []structField
	byName := make(map[string][]int)

	indexStructInner(typ, nil, &byPos, byName, map[reflect.Type]struct{}{})

	ret := structIndex{
		byName: make(map[string]int),
	}

	for curPos, _field := range byPos {
		name := _field.Name
		fieldPoss := byName[name]
		switch len(fieldPoss) {
		case 0:
			// do nothing
		case 1:
			ret.byName[name] = len(ret.byPos)
			ret.byPos = append(ret.byPos, _field)
		default:
			// To quote the encoding/json docs (version 1.18.4):
			//
			//    If there are multiple fields at the same level, and that level is the
			//    least nested (and would therefore be the nesting level selected by the
			//    usual Go rules), the following extra rules apply:
			//
			//    1) Of those fields, if any are JSON-tagged, only tagged fields are
			//       considered, even if there are multiple untagged fields that would
			//       otherwise conflict.
			//
			//    2) If there is exactly one field (tagged or not according to the first
			//       rule), that is selected.
			//
			//    3) Otherwise there are multiple fields, and all are ignored; no error
			//       occurs.
			leastLevel := len(byPos[fieldPoss[0]].Path)
			for _, fieldPos := range fieldPoss[1:] {
				field := byPos[fieldPos]
				if len(field.Path) < leastLevel {
					leastLevel = len(field.Path)
				}
			}
			var numUntagged, numTagged int
			var untaggedPos, taggedPos int
			for _, fieldPos := range fieldPoss {
				field := byPos[fieldPos]
				if len(field.Path) != leastLevel {
					continue
				}
				if field.Tagged {
					numTagged++
					taggedPos = fieldPos
					if numTagged > 1 {
						break // optimization
					}
				} else {
					numUntagged++
					untaggedPos = fieldPos
				}
			}
			switch numTagged {
			case 0:
				switch numUntagged {
				case 0:
					// do nothing
				case 1:
					if curPos == untaggedPos {
						ret.byName[name] = len(ret.byPos)
						ret.byPos = append(ret.byPos, byPos[curPos])
					}
				}
			case 1:
				if curPos == taggedPos {
					ret.byName[name] = len(ret.byPos)
					ret.byPos = append(ret.byPos, byPos[curPos])
				}
			}
		}
	}

	return ret
}

func indexStructInner(typ reflect.Type, prefix []int, byPos *[]structField, byName map[string][]int, seen map[reflect.Type]struct{}) {
	if _, ok := seen[typ]; ok {
		return
	}
	seen[typ] = struct{}{}
	defer delete(seen, typ)

	n := typ.NumField()
	for i := 0; i < n; i++ {
		path := append(append([]int(nil), prefix...), i)

		fTyp := typ.Field(i)
		var embed bool
		if fTyp.Anonymous {
			t := fTyp.Type
			if t.Kind() == reflect.Pointer {
				t = t.Elem()
			}
			if !fTyp.IsExported() && t.Kind() != reflect.Struct {
				continue
			}
			embed = t.Kind() == reflect.Struct
		} else if !fTyp.IsExported() {
			continue
		}
		tag := fTyp.Tag.Get("json")
		if tag == "-" {
			continue
		}
		tagName, opts := parseTag(tag)
		name := tagName
		if !isValidTag(name) {
			name = ""
		}
		if name == "" {
			name = fTyp.Name
		}

		if embed && tagName == "" {
			t := fTyp.Type
			if t.Kind() == reflect.Pointer {
				t = t.Elem()
			}
			indexStructInner(t, path, byPos, byName, seen)
		} else {
			byName[name] = append(byName[name], len(*byPos))
			*byPos = append(*byPos, structField{
				Name:      name,
				Path:      path,
				Tagged:    tagName != "",
				OmitEmpty: opts.Contains("omitempty"),
				Quote:     opts.Contains("string") && isQuotable(fTyp.Type),
			})
		}
	}
}

func isQuotable(typ reflect.Type) bool {
	for typ.Kind() == reflect.Pointer {
		typ = typ.Elem()
	}
	switch typ.Kind() {
	case reflect.Bool,
		reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
		reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
		reflect.Uintptr,
		reflect.Float32, reflect.Float64,
		reflect.String:
		return true
	default:
		return false
	}
}