-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbuildin.go
90 lines (78 loc) · 2.17 KB
/
buildin.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
package govalidator
import (
"context"
"fmt"
"github.com/viant/xunsafe"
"reflect"
"unsafe"
)
type Zeroable interface {
IsZero() bool
}
func checkRequiredPtr(ctx context.Context, value interface{}) (bool, error) {
ptr := xunsafe.AsPointer(value)
if ptr == nil || (*unsafe.Pointer)(ptr) == nil {
return false, nil
}
return true, nil
}
func checkRequiredString(ctx context.Context, value interface{}) (bool, error) {
text, _ := value.(string)
return text != "", nil
}
func checkRequiredSlice(ctx context.Context, value interface{}) (bool, error) {
if value == nil {
return false, nil
}
ptr := xunsafe.AsPointer(value)
header := (*reflect.SliceHeader)(ptr)
return header.Len > 0, nil
}
func checkRequiredNoZeroStruct(ctx context.Context, value interface{}) (bool, error) {
zeroer, ok := value.(Zeroable)
if !ok {
return false, fmt.Errorf("expected: %T, but had: %T", zeroer, value)
}
return !zeroer.IsZero(), nil
}
func newRequiredCheck(field *Field, check *Check) (IsValid, error) {
switch field.Kind() {
case reflect.Ptr:
return checkRequiredPtr, nil
case reflect.Struct:
_, ok := field.Type.MethodByName("IsZero")
if !ok {
return nil, fmt.Errorf("struct does not implement IsZero for required check: %v", field.Type.String())
}
return checkRequiredNoZeroStruct, nil
case reflect.String:
return checkRequiredString, nil
case reflect.Int:
return checkRequiredInt, nil
case reflect.Bool:
return checkRequiredBool, nil
case reflect.Float64:
return checkRequiredFloat64, nil
case reflect.Slice:
return checkRequiredSlice, nil
}
return nil, fmt.Errorf("required unsupported type: %v %v", field.Name, field.Type.String())
}
func checkRequiredInt(ctx context.Context, value interface{}) (bool, error) {
intValue, _ := value.(int)
return intValue != 0, nil
}
var boolType = reflect.TypeOf(true)
func checkRequiredBool(ctx context.Context, value interface{}) (bool, error) {
switch actual := value.(type) {
case bool:
return actual, nil
default:
ret := reflect.ValueOf(value).Bool()
return ret, nil
}
}
func checkRequiredFloat64(ctx context.Context, value interface{}) (bool, error) {
intValue, _ := value.(float64)
return intValue != 0, nil
}