/
types.go
58 lines (48 loc) · 1.03 KB
/
types.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
package common
import (
"encoding/hex"
)
const (
ChainIdSize = 64
)
type ChainIdType [ChainIdSize]byte
func (c ChainIdType) Hex() string {
return hex.EncodeToString(c[:])
}
func (c *ChainIdType) SetBytes(b []byte) {
if len(b) > len(c) {
copy(c[:], b[len(b)-ChainIdSize:])
} else {
copy(c[ChainIdSize-len(b):], b)
}
}
func Bytes2ChainId(b []byte) ChainIdType {
if b == nil {
return ChainIdType{}
}
var chainId ChainIdType
chainId.SetBytes(b)
return chainId
}
func Hex2ChainId(s string) ChainIdType {
if s == "" {
return ChainIdType{}
}
b, err := hex.DecodeString(s)
if err != nil {
return ChainIdType{}
}
return Bytes2ChainId(b)
}
func (c ChainIdType) MarshalText() ([]byte, error) {
return []byte(c.Hex()), nil
}
// UnmarshalJSON implements json.Unmarshaler.
func (c *ChainIdType) UnmarshalJSON(input []byte) error {
return c.UnmarshalText(input[1 : len(input)-1])
}
// UnmarshalText implements encoding.TextUnmarshaler
func (c *ChainIdType) UnmarshalText(input []byte) error {
c.SetBytes(input)
return nil
}