peer_serde.go 1.84 KB
Newer Older
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
// This file contains Protobuf and JSON serialization/deserialization methods for peer IDs.
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
}

// BinaryMarshal returns the byte representation of the peer ID.
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
}

// BinaryUnmarshal sets the ID from its binary representation.
func (id *ID) UnmarshalBinary(data []byte) error {
	return id.Unmarshal(data)
}

// Implements Gogo's proto.Sizer, but we omit the compile-time assertion to avoid introducing a hard
// 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
}

// TextMarshal returns the text encoding of the ID.
func (id ID) MarshalText() ([]byte, error) {
	return []byte(IDB58Encode(id)), nil
}

// TextUnmarshal restores the ID from its text encoding.
func (id *ID) UnmarshalText(data []byte) error {
	pid, err := IDB58Decode(string(data))
	if err != nil {
		return err
	}
	*id = pid
	return nil
}