peer_serde.go 1.85 KB
Newer Older
Vasco Santos's avatar
Vasco Santos committed
1
// Package peer contains Protobuf and JSON serialization/deserialization methods for peer IDs.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
package peer

import (
	"encoding"
	"encoding/json"
)

// Interface assertions commented out to avoid introducing hard dependencies to protobuf.
// var _ proto.Marshaler = (*ID)(nil)
// var _ proto.Unmarshaler = (*ID)(nil)
var _ json.Marshaler = (*ID)(nil)
var _ json.Unmarshaler = (*ID)(nil)

var _ encoding.BinaryMarshaler = (*ID)(nil)
var _ encoding.BinaryUnmarshaler = (*ID)(nil)
var _ encoding.TextMarshaler = (*ID)(nil)
var _ encoding.TextUnmarshaler = (*ID)(nil)

func (id ID) Marshal() ([]byte, error) {
	return []byte(id), nil
}

Vasco Santos's avatar
Vasco Santos committed
24
// MarshalBinary returns the byte representation of the peer ID.
25 26 27 28 29 30 31 32 33 34 35 36 37
func (id ID) MarshalBinary() ([]byte, error) {
	return id.Marshal()
}

func (id ID) MarshalTo(data []byte) (n int, err error) {
	return copy(data, []byte(id)), nil
}

func (id *ID) Unmarshal(data []byte) (err error) {
	*id, err = IDFromBytes(data)
	return err
}

Vasco Santos's avatar
Vasco Santos committed
38
// UnmarshalBinary sets the ID from its binary representation.
39 40 41 42
func (id *ID) UnmarshalBinary(data []byte) error {
	return id.Unmarshal(data)
}

Vasco Santos's avatar
Vasco Santos committed
43
// Size implements Gogo's proto.Sizer, but we omit the compile-time assertion to avoid introducing a hard
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
// dependency on gogo.
func (id ID) Size() int {
	return len([]byte(id))
}

func (id ID) MarshalJSON() ([]byte, error) {
	return json.Marshal(IDB58Encode(id))
}

func (id *ID) UnmarshalJSON(data []byte) (err error) {
	var v string
	if err = json.Unmarshal(data, &v); err != nil {
		return err
	}
	*id, err = IDB58Decode(v)
	return err
}

Vasco Santos's avatar
Vasco Santos committed
62
// MarshalText returns the text encoding of the ID.
63 64 65 66
func (id ID) MarshalText() ([]byte, error) {
	return []byte(IDB58Encode(id)), nil
}

Vasco Santos's avatar
Vasco Santos committed
67
// UnmarshalText restores the ID from its text encoding.
68 69 70 71 72 73 74 75
func (id *ID) UnmarshalText(data []byte) error {
	pid, err := IDB58Decode(string(data))
	if err != nil {
		return err
	}
	*id = pid
	return nil
}