-
Notifications
You must be signed in to change notification settings - Fork 0
/
keys_tree.go
349 lines (326 loc) · 9.1 KB
/
keys_tree.go
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
/*
Licensed under the MIT License <http://opensource.org/licenses/MIT>.
Copyright © 2023-2024 Seagate Technology LLC and/or its Affiliates
Copyright © 2020-2024 Microsoft Corporation. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
*/
package config
import (
"fmt"
"reflect"
"strconv"
"strings"
)
const STRUCT_TAG = "config"
type TreeNode struct {
children map[string]*TreeNode
value interface{}
name string
}
type Tree struct {
head *TreeNode
}
// NewTree returns a new Tree object with the head initialized to a default root TreeNode
func NewTree() *Tree {
return &Tree{
head: NewTreeNode("root"),
}
}
// NewTreeNode returns a TreeNode initialized with the passed in string as name
func NewTreeNode(name string) *TreeNode {
return &TreeNode{
children: make(map[string]*TreeNode),
name: name,
}
}
// Insert function is used to insert a new object into the tree
// The key is specified as a dot separated hierarchical value
// For eg. root.child1.child2
func (tree *Tree) Insert(key string, value interface{}) {
subKeys := strings.Split(key, ".")
curNode := tree.head
for _, idx := range subKeys {
if subStruct, ok := curNode.children[idx]; ok {
if subStruct != nil {
curNode = subStruct
} else {
break
}
} else {
curNode.children[idx] = NewTreeNode(idx)
curNode = curNode.children[idx]
}
}
curNode.value = value
}
// Print is a utility function that prints the Tree in a level order fashion
func (tree *Tree) Print() {
nodes := make([]*TreeNode, 0)
nodes = append(nodes, tree.head)
for len(nodes) > 0 {
curNode := nodes[0]
nodes = nodes[1:]
for key, node := range curNode.children {
fmt.Print(key, ",")
nodes = append(nodes, node)
}
}
}
// GetSubTree returns the sub Tree that is present from the last child of the key passed in.
// For eg. to retrieve the subtree starting from child2 the passed key can be root.child1.child2
func (tree *Tree) GetSubTree(key string) *TreeNode {
subKeys := strings.Split(key, ".")
curNode := tree.head
for _, idx := range subKeys {
if curNode == nil {
return nil
}
curNode = curNode.children[idx]
}
return curNode
}
// parseValue is a utility function that accepts a val and returns the parsed value of that type.
func parseValue(val string, toType reflect.Kind) interface{} {
switch toType {
case reflect.Bool:
parsed, err := strconv.ParseBool(val)
if err != nil {
return nil
}
return parsed
case reflect.Int:
parsed, err := strconv.ParseInt(val, 0, 0)
if err != nil {
return nil
}
return int(parsed)
case reflect.Int8:
parsed, err := strconv.ParseInt(val, 0, 8)
if err != nil {
return nil
}
return int8(parsed)
case reflect.Int16:
parsed, err := strconv.ParseInt(val, 0, 16)
if err != nil {
return nil
}
return int16(parsed)
case reflect.Int32:
parsed, err := strconv.ParseInt(val, 0, 32)
if err != nil {
return nil
}
return int32(parsed)
case reflect.Int64:
parsed, err := strconv.ParseInt(val, 0, 64)
if err != nil {
return nil
}
return int64(parsed)
case reflect.Uint:
parsed, err := strconv.ParseUint(val, 0, 0)
if err != nil {
return nil
}
return uint(parsed)
case reflect.Uint8:
parsed, err := strconv.ParseUint(val, 0, 8)
if err != nil {
return nil
}
return uint8(parsed)
case reflect.Uint16:
parsed, err := strconv.ParseUint(val, 0, 16)
if err != nil {
return nil
}
return uint16(parsed)
case reflect.Uint32:
parsed, err := strconv.ParseUint(val, 0, 32)
if err != nil {
return nil
}
return uint32(parsed)
case reflect.Uint64:
parsed, err := strconv.ParseUint(val, 0, 64)
if err != nil {
return nil
}
return uint64(parsed)
case reflect.Float32:
parsed, err := strconv.ParseFloat(val, 32)
if err != nil {
return nil
}
return float32(parsed)
case reflect.Float64:
parsed, err := strconv.ParseFloat(val, 64)
if err != nil {
return nil
}
return float64(parsed)
case reflect.Complex64:
parsed, err := strconv.ParseComplex(val, 64)
if err != nil {
return nil
}
return complex64(parsed)
case reflect.Complex128:
parsed, err := strconv.ParseComplex(val, 128)
if err != nil {
return nil
}
return complex128(parsed)
case reflect.String:
return val
default:
return nil
}
}
// MergeWithKey is used to merge the contained tree with the object (obj) that is passed in as parameter.
// getValue parameter is a function that accepts the value stored in a TreeNode and performs any business logic and returns the value that has to be placed in the obj parameter
// it must also return true|false based on which the value will be set in the obj parameter.
func (tree *Tree) MergeWithKey(key string, obj interface{}, getValue func(val interface{}) (res interface{}, ok bool)) {
subTree := tree.GetSubTree(key)
if subTree == nil {
return
}
var elem = reflect.Indirect(reflect.ValueOf(obj))
if obj == nil {
return
}
if elem.Type().Kind() == reflect.Struct {
for i := 0; i < elem.NumField(); i++ {
idx := getIdxFromField(elem.Type().Field(i))
if _, ok := subTree.children[idx]; ok {
if elem.Field(i).Type().Kind() == reflect.Struct {
subKey := key + "." + idx
tree.MergeWithKey(subKey, elem.Field(i).Addr().Interface(), getValue)
} else if elem.Field(i).Type().Kind() == reflect.Ptr {
subKey := key + "." + idx
tree.MergeWithKey(subKey, elem.Field(i).Elem().Addr().Interface(), getValue)
} else {
val, ok := getValue(subTree.children[idx].value)
if ok {
assignToField(elem.Field(i), val)
}
}
}
}
} else if isPrimitiveType(elem.Type().Kind()) {
val, ok := getValue(subTree.value)
if ok {
assignToField(elem, val)
}
}
}
// Merge performs the same function as MergeWithKey but at the root level
func (tree *Tree) Merge(obj interface{}, getValue func(val interface{}) (res interface{}, ok bool)) {
subTree := tree.head
if subTree == nil {
return
}
var elem = reflect.Indirect(reflect.ValueOf(obj))
if obj == nil {
return
}
if elem.Type().Kind() == reflect.Struct {
for i := 0; i < elem.NumField(); i++ {
idx := getIdxFromField(elem.Type().Field(i))
if _, ok := subTree.children[idx]; ok {
if elem.Field(i).Type().Kind() == reflect.Struct {
subKey := idx
tree.MergeWithKey(subKey, elem.Field(i).Addr().Interface(), getValue)
} else if elem.Field(i).Type().Kind() == reflect.Ptr {
subKey := idx
tree.MergeWithKey(subKey, elem.Field(i).Elem().Addr().Interface(), getValue)
} else {
val, ok := getValue(subTree.children[idx].value)
if ok {
assignToField(elem.Field(i), val)
}
}
}
}
} else if isPrimitiveType(elem.Type().Kind()) {
val, ok := getValue(subTree.value)
if ok {
assignToField(elem, val)
}
}
}
// isPrimitiveType is a utility function that returns true if the kind parameter is a primitive data type or not
func isPrimitiveType(kind reflect.Kind) bool {
switch kind {
case reflect.Bool:
return true
case reflect.Int:
return true
case reflect.Int8:
return true
case reflect.Int16:
return true
case reflect.Int32:
return true
case reflect.Int64:
return true
case reflect.Uint:
return true
case reflect.Uint8:
return true
case reflect.Uint16:
return true
case reflect.Uint32:
return true
case reflect.Uint64:
return true
case reflect.Float32:
return true
case reflect.Float64:
return true
case reflect.Complex64:
return true
case reflect.Complex128:
return true
case reflect.String:
return true
default:
return false
}
}
// assignToField is utility function to set the val to the passed field based on it's state
func assignToField(field reflect.Value, val interface{}) {
if field.CanSet() {
if reflect.TypeOf(val).Kind() == reflect.String {
parseVal := parseValue(val.(string), field.Kind())
if parseVal != nil {
field.Set(reflect.ValueOf(parseVal))
}
} else {
field.Set(reflect.ValueOf(val))
}
}
}
// getIdxFromField is a utility function that returns the key to index into the map based on struct tags.
func getIdxFromField(structField reflect.StructField) string {
idx := structField.Tag.Get(STRUCT_TAG)
if idx == "" {
idx = strings.ToLower(structField.Name)
}
return idx
}