2018-06-28 22:48:56 -04:00
|
|
|
package cid
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
mh "github.com/multiformats/go-multihash"
|
|
|
|
|
)
|
|
|
|
|
|
2018-08-09 00:04:26 -04:00
|
|
|
type Builder interface {
|
2018-05-03 15:12:25 +02:00
|
|
|
Sum(data []byte) (Cid, error)
|
2018-07-24 22:28:19 -04:00
|
|
|
GetCodec() uint64
|
2018-08-09 00:04:26 -04:00
|
|
|
WithCodec(uint64) Builder
|
2018-06-28 22:48:56 -04:00
|
|
|
}
|
|
|
|
|
|
2018-08-09 00:04:26 -04:00
|
|
|
type V0Builder struct{}
|
2018-06-28 22:48:56 -04:00
|
|
|
|
2018-08-09 00:04:26 -04:00
|
|
|
type V1Builder struct {
|
2018-08-10 00:13:49 -04:00
|
|
|
Codec uint64
|
|
|
|
|
MhType uint64
|
|
|
|
|
MhLength int // MhLength <= 0 means the default length
|
2018-06-28 22:48:56 -04:00
|
|
|
}
|
|
|
|
|
|
2018-07-24 22:28:19 -04:00
|
|
|
func (p Prefix) GetCodec() uint64 {
|
|
|
|
|
return p.Codec
|
|
|
|
|
}
|
|
|
|
|
|
2018-08-09 00:04:26 -04:00
|
|
|
func (p Prefix) WithCodec(c uint64) Builder {
|
2018-07-24 22:28:19 -04:00
|
|
|
if c == p.Codec {
|
|
|
|
|
return p
|
|
|
|
|
}
|
|
|
|
|
p.Codec = c
|
|
|
|
|
if c != DagProtobuf {
|
|
|
|
|
p.Version = 1
|
|
|
|
|
}
|
|
|
|
|
return p
|
|
|
|
|
}
|
|
|
|
|
|
2018-05-03 15:12:25 +02:00
|
|
|
func (p V0Builder) Sum(data []byte) (Cid, error) {
|
2018-06-28 22:48:56 -04:00
|
|
|
hash, err := mh.Sum(data, mh.SHA2_256, -1)
|
|
|
|
|
if err != nil {
|
2018-08-25 03:05:17 -04:00
|
|
|
return Nil, err
|
2018-06-28 22:48:56 -04:00
|
|
|
}
|
|
|
|
|
return NewCidV0(hash), nil
|
|
|
|
|
}
|
|
|
|
|
|
2018-08-09 00:04:26 -04:00
|
|
|
func (p V0Builder) GetCodec() uint64 {
|
2018-07-24 22:28:19 -04:00
|
|
|
return DagProtobuf
|
|
|
|
|
}
|
|
|
|
|
|
2018-08-09 00:04:26 -04:00
|
|
|
func (p V0Builder) WithCodec(c uint64) Builder {
|
2018-07-24 22:28:19 -04:00
|
|
|
if c == DagProtobuf {
|
|
|
|
|
return p
|
|
|
|
|
}
|
2018-08-10 00:13:49 -04:00
|
|
|
return V1Builder{Codec: c, MhType: mh.SHA2_256}
|
2018-07-24 22:28:19 -04:00
|
|
|
}
|
|
|
|
|
|
2018-05-03 15:12:25 +02:00
|
|
|
func (p V1Builder) Sum(data []byte) (Cid, error) {
|
2018-08-10 00:13:49 -04:00
|
|
|
mhLen := p.MhLength
|
2018-06-28 22:48:56 -04:00
|
|
|
if mhLen <= 0 {
|
|
|
|
|
mhLen = -1
|
|
|
|
|
}
|
2018-08-10 00:13:49 -04:00
|
|
|
hash, err := mh.Sum(data, p.MhType, mhLen)
|
2018-06-28 22:48:56 -04:00
|
|
|
if err != nil {
|
2018-08-25 03:05:17 -04:00
|
|
|
return Nil, err
|
2018-06-28 22:48:56 -04:00
|
|
|
}
|
|
|
|
|
return NewCidV1(p.Codec, hash), nil
|
|
|
|
|
}
|
2018-07-24 22:28:19 -04:00
|
|
|
|
2018-08-09 00:04:26 -04:00
|
|
|
func (p V1Builder) GetCodec() uint64 {
|
2018-07-24 22:28:19 -04:00
|
|
|
return p.Codec
|
|
|
|
|
}
|
|
|
|
|
|
2018-08-09 00:04:26 -04:00
|
|
|
func (p V1Builder) WithCodec(c uint64) Builder {
|
2018-07-24 22:28:19 -04:00
|
|
|
p.Codec = c
|
|
|
|
|
return p
|
|
|
|
|
}
|