Skip to content

Commit 8aa9fde

Browse files
authored
Merge pull request #4 from ipfs/kevina/inliner
Add Inliner CID Builder.
2 parents b6f51d5 + 4709f60 commit 8aa9fde

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

inline.go

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package cidutil
2+
3+
import (
4+
cid "github.com/ipfs/go-cid"
5+
mhash "github.com/multiformats/go-multihash"
6+
)
7+
8+
// InlineBuilder is a cid.Builder that will use the id multihash when the
9+
// size of the content is no more than limit
10+
type InlineBuilder struct {
11+
cid.Builder // Parent Builder
12+
Limit int // Limit (inclusive)
13+
}
14+
15+
// WithCodec implements the cid.Builder interface
16+
func (p InlineBuilder) WithCodec(c uint64) cid.Builder {
17+
return InlineBuilder{p.Builder.WithCodec(c), p.Limit}
18+
}
19+
20+
// Sum implements the cid.Builder interface
21+
func (p InlineBuilder) Sum(data []byte) (*cid.Cid, error) {
22+
if len(data) > p.Limit {
23+
return p.Builder.Sum(data)
24+
}
25+
return cid.V1Builder{Codec: p.GetCodec(), MhType: mhash.ID}.Sum(data)
26+
}

inline_test.go

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package cidutil
2+
3+
import (
4+
"math/rand"
5+
"testing"
6+
7+
cid "github.com/ipfs/go-cid"
8+
mhash "github.com/multiformats/go-multihash"
9+
)
10+
11+
func TestInlineBuilderSmallValue(t *testing.T) {
12+
builder := InlineBuilder{cid.V0Builder{}, 64}
13+
c, err := builder.Sum([]byte("Hello World"))
14+
if err != nil {
15+
t.Fatal(err)
16+
}
17+
if c.Prefix().MhType != mhash.ID {
18+
t.Fatal("Inliner builder failed to use ID Multihash on small values")
19+
}
20+
}
21+
22+
func TestInlinerBuilderLargeValue(t *testing.T) {
23+
builder := InlineBuilder{cid.V0Builder{}, 64}
24+
data := make([]byte, 512)
25+
rand.Read(data)
26+
c, err := builder.Sum(data)
27+
if err != nil {
28+
t.Fatal(err)
29+
}
30+
if c.Prefix().MhType == mhash.ID {
31+
t.Fatal("Inliner builder used ID Multihash on large values")
32+
}
33+
}

0 commit comments

Comments
 (0)