cid.go 938 Bytes
Newer Older
Steven Allen's avatar
Steven Allen committed
1 2 3
package bitswap_message_pb

import (
4
	"gitlab.dms3.io/dms3/go-cid"
Steven Allen's avatar
Steven Allen committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
)

// NOTE: Don't "embed" the cid, wrap it like we're doing here. Otherwise, gogo
// will try to use the Bytes() function.

// Cid is a custom type for CIDs in protobufs, that allows us to avoid
// reallocating.
type Cid struct {
	Cid cid.Cid
}

func (c Cid) Marshal() ([]byte, error) {
	return c.Cid.Bytes(), nil
}

func (c *Cid) MarshalTo(data []byte) (int, error) {
21 22
	// intentionally using KeyString here to avoid allocating.
	return copy(data[:c.Size()], c.Cid.KeyString()), nil
Steven Allen's avatar
Steven Allen committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
}

func (c *Cid) Unmarshal(data []byte) (err error) {
	c.Cid, err = cid.Cast(data)
	return err
}

func (c *Cid) Size() int {
	return len(c.Cid.KeyString())
}

func (c Cid) MarshalJSON() ([]byte, error) {
	return c.Cid.MarshalJSON()
}

func (c *Cid) UnmarshalJSON(data []byte) error {
	return c.Cid.UnmarshalJSON(data)
}

func (c Cid) Equal(other Cid) bool {
	return c.Cid.Equals(c.Cid)
}