-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
79 lines (70 loc) · 1.93 KB
/
common.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
package oxygen
import (
"errors"
"fmt"
"reflect"
)
var (
errExist = errors.New("exist")
ErrNotSupportType = errors.New("cannot support type")
ErrNilInterface = errors.New("interface is nil")
ErrPointerToUnexported = errors.New("cannot set embedded pointer to unexported struct")
ErrInvalidFormat = errors.New("the raw data has an invalid format for an object value")
)
func bitSize(v reflect.Kind) int {
switch v {
case reflect.Int8, reflect.Uint8:
return 8
case reflect.Int16, reflect.Uint16:
return 16
case reflect.Int32, reflect.Uint32, reflect.Float32:
return 32
case reflect.Int64, reflect.Uint64, reflect.Float64:
return 64
case reflect.Int, reflect.Uint, reflect.Uintptr:
return 32 << (^uint(0) >> 63)
default:
return 0
}
}
func isEmptyValue(v reflect.Value) bool {
switch v.Kind() {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
reflect.Float32, reflect.Float64:
return v.IsZero()
case reflect.Interface, reflect.Pointer:
return v.IsNil()
default:
return !v.IsValid()
}
}
type context[T any] struct {
structName string
field *field[T]
err error
}
func (c *context[T]) setError(tagName, state string, err error) {
err = unwrapErr(err)
if c.structName == "" {
c.err = fmt.Errorf("%s: cannot %s Go value of type %s: %w", tagName, state, c.field.typ, err)
} else {
c.err = fmt.Errorf("%s: cannot %s Go struct field %s.%s of type %s: %w", tagName, state, c.structName, c.field.name, c.field.typ, err)
}
}
func unwrapErr(err error) error {
if ew := errors.Unwrap(err); ew != nil {
return ew
}
return err
}
func unPoint(t reflect.Type) reflect.Type {
if t.Kind() != reflect.Pointer {
return t
}
return unPoint(t.Elem())
}