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
|
// Copyright © 2014 Steve Francia <spf@spf13.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package cast
import (
"encoding/json"
"fmt"
"html/template"
"strconv"
"time"
)
// ToBoolE casts any value to a bool type.
func ToBoolE(i any) (bool, error) {
i, _ = indirect(i)
switch b := i.(type) {
case bool:
return b, nil
case nil:
return false, nil
case int:
return b != 0, nil
case int8:
return b != 0, nil
case int16:
return b != 0, nil
case int32:
return b != 0, nil
case int64:
return b != 0, nil
case uint:
return b != 0, nil
case uint8:
return b != 0, nil
case uint16:
return b != 0, nil
case uint32:
return b != 0, nil
case uint64:
return b != 0, nil
case float32:
return b != 0, nil
case float64:
return b != 0, nil
case time.Duration:
return b != 0, nil
case string:
return strconv.ParseBool(b)
case json.Number:
v, err := ToInt64E(b)
if err == nil {
return v != 0, nil
}
return false, fmt.Errorf(errorMsg, i, i, false)
default:
if i, ok := resolveAlias(i); ok {
return ToBoolE(i)
}
return false, fmt.Errorf(errorMsg, i, i, false)
}
}
// ToStringE casts any value to a string type.
func ToStringE(i any) (string, error) {
switch s := i.(type) {
case string:
return s, nil
case bool:
return strconv.FormatBool(s), nil
case float64:
return strconv.FormatFloat(s, 'f', -1, 64), nil
case float32:
return strconv.FormatFloat(float64(s), 'f', -1, 32), nil
case int:
return strconv.Itoa(s), nil
case int8:
return strconv.FormatInt(int64(s), 10), nil
case int16:
return strconv.FormatInt(int64(s), 10), nil
case int32:
return strconv.FormatInt(int64(s), 10), nil
case int64:
return strconv.FormatInt(s, 10), nil
case uint:
return strconv.FormatUint(uint64(s), 10), nil
case uint8:
return strconv.FormatUint(uint64(s), 10), nil
case uint16:
return strconv.FormatUint(uint64(s), 10), nil
case uint32:
return strconv.FormatUint(uint64(s), 10), nil
case uint64:
return strconv.FormatUint(s, 10), nil
case json.Number:
return s.String(), nil
case []byte:
return string(s), nil
case template.HTML:
return string(s), nil
case template.URL:
return string(s), nil
case template.JS:
return string(s), nil
case template.CSS:
return string(s), nil
case template.HTMLAttr:
return string(s), nil
case nil:
return "", nil
case fmt.Stringer:
return s.String(), nil
case error:
return s.Error(), nil
default:
if i, ok := indirect(i); ok {
return ToStringE(i)
}
if i, ok := resolveAlias(i); ok {
return ToStringE(i)
}
return "", fmt.Errorf(errorMsg, i, i, "")
}
}
|