File: struct.go

package info (click to toggle)
golang-github-azuread-microsoft-authentication-library-for-go 1.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 964 kB
  • sloc: makefile: 4
file content (290 lines) | stat: -rw-r--r-- 7,436 bytes parent folder | download | duplicates (7)
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

package json

import (
	"encoding/json"
	"fmt"
	"reflect"
	"strings"
)

func unmarshalStruct(jdec *json.Decoder, i interface{}) error {
	v := reflect.ValueOf(i)
	if v.Kind() != reflect.Ptr {
		return fmt.Errorf("Unmarshal() received type %T, which is not a *struct", i)
	}
	v = v.Elem()
	if v.Kind() != reflect.Struct {
		return fmt.Errorf("Unmarshal() received type %T, which is not a *struct", i)
	}

	if hasUnmarshalJSON(v) {
		// Indicates that this type has a custom Unmarshaler.
		return jdec.Decode(v.Addr().Interface())
	}

	f := v.FieldByName(addField)
	if f.Kind() == reflect.Invalid {
		return fmt.Errorf("Unmarshal(%T) only supports structs that have the field AdditionalFields or implements json.Unmarshaler", i)
	}

	if f.Kind() != reflect.Map || !f.Type().AssignableTo(mapStrInterType) {
		return fmt.Errorf("type %T has field 'AdditionalFields' that is not a map[string]interface{}", i)
	}

	dec := newDecoder(jdec, v)
	return dec.run()
}

type decoder struct {
	dec        *json.Decoder
	value      reflect.Value // This will be a reflect.Struct
	translator translateFields
	key        string
}

func newDecoder(dec *json.Decoder, value reflect.Value) *decoder {
	return &decoder{value: value, dec: dec}
}

// run runs our decoder state machine.
func (d *decoder) run() error {
	var state = d.start
	var err error
	for {
		state, err = state()
		if err != nil {
			return err
		}
		if state == nil {
			return nil
		}
	}
}

// start looks for our opening delimeter '{' and then transitions to looping through our fields.
func (d *decoder) start() (stateFn, error) {
	var err error
	d.translator, err = findFields(d.value)
	if err != nil {
		return nil, err
	}

	delim, err := d.dec.Token()
	if err != nil {
		return nil, err
	}
	if !delimIs(delim, '{') {
		return nil, fmt.Errorf("Unmarshal expected opening {, received %v", delim)
	}

	return d.next, nil
}

// next gets the next struct field name from the raw json or stops the machine if we get our closing }.
func (d *decoder) next() (stateFn, error) {
	if !d.dec.More() {
		// Remove the closing }.
		if _, err := d.dec.Token(); err != nil {
			return nil, err
		}
		return nil, nil
	}

	key, err := d.dec.Token()
	if err != nil {
		return nil, err
	}

	d.key = key.(string)
	return d.storeValue, nil
}

// storeValue takes the next value and stores it our struct. If the field can't be found
// in the struct, it pushes the operation to storeAdditional().
func (d *decoder) storeValue() (stateFn, error) {
	goName := d.translator.goName(d.key)
	if goName == "" {
		goName = d.key
	}

	// We don't have the field in the struct, so it goes in AdditionalFields.
	f := d.value.FieldByName(goName)
	if f.Kind() == reflect.Invalid {
		return d.storeAdditional, nil
	}

	// Indicates that this type has a custom Unmarshaler.
	if hasUnmarshalJSON(f) {
		err := d.dec.Decode(f.Addr().Interface())
		if err != nil {
			return nil, err
		}
		return d.next, nil
	}

	t, isPtr, err := fieldBaseType(d.value, goName)
	if err != nil {
		return nil, fmt.Errorf("type(%s) had field(%s) %w", d.value.Type().Name(), goName, err)
	}

	switch t.Kind() {
	// We need to recursively call ourselves on any *struct or struct.
	case reflect.Struct:
		if isPtr {
			if f.IsNil() {
				f.Set(reflect.New(t))
			}
		} else {
			f = f.Addr()
		}
		if err := unmarshalStruct(d.dec, f.Interface()); err != nil {
			return nil, err
		}
		return d.next, nil
	case reflect.Map:
		v := reflect.MakeMap(f.Type())
		ptr := newValue(f.Type())
		ptr.Elem().Set(v)
		if err := unmarshalMap(d.dec, ptr); err != nil {
			return nil, err
		}
		f.Set(ptr.Elem())
		return d.next, nil
	case reflect.Slice:
		v := reflect.MakeSlice(f.Type(), 0, 0)
		ptr := newValue(f.Type())
		ptr.Elem().Set(v)
		if err := unmarshalSlice(d.dec, ptr); err != nil {
			return nil, err
		}
		f.Set(ptr.Elem())
		return d.next, nil
	}

	if !isPtr {
		f = f.Addr()
	}

	// For values that are pointers, we need them to be non-nil in order
	// to decode into them.
	if f.IsNil() {
		f.Set(reflect.New(t))
	}

	if err := d.dec.Decode(f.Interface()); err != nil {
		return nil, err
	}

	return d.next, nil
}

// storeAdditional pushes the key/value into our .AdditionalFields map.
func (d *decoder) storeAdditional() (stateFn, error) {
	rw := json.RawMessage{}
	if err := d.dec.Decode(&rw); err != nil {
		return nil, err
	}
	field := d.value.FieldByName(addField)
	if field.IsNil() {
		field.Set(reflect.MakeMap(field.Type()))
	}
	field.SetMapIndex(reflect.ValueOf(d.key), reflect.ValueOf(rw))
	return d.next, nil
}

func fieldBaseType(v reflect.Value, fieldName string) (t reflect.Type, isPtr bool, err error) {
	sf, ok := v.Type().FieldByName(fieldName)
	if !ok {
		return nil, false, fmt.Errorf("bug: fieldBaseType() lookup of field(%s) on type(%s): do not have field", fieldName, v.Type().Name())
	}
	t = sf.Type
	if t.Kind() == reflect.Ptr {
		t = t.Elem()
		isPtr = true
	}
	if t.Kind() == reflect.Ptr {
		return nil, isPtr, fmt.Errorf("received pointer to pointer type, not supported")
	}
	return t, isPtr, nil
}

type translateField struct {
	jsonName string
	goName   string
}

// translateFields is a list of translateFields with a handy lookup method.
type translateFields []translateField

// goName loops through a list of fields looking for one contaning the jsonName and
// returning the goName. If not found, returns the empty string.
// Note: not a map because at this size slices are faster even in tight loops.
func (t translateFields) goName(jsonName string) string {
	for _, entry := range t {
		if entry.jsonName == jsonName {
			return entry.goName
		}
	}
	return ""
}

// jsonName loops through a list of fields looking for one contaning the goName and
// returning the jsonName. If not found, returns the empty string.
// Note: not a map because at this size slices are faster even in tight loops.
func (t translateFields) jsonName(goName string) string {
	for _, entry := range t {
		if entry.goName == goName {
			return entry.jsonName
		}
	}
	return ""
}

var umarshalerType = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()

// findFields parses a struct and writes the field tags for lookup. It will return an error
// if any field has a type of *struct or struct that does not implement json.Marshaler.
func findFields(v reflect.Value) (translateFields, error) {
	if v.Kind() == reflect.Ptr {
		v = v.Elem()
	}
	if v.Kind() != reflect.Struct {
		return nil, fmt.Errorf("findFields received a %s type, expected *struct or struct", v.Type().Name())
	}
	tfs := make([]translateField, 0, v.NumField())
	for i := 0; i < v.NumField(); i++ {
		tf := translateField{
			goName:   v.Type().Field(i).Name,
			jsonName: parseTag(v.Type().Field(i).Tag.Get("json")),
		}
		switch tf.jsonName {
		case "", "-":
			tf.jsonName = tf.goName
		}
		tfs = append(tfs, tf)

		f := v.Field(i)
		if f.Kind() == reflect.Ptr {
			f = f.Elem()
		}
		if f.Kind() == reflect.Struct {
			if f.Type().Implements(umarshalerType) {
				return nil, fmt.Errorf("struct type %q which has field %q which "+
					"doesn't implement json.Unmarshaler", v.Type().Name(), v.Type().Field(i).Name)
			}
		}
	}
	return tfs, nil
}

// parseTag just returns the first entry in the tag. tag is the string
// returned by reflect.StructField.Tag().Get().
func parseTag(tag string) string {
	if idx := strings.Index(tag, ","); idx != -1 {
		return tag[:idx]
	}
	return tag
}