builder.go 1.22 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
	Codec    uint64
	MhType   uint64
	MhLength int // MhLength <= 0 means the default length
19 20
}

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
}

36
func (p V0Builder) Sum(data []byte) (Cid, error) {
37 38
	hash, err := mh.Sum(data, mh.SHA2_256, -1)
	if err != nil {
39
		return Undef, err
40
	}
41
	return Cid{string(hash)}, nil
42 43
}

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
	}
52
	return V1Builder{Codec: c, MhType: mh.SHA2_256}
53 54
}

55
func (p V1Builder) Sum(data []byte) (Cid, error) {
56
	mhLen := p.MhLength
57 58 59
	if mhLen <= 0 {
		mhLen = -1
	}
60
	hash, err := mh.Sum(data, p.MhType, mhLen)
61
	if err != nil {
62
		return Undef, err
63 64 65
	}
	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
}