-
-
Notifications
You must be signed in to change notification settings - Fork 299
/
int.go
130 lines (96 loc) · 1.7 KB
/
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
package values
import (
"encoding/binary"
"encoding/json"
"hash/fnv"
"strconv"
"github.com/MontFerret/ferret/pkg/runtime/core"
)
type Int int
var ZeroInt = Int(0)
func NewInt(input int) Int {
return Int(input)
}
func ParseInt(input interface{}) (Int, error) {
if core.IsNil(input) {
return ZeroInt, nil
}
i, ok := input.(int)
if ok {
if i == 0 {
return ZeroInt, nil
}
return Int(i), nil
}
// try to cast
str, ok := input.(string)
if ok {
i, err := strconv.Atoi(str)
if err == nil {
if i == 0 {
return ZeroInt, nil
}
return Int(i), nil
}
}
return ZeroInt, core.Error(core.ErrInvalidType, "expected 'int'")
}
func ParseIntP(input interface{}) Int {
res, err := ParseInt(input)
if err != nil {
panic(err)
}
return res
}
func (t Int) MarshalJSON() ([]byte, error) {
return json.Marshal(int(t))
}
func (t Int) Type() core.Type {
return core.IntType
}
func (t Int) String() string {
return strconv.Itoa(int(t))
}
func (t Int) Compare(other core.Value) int {
raw := int(t)
switch other.Type() {
case core.IntType:
i := other.Unwrap().(int)
if raw == i {
return 0
}
if raw < i {
return -1
}
return +1
case core.FloatType:
f := other.Unwrap().(float64)
i := int(f)
if raw == i {
return 0
}
if raw < i {
return -1
}
return +1
case core.BooleanType, core.NoneType:
return 1
default:
return -1
}
}
func (t Int) Unwrap() interface{} {
return int(t)
}
func (t Int) Hash() uint64 {
h := fnv.New64a()
h.Write([]byte(t.Type().String()))
h.Write([]byte(":"))
bytes := make([]byte, 8)
binary.LittleEndian.PutUint64(bytes, uint64(t))
h.Write(bytes)
return h.Sum64()
}
func (t Int) Copy() core.Value {
return t
}