-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.go
116 lines (111 loc) · 2.14 KB
/
utils.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
package gocast
import (
"database/sql/driver"
"reflect"
)
// IsEmpty checks value for empty state
func IsEmpty[T any](v T) bool {
switch tv := any(v).(type) {
case nil:
return true
case bool:
return !tv
case int:
return tv == 0
case int8:
return tv == 0
case int16:
return tv == 0
case int32:
return tv == 0
case int64:
return tv == 0
case uint:
return tv == 0
case uint8:
return tv == 0
case uint16:
return tv == 0
case uint32:
return tv == 0
case uint64:
return tv == 0
case float32:
return tv == 0
case float64:
return tv == 0
case string:
return tv == ""
case []int:
return len(tv) == 0
case []int8:
return len(tv) == 0
case []int16:
return len(tv) == 0
case []int32:
return len(tv) == 0
case []int64:
return len(tv) == 0
case []uint:
return len(tv) == 0
case []uint8:
return len(tv) == 0
case []uint16:
return len(tv) == 0
case []uint32:
return len(tv) == 0
case []uint64:
return len(tv) == 0
case []float32:
return len(tv) == 0
case []float64:
return len(tv) == 0
case []any:
return len(tv) == 0
case []bool:
return len(tv) == 0
case []string:
return len(tv) == 0
}
return IsEmptyByReflection(reflect.ValueOf(v))
}
// IsEmptyByReflection value
func IsEmptyByReflection(v reflect.Value) bool {
if !v.IsValid() {
return true
}
switch v.Kind() {
case reflect.Interface, reflect.Ptr:
if v.IsNil() {
return true
}
return IsEmptyByReflection(v.Elem())
case reflect.Bool:
return !v.Bool()
case reflect.Slice, reflect.Array, reflect.Map, reflect.String:
return v.Len() == 0
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
}
return false
}
func getValue(v any) any {
if v == nil {
return nil
}
if vl, ok := v.(driver.Valuer); ok {
v, _ = vl.Value()
}
return v
}
func reflectTarget(r reflect.Value) reflect.Value {
for kind := r.Kind(); kind == reflect.Ptr || kind == reflect.Interface; {
r = r.Elem()
kind = r.Kind()
}
return r
}