-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathuint64.go
110 lines (103 loc) · 2.14 KB
/
uint64.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package cast
// Uint64 will return an int64 when `v` is of type uint64, uint32, uint16, uint8, uint or has a method:
//
// type interface {
// Uint64() (uint64, error)
// }
//
// ... that returns successfully, or has a method:
//
// type interface {
// Uint32() (uint32, error)
// }
//
// ... that returns successfully, or has a method:
//
// type interface {
// Uint16() (uint16, error)
// }
//
// ... that returns successfully, or has a method:
//
// type interface {
// Uint8() (uint8, error)
// }
//
// ... that returns successfully, or has a method:
//
// type interface {
// Uint() (uint, error)
// }
//
// ... that returns successfully.
//
// Else it will return an error.
func Uint64(v any) (uint64, error) {
switch value := v.(type) {
case uint64er:
return value.Uint64()
case uint32er:
return func()(uint64, error){
casted, err := value.Uint32()
if nil != err {
return 0, err
}
return uint64(casted), nil
}()
case uint16er:
return func()(uint64, error){
casted, err := value.Uint16()
if nil != err {
return 0, err
}
return uint64(casted), nil
}()
case uint8er:
return func()(uint64, error){
casted, err := value.Uint8()
if nil != err {
return 0, err
}
return uint64(casted), nil
}()
case uinter:
return func()(uint64, error) {
casted, err := value.Uint()
if nil != err {
return 0, err
}
return uint64(casted), nil
}()
case uint64:
return uint64(value), nil
case uint32:
return uint64(value), nil
case uint16:
return uint64(value), nil
case uint8:
return uint64(value), nil
case uint:
return uint64(value), nil
default:
return 0, internalCannotCastComplainer{expectedType:"uint64", actualType:typeof(value)}
}
}
// Uint64Else is similar to [Uint64] except that if a cast cannot be done, it returns the `alternative`.
func Uint64Else(v any, alternative uint64) uint64 {
result, err := Uint64(v)
if nil != err {
return alternative
}
return result
}
// MustUint64 is like Uint64, expect panic()s on an error.
func MustUint64(v any) uint64 {
x, err := Uint64(v)
if nil != err {
panic(err)
}
return x
}
type uint64er interface {
Uint64() (uint64, error)
}