Skip to content

Commit ce9c9c3

Browse files
committed
Create new Format interface for creating CIDs.
1 parent 5b04f30 commit ce9c9c3

File tree

2 files changed

+113
-0
lines changed

2 files changed

+113
-0
lines changed

format.go

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package cid
2+
3+
import (
4+
mh "github.com/multiformats/go-multihash"
5+
)
6+
7+
type Format interface {
8+
Sum(data []byte) (*Cid, error)
9+
}
10+
11+
type FormatV0 struct{}
12+
13+
type FormatV1 struct {
14+
Codec uint64
15+
HashFun uint64
16+
HashLen int // 0 (or -1 for compatibility) means the default length
17+
}
18+
19+
func PrefixToFormat(p Prefix) Format {
20+
if p.Version == 0 {
21+
return FormatV0{}
22+
}
23+
mhLen := p.MhLength
24+
if p.MhType == mh.ID {
25+
mhLen = 0
26+
}
27+
if mhLen == -1 {
28+
mhLen = 0
29+
}
30+
return FormatV1{
31+
Codec: p.Codec,
32+
HashFun: p.MhType,
33+
HashLen: mhLen,
34+
}
35+
}
36+
37+
func (p FormatV0) Sum(data []byte) (*Cid, error) {
38+
hash, err := mh.Sum(data, mh.SHA2_256, -1)
39+
if err != nil {
40+
return nil, err
41+
}
42+
return NewCidV0(hash), nil
43+
}
44+
45+
func (p FormatV1) Sum(data []byte) (*Cid, error) {
46+
mhLen := p.HashLen
47+
if mhLen == 0 {
48+
mhLen = -1
49+
}
50+
hash, err := mh.Sum(data, p.HashFun, mhLen)
51+
if err != nil {
52+
return nil, err
53+
}
54+
return NewCidV1(p.Codec, hash), nil
55+
}

format_test.go

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package cid
2+
3+
import (
4+
"testing"
5+
6+
mh "github.com/multiformats/go-multihash"
7+
)
8+
9+
func TestFormatV1(t *testing.T) {
10+
data := []byte("this is some test content")
11+
12+
// Construct c1
13+
format := FormatV1{Codec: DagCBOR, HashFun: mh.SHA2_256}
14+
c1, err := format.Sum(data)
15+
if err != nil {
16+
t.Fatal(err)
17+
}
18+
19+
// Construct c2
20+
hash, err := mh.Sum(data, mh.SHA2_256, -1)
21+
if err != nil {
22+
t.Fatal(err)
23+
}
24+
c2 := NewCidV1(DagCBOR, hash)
25+
26+
if !c1.Equals(c2) {
27+
t.Fatal("cids mismatch")
28+
}
29+
if c1.Prefix() != c2.Prefix() {
30+
t.Fatal("prefixes mismatch")
31+
}
32+
}
33+
34+
func TestFormatV0(t *testing.T) {
35+
data := []byte("this is some test content")
36+
37+
// Construct c1
38+
format := FormatV0{}
39+
c1, err := format.Sum(data)
40+
if err != nil {
41+
t.Fatal(err)
42+
}
43+
44+
// Construct c2
45+
hash, err := mh.Sum(data, mh.SHA2_256, -1)
46+
if err != nil {
47+
t.Fatal(err)
48+
}
49+
c2 := NewCidV0(hash)
50+
51+
if !c1.Equals(c2) {
52+
t.Fatal("cids mismatch")
53+
}
54+
if c1.Prefix() != c2.Prefix() {
55+
t.Fatal("prefixes mismatch")
56+
}
57+
}
58+

0 commit comments

Comments
 (0)