This repository has been archived by the owner on Aug 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 27
/
int.go
110 lines (98 loc) · 2.07 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
// Copyright 2017-2018 The qitmeer developers
package types
import (
"github.com/Qitmeer/qitmeer/common/util"
"math/big"
//"fmt"
"fmt"
"strings"
)
type Bytes []byte
type Uint uint
type UInt64 uint64
type UInt128 big.Int
type UInt256 big.Int
func parseUInt64(s string) (UInt64, bool) {
var u64 UInt64
if i, ok := parseBigInt(s, 64); ok {
u64 = UInt64(i.Uint64())
return u64, true
}
return u64, false
}
func parseUInt128(s string) (UInt128, bool) {
var u128 UInt128
if i, ok := parseBigInt(s, 128); ok {
u128 = UInt128(*i)
return u128, true
}
return u128, false
}
func parseUInt256(s string) (UInt256, bool) {
var u256 UInt256
if i, ok := parseBigInt(s, 256); ok {
u256 = UInt256(*i)
return u256, true
}
return u256, false
}
func parseBigInt(s string, size int) (i *big.Int, ok bool) {
if s == "" {
return new(big.Int), true
}
i, ok = nil, false
if util.HasHexPrefix(s) {
i, ok = new(big.Int).SetString(s[2:], 16)
} else {
i, ok = new(big.Int).SetString(s, 10)
}
if ok && i.BitLen() > 256 {
i, ok = nil, false
}
return
}
func (i *UInt256) MarshalJSON() ([]byte, error) {
if i == nil {
return []byte("0x0"), nil
}
return []byte(fmt.Sprintf(`"%#x"`, (*big.Int)(i))), nil
}
func (i *UInt64) UnmarshalJSON(input []byte) error {
s := strings.Trim(string(input), "\"")
int64, ok := parseUInt64(s)
if !ok {
return fmt.Errorf("invalid hex or decimal integer %q ", input)
}
*i = int64
return nil
}
func (i *UInt128) UnmarshalJSON(input []byte) error {
s := strings.Trim(string(input), "\"")
u128, ok := parseUInt128(s)
if !ok {
return fmt.Errorf("invalid hex or decimal integer %q", input)
}
*i = u128
return nil
}
func (i *UInt256) UnmarshalJSON(input []byte) error {
s := strings.Trim(string(input), "\"")
u256, ok := parseUInt256(s)
if !ok {
return fmt.Errorf("invalid hex or decimal integer %q", input)
}
*i = u256
return nil
}
func NewUInt128(x int64) *UInt128 {
a := big.NewInt(x)
i := new(UInt128)
*i = UInt128(*a)
return i
}
func NewUInt256(x int64) *UInt256 {
a := big.NewInt(x)
i := new(UInt256)
*i = UInt256(*a)
return i
}