-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoding.go
executable file
·81 lines (59 loc) · 1.16 KB
/
encoding.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
package types
import (
"fmt"
"math/big"
"strconv"
"strings"
"github.com/definenulls/komerco-chain/helper/hex"
)
func ParseUint64orHex(val *string) (uint64, error) {
if val == nil {
return 0, nil
}
str := *val
base := 10
if strings.HasPrefix(str, "0x") {
str = str[2:]
base = 16
}
return strconv.ParseUint(str, base, 64)
}
func ParseUint256orHex(val *string) (*big.Int, error) {
if val == nil {
return nil, nil
}
str := *val
base := 10
if strings.HasPrefix(str, "0x") {
str = str[2:]
base = 16
}
b, ok := new(big.Int).SetString(str, base)
if !ok {
return nil, fmt.Errorf("could not parse")
}
return b, nil
}
func ParseInt64orHex(val *string) (int64, error) {
i, err := ParseUint64orHex(val)
return int64(i), err
}
func ParseBytes(val *string) ([]byte, error) {
if val == nil {
return []byte{}, nil
}
str := strings.TrimPrefix(*val, "0x")
return hex.DecodeString(str)
}
func EncodeUint64(b uint64) *string {
res := fmt.Sprintf("0x%x", b)
return &res
}
func EncodeBytes(b []byte) *string {
res := "0x" + hex.EncodeToString(b)
return &res
}
func EncodeBigInt(b *big.Int) *string {
res := "0x" + b.Text(16)
return &res
}