-
Notifications
You must be signed in to change notification settings - Fork 0
/
cast_bool.go
70 lines (60 loc) · 1.27 KB
/
cast_bool.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
package pick
import (
"encoding/json"
"strconv"
)
func (c DefaultCaster) AsBool(input any) (bool, error) {
switch origin := input.(type) {
case int:
return origin != 0, nil
case int8:
return origin != 0, nil
case int16:
return origin != 0, nil
case int32:
return origin != 0, nil
case int64:
return origin != 0, nil
case uint:
return origin != 0, nil
case uint8:
return origin != 0, nil
case uint16:
return origin != 0, nil
case uint32:
return origin != 0, nil
case uint64:
return origin != 0, nil
case float32:
return origin != 0, nil
case float64:
return origin != 0, nil
case string:
b, err := strconv.ParseBool(origin)
if err != nil {
return false, newCastError(err, input)
}
return b, nil
case json.Number:
n, err := origin.Float64()
if err != nil {
return false, newCastError(err, input)
}
return c.AsBool(n)
case []byte:
return c.AsBool(string(origin))
case bool:
return origin, nil
case nil:
return false, nil
default:
// try to cast to basic (in case input is ~basic)
if basic, err := tryCastToBasicType(input); err == nil {
return c.AsBool(basic)
}
return tryReflectConvert[bool](input)
}
}
func (c DefaultCaster) AsBoolSlice(input any) ([]bool, error) {
return mapTo(input, mapOpFn(c.AsBool))
}