/
bytes.go
58 lines (46 loc) · 1.04 KB
/
bytes.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 chain
import (
"encoding/hex"
"github.com/greymass/go-eosio/pkg/abi"
)
// Binary data type, encodes to hex string in JSON.
// Use the Blob type instead where possible since it encodes to base64.
type Bytes []byte
func (b Bytes) Hex() string {
return hex.EncodeToString(b)
}
// abi.Marshaler conformance
func (b Bytes) MarshalABI(e *abi.Encoder) error {
var err error
l := uint(len(b))
err = e.WriteVaruint(l)
if err == nil {
err = e.WriteBytes(b)
}
return err
}
// abi.Unmarshaler conformance
func (b *Bytes) UnmarshalABI(d *abi.Decoder) error {
l, err := d.ReadVaruint()
if err != nil {
return err
}
_, data, err := d.ReadBytes(int(l))
if err == nil {
*b = data
}
return err
}
// encoding.TextMarshaler conformance
func (b Bytes) MarshalText() (text []byte, err error) {
return []byte(b.Hex()), nil
}
// encoding.TextUnmarshaler conformance
func (b *Bytes) UnmarshalText(text []byte) error {
data := make([]byte, hex.DecodedLen(len(text)))
_, err := hex.Decode(data, text)
if err == nil {
*b = data
}
return nil
}