format.go 1.45 KB
Newer Older
1 2 3 4 5 6 7 8
package cid

import (
	mh "github.com/multiformats/go-multihash"
)

type Format interface {
	Sum(data []byte) (*Cid, error)
9 10
	GetCodec() uint64
	WithCodec(uint64) Format
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
}

type FormatV0 struct{}

type FormatV1 struct {
	Codec   uint64
	HashFun uint64
	HashLen int // HashLen <= 0 means the default length
}

func PrefixToFormat(p Prefix) Format {
	if p.Version == 0 {
		return FormatV0{}
	}
	mhLen := p.MhLength
	if p.MhType == mh.ID {
		mhLen = 0
	}
	if mhLen < 0 {
		mhLen = 0
	}
	return FormatV1{
		Codec:   p.Codec,
		HashFun: p.MhType,
		HashLen: mhLen,
	}
}

39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
func (p Prefix) GetCodec() uint64 {
	return p.Codec
}

func (p Prefix) WithCodec(c uint64) Format {
	if c == p.Codec {
		return p
	}
	p.Codec = c
	if c != DagProtobuf {
		p.Version = 1
	}
	return p
}

54 55 56 57 58 59 60 61
func (p FormatV0) Sum(data []byte) (*Cid, error) {
	hash, err := mh.Sum(data, mh.SHA2_256, -1)
	if err != nil {
		return nil, err
	}
	return NewCidV0(hash), nil
}

62 63 64 65 66 67 68 69 70 71 72
func (p FormatV0) GetCodec() uint64 {
	return DagProtobuf
}

func (p FormatV0) WithCodec(c uint64) Format {
	if c == DagProtobuf {
		return p
	}
	return FormatV1{Codec: c, HashFun: mh.SHA2_256}
}

73 74 75 76 77 78 79 80 81 82 83
func (p FormatV1) Sum(data []byte) (*Cid, error) {
	mhLen := p.HashLen
	if mhLen <= 0 {
		mhLen = -1
	}
	hash, err := mh.Sum(data, p.HashFun, mhLen)
	if err != nil {
		return nil, err
	}
	return NewCidV1(p.Codec, hash), nil
}
84 85 86 87 88 89 90 91 92

func (p FormatV1) GetCodec() uint64 {
	return p.Codec
}

func (p FormatV1) WithCodec(c uint64) Format {
	p.Codec = c
	return p
}