Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
kardolus
GitHub Repository: kardolus/chatgpt-cli
Path: blob/main/vendor/github.com/spf13/cast/cast.go
2875 views
1
// Copyright © 2014 Steve Francia <[email protected]>.
2
//
3
// Use of this source code is governed by an MIT-style
4
// license that can be found in the LICENSE file.
5
6
// Package cast provides easy and safe casting in Go.
7
package cast
8
9
import "time"
10
11
const errorMsg = "unable to cast %#v of type %T to %T"
12
const errorMsgWith = "unable to cast %#v of type %T to %T: %w"
13
14
// Basic is a type parameter constraint for functions accepting basic types.
15
//
16
// It represents the supported basic types this package can cast to.
17
type Basic interface {
18
string | bool | Number | time.Time | time.Duration
19
}
20
21
// ToE casts any value to a [Basic] type.
22
func ToE[T Basic](i any) (T, error) {
23
var t T
24
25
var v any
26
var err error
27
28
switch any(t).(type) {
29
case string:
30
v, err = ToStringE(i)
31
case bool:
32
v, err = ToBoolE(i)
33
case int:
34
v, err = toNumberE[int](i, parseInt[int])
35
case int8:
36
v, err = toNumberE[int8](i, parseInt[int8])
37
case int16:
38
v, err = toNumberE[int16](i, parseInt[int16])
39
case int32:
40
v, err = toNumberE[int32](i, parseInt[int32])
41
case int64:
42
v, err = toNumberE[int64](i, parseInt[int64])
43
case uint:
44
v, err = toUnsignedNumberE[uint](i, parseUint[uint])
45
case uint8:
46
v, err = toUnsignedNumberE[uint8](i, parseUint[uint8])
47
case uint16:
48
v, err = toUnsignedNumberE[uint16](i, parseUint[uint16])
49
case uint32:
50
v, err = toUnsignedNumberE[uint32](i, parseUint[uint32])
51
case uint64:
52
v, err = toUnsignedNumberE[uint64](i, parseUint[uint64])
53
case float32:
54
v, err = toNumberE[float32](i, parseFloat[float32])
55
case float64:
56
v, err = toNumberE[float64](i, parseFloat[float64])
57
case time.Time:
58
v, err = ToTimeE(i)
59
case time.Duration:
60
v, err = ToDurationE(i)
61
}
62
63
if err != nil {
64
return t, err
65
}
66
67
return v.(T), nil
68
}
69
70
// Must is a helper that wraps a call to a cast function and panics if the error is non-nil.
71
func Must[T any](i any, err error) T {
72
if err != nil {
73
panic(err)
74
}
75
76
return i.(T)
77
}
78
79
// To casts any value to a [Basic] type.
80
func To[T Basic](i any) T {
81
v, _ := ToE[T](i)
82
83
return v
84
}
85
86