-
Notifications
You must be signed in to change notification settings - Fork 9
/
reflect_helper.go
282 lines (267 loc) · 7.55 KB
/
reflect_helper.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
// Copyright 2021 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"errors"
"reflect"
"strconv"
"strings"
)
var DeprecatedTags = map[string]string{
"enable-streaming": "EnableStreaming",
}
func ValueToInt(value reflect.Value) int64 {
switch value.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return value.Int()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return int64(value.Uint())
default:
return 0
}
}
func ValueToFloat(value reflect.Value) float64 {
if value.Kind() == reflect.Float32 || value.Kind() == reflect.Float64 {
return value.Float()
}
return 0
}
func ValueToBool(value reflect.Value) bool {
if value.Kind() == reflect.Bool {
return value.Bool()
}
return false
}
// ValueToString return the parsed string value for other type
func ValueToString(value reflect.Value) string {
switch value.Kind() {
case reflect.String:
return value.String()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return strconv.FormatInt(value.Int(), 10)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return strconv.FormatUint(value.Uint(), 10)
case reflect.Float32, reflect.Float64:
return strconv.FormatFloat(value.Float(), 'f', -1, 64)
case reflect.Array, reflect.Slice:
elems := make([]string, value.Len())
for i := 0; i < value.Len(); i++ {
elems[i] = ValueToString(value.Index(i))
}
return strings.Join(elems, ",")
}
return value.String()
}
// FlatMap iterate all map element with the given tagPath, return a slice contain all visited elements.
// the given value should be a map type.
func FlatMap(value reflect.Value, tagPath string) reflect.Value {
if value.Kind() != reflect.Map {
return reflect.ValueOf(nil)
}
if value.Len() == 0 {
return reflect.ValueOf(nil)
}
mIter := value.MapRange()
if len(tagPath) == 0 {
result := reflect.MakeSlice(reflect.SliceOf(value.Type().Elem()), 0, value.Len())
for mIter.Next() {
result = reflect.Append(result, mIter.Value())
}
return result
}
tags := strings.Split(tagPath, ".")
elem := VisitByTagPath(value.MapIndex(value.MapKeys()[0]), tags, 0)
result := reflect.MakeSlice(reflect.SliceOf(elem.Type()), 0, value.Len())
for mIter.Next() {
result = reflect.Append(result, VisitByTagPath(mIter.Value(), tags, 0))
}
return result
}
func Len(value reflect.Value) int {
if !value.IsValid() {
return 0
}
switch value.Kind() {
case reflect.Array, reflect.Slice, reflect.Map, reflect.String:
return value.Len()
}
return 0
}
func ElemInRange(value reflect.Value, l int64, h int64) bool {
if value.Kind() != reflect.Slice {
return false
}
switch value.Type().Elem().Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
for i := 0; i < value.Len(); i++ {
if value.Index(i).Int() < l || value.Index(i).Int() > h {
return false
}
}
return true
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
for i := 0; i < value.Len(); i++ {
num := int64(value.Index(i).Uint())
if num < l || num > h {
return false
}
}
return true
case reflect.Float32, reflect.Float64:
for i := 0; i < value.Len(); i++ {
num := value.Index(i).Float()
if num < float64(l) || num > float64(h) {
return false
}
}
return true
}
return false
}
func VisitByTagPath(node reflect.Value, tags []string, idx int) reflect.Value {
if node.Interface() == nil {
return reflect.ValueOf(nil)
}
value := node
if value.Type().Kind() == reflect.Ptr {
value = value.Elem()
}
valueType := value.Type()
isLast := idx == len(tags)-1
switch valueType.Kind() {
case reflect.Struct:
// check embedded field case first
if valueType.NumField() == 1 && valueType.Field(0).Anonymous {
return VisitByTagPath(value.Field(0), tags, idx)
}
// TODO:
filedName, deprecated := DeprecatedTags[tags[idx]]
if deprecated {
field := value.FieldByName(filedName)
if isLast {
return field
}
return VisitByTagPath(field, tags, idx+1)
}
if isLast {
for i := 0; i < valueType.NumField(); i++ {
if jsonTagMatch(valueType.Field(i).Tag.Get("json"), tags[idx]) && value.Field(i).CanInterface() {
return value.Field(i)
}
}
} else {
for i := 0; i < valueType.NumField(); i++ {
if jsonTagMatch(valueType.Field(i).Tag.Get("json"), tags[idx]) {
return VisitByTagPath(value.Field(i), tags, idx+1)
}
}
}
case reflect.Slice, reflect.Array:
idx, err := parseIdx(tags[idx])
if err != nil {
return reflect.ValueOf(nil)
}
// panic if idx out of range
if isLast {
return value.Index(idx)
}
return VisitByTagPath(value.Index(idx), tags, idx+1)
case reflect.Map:
keyType := valueType.Key()
switch keyType.Kind() {
case reflect.String:
elemValue := value.MapIndex(reflect.ValueOf(tags[idx]))
if isLast {
return elemValue
}
return VisitByTagPath(elemValue, tags, idx+1)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
k, err := strconv.Atoi(tags[idx])
if err != nil {
return reflect.ValueOf(nil)
}
if isLast {
return value.MapIndex(reflect.ValueOf(k))
}
return VisitByTagPath(value.MapIndex(reflect.ValueOf(k)), tags, idx+1)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
k, err := strconv.ParseUint(tags[idx], 10, 64)
if err != nil {
return reflect.ValueOf(nil)
}
if isLast {
return value.MapIndex(reflect.ValueOf(k))
}
return VisitByTagPath(value.MapIndex(reflect.ValueOf(k)), tags, idx+1)
case reflect.Float64, reflect.Float32:
k, err := strconv.ParseFloat(tags[idx], 10)
if err != nil {
return reflect.ValueOf(nil)
}
if isLast {
return value.MapIndex(reflect.ValueOf(k))
}
return VisitByTagPath(value.MapIndex(reflect.ValueOf(k)), tags, idx+1)
default:
// not support return nil
return reflect.ValueOf(nil)
}
}
return reflect.ValueOf(nil) // which means not found any value match the given tag path
}
// @1 -> 1, @2 -> 2
func parseIdx(s string) (int, error) {
if strings.HasPrefix(s, "@") {
return 0, errors.New("index format error")
}
idxStr := strings.TrimPrefix(s, "@")
return strconv.Atoi(idxStr)
}
func jsonTagMatch(tag string, target string) bool {
if tag == target {
return true
}
if strings.TrimSuffix(tag, ",string") == target {
return true
}
if strings.TrimSuffix(tag, ",omitempty") == target {
return true
}
if strings.TrimSuffix(tag, ",string,omitempty") == target {
return true
}
return false
}
func RecursiveSetBoolValue(reflectV reflect.Value, value bool) {
if reflectV.CanSet() && reflectV.Kind() != reflect.Struct {
reflectV.SetBool(value)
}
if reflectV.Kind() == reflect.Struct {
for i := 0; i < reflectV.NumField(); i++ {
RecursiveSetBoolValue(reflectV.Field(i), value)
}
}
}
func RecursiveIfBoolValueExist(reflectV reflect.Value, value bool) bool {
switch reflectV.Kind() {
case reflect.Bool:
return reflectV.Bool() == value
case reflect.Struct:
for i := 0; i < reflectV.NumField(); i++ {
if RecursiveIfBoolValueExist(reflectV.Field(i), value) {
return true
}
}
}
return false
}