-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgconv_int.go
137 lines (129 loc) · 2.39 KB
/
gconv_int.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gconv
import (
"math"
"strconv"
"github.com/gogf/gf/v2/encoding/gbinary"
"github.com/gogf/gf/v2/util/gconv/internal/localinterface"
)
// Int converts `any` to int.
func Int(any interface{}) int {
if any == nil {
return 0
}
if v, ok := any.(int); ok {
return v
}
return int(Int64(any))
}
// Int8 converts `any` to int8.
func Int8(any interface{}) int8 {
if any == nil {
return 0
}
if v, ok := any.(int8); ok {
return v
}
return int8(Int64(any))
}
// Int16 converts `any` to int16.
func Int16(any interface{}) int16 {
if any == nil {
return 0
}
if v, ok := any.(int16); ok {
return v
}
return int16(Int64(any))
}
// Int32 converts `any` to int32.
func Int32(any interface{}) int32 {
if any == nil {
return 0
}
if v, ok := any.(int32); ok {
return v
}
return int32(Int64(any))
}
// Int64 converts `any` to int64.
func Int64(any interface{}) int64 {
if any == nil {
return 0
}
switch value := any.(type) {
case int:
return int64(value)
case int8:
return int64(value)
case int16:
return int64(value)
case int32:
return int64(value)
case int64:
return value
case uint:
return int64(value)
case uint8:
return int64(value)
case uint16:
return int64(value)
case uint32:
return int64(value)
case uint64:
return int64(value)
case float32:
return int64(value)
case float64:
return int64(value)
case bool:
if value {
return 1
}
return 0
case []byte:
return gbinary.DecodeToInt64(value)
default:
if f, ok := value.(localinterface.IInt64); ok {
return f.Int64()
}
var (
s = String(value)
isMinus = false
)
if len(s) > 0 {
if s[0] == '-' {
isMinus = true
s = s[1:]
} else if s[0] == '+' {
s = s[1:]
}
}
// Hexadecimal
if len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X') {
if v, e := strconv.ParseInt(s[2:], 16, 64); e == nil {
if isMinus {
return -v
}
return v
}
}
// Decimal
if v, e := strconv.ParseInt(s, 10, 64); e == nil {
if isMinus {
return -v
}
return v
}
// Float64
if valueInt64 := Float64(value); math.IsNaN(valueInt64) {
return 0
} else {
return int64(valueInt64)
}
}
}