builder.go 1.21 KB
Newer Older
1 2 3 4 5 6
package cid

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

Kevin Atkinson's avatar
Kevin Atkinson committed
7
type Builder interface {
8
	Sum(data []byte) (*Cid, error)
9
	GetCodec() uint64
Kevin Atkinson's avatar
Kevin Atkinson committed
10
	WithCodec(uint64) Builder
11 12
}

Kevin Atkinson's avatar
Kevin Atkinson committed
13
type V0Builder struct{}
14

Kevin Atkinson's avatar
Kevin Atkinson committed
15
type V1Builder struct {
16 17 18 19 20
	Codec   uint64
	HashFun uint64
	HashLen int // HashLen <= 0 means the default length
}

21 22 23 24
func (p Prefix) GetCodec() uint64 {
	return p.Codec
}

Kevin Atkinson's avatar
Kevin Atkinson committed
25
func (p Prefix) WithCodec(c uint64) Builder {
26 27 28 29 30 31 32 33 34 35
	if c == p.Codec {
		return p
	}
	p.Codec = c
	if c != DagProtobuf {
		p.Version = 1
	}
	return p
}

Kevin Atkinson's avatar
Kevin Atkinson committed
36
func (p V0Builder) Sum(data []byte) (*Cid, error) {
37 38 39 40 41 42 43
	hash, err := mh.Sum(data, mh.SHA2_256, -1)
	if err != nil {
		return nil, err
	}
	return NewCidV0(hash), nil
}

Kevin Atkinson's avatar
Kevin Atkinson committed
44
func (p V0Builder) GetCodec() uint64 {
45 46 47
	return DagProtobuf
}

Kevin Atkinson's avatar
Kevin Atkinson committed
48
func (p V0Builder) WithCodec(c uint64) Builder {
49 50 51
	if c == DagProtobuf {
		return p
	}
Kevin Atkinson's avatar
Kevin Atkinson committed
52
	return V1Builder{Codec: c, HashFun: mh.SHA2_256}
53 54
}

Kevin Atkinson's avatar
Kevin Atkinson committed
55
func (p V1Builder) Sum(data []byte) (*Cid, error) {
56 57 58 59 60 61 62 63 64 65
	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
}
66

Kevin Atkinson's avatar
Kevin Atkinson committed
67
func (p V1Builder) GetCodec() uint64 {
68 69 70
	return p.Codec
}

Kevin Atkinson's avatar
Kevin Atkinson committed
71
func (p V1Builder) WithCodec(c uint64) Builder {
72 73 74
	p.Codec = c
	return p
}