-
Notifications
You must be signed in to change notification settings - Fork 14
/
hexbytes.go
86 lines (68 loc) · 1.78 KB
/
hexbytes.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
package types
import (
"encoding/hex"
"github.com/tinylib/msgp/msgp"
"github.com/qlcchain/go-qlc/common/util"
)
type HexBytes []byte
func init() {
msgp.RegisterExtension(HexBytesExtensionType, func() msgp.Extension { return new(HexBytes) })
}
func NewHexBytesFromHex(hexStr string) HexBytes {
hbs := HexBytes{}
err := hbs.SetHex(hexStr)
if err != nil {
return nil
}
return hbs
}
func NewHexBytesFromData(data []byte) HexBytes {
hbs := make([]byte, len(data))
copy(hbs[:], data)
return hbs
}
func (hbs *HexBytes) SetHex(hexString string) error {
s := util.TrimQuotes(hexString)
size := hex.DecodedLen(len(s))
hbs2 := make([]byte, size)
if _, err := hex.Decode(hbs2[:], []byte(s)); err != nil {
return err
}
*hbs = hbs2
return nil
}
func (hbs HexBytes) String() string {
return hex.EncodeToString(hbs[:])
}
//ExtensionType implements Extension.ExtensionType interface
func (hbs HexBytes) ExtensionType() int8 {
return HexBytesExtensionType
}
//ExtensionType implements Extension.Len interface
func (hbs HexBytes) Len() int {
return len(hbs[:])
}
//ExtensionType implements Extension.MarshalBinaryTo interface
func (hbs HexBytes) MarshalBinaryTo(text []byte) error {
copy(text, hbs[:])
return nil
}
//ExtensionType implements Extension.UnmarshalBinary interface
func (hbs *HexBytes) UnmarshalBinary(text []byte) error {
*hbs = make([]byte, len(text))
copy((*hbs)[:], text)
return nil
}
//UnmarshalText implements encoding.TextUnmarshaler
func (hbs *HexBytes) UnmarshalText(text []byte) error {
s := util.TrimQuotes(string(text))
err := hbs.SetHex(s)
return err
}
// MarshalText implements the encoding.TextMarshaler interface.
func (hbs HexBytes) MarshalText() (text []byte, err error) {
return []byte(hbs.String()), nil
}
func (hbs HexBytes) Bytes() []byte {
return hbs[:]
}