Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Inliner CID Builder. #4

Merged
merged 2 commits into from
Aug 21, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions inliner.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package cidutil

import (
cid "github.com/ipfs/go-cid"
mhash "github.com/multiformats/go-multihash"
)

// Inliner is a cid.Builder that will use the id multihash when the
// size of the content is no more than limit
type Inliner struct {
cid.Builder
Limit int
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should probably be documented (inclusive? exclusive?).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mean "Limit"? I said above "size of the content is no more than limit" which should imply inclusive.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah. I didn't see that. Yes, that should be sufficient.

}

// WithCodec implements the cid.Builder interface
func (p Inliner) WithCodec(c uint64) cid.Builder {
return Inliner{p.Builder.WithCodec(c), p.Limit}
}

// Sum implements the cid.Builder interface
func (p Inliner) Sum(data []byte) (*cid.Cid, error) {
if len(data) > p.Limit {
return p.Builder.Sum(data)
}
return cid.V1Builder{Codec: p.GetCodec(), MhType: mhash.ID}.Sum(data)
}
33 changes: 33 additions & 0 deletions inliner_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package cidutil

import (
"math/rand"
"testing"

cid "github.com/ipfs/go-cid"
mhash "github.com/multiformats/go-multihash"
)

func TestInlinerSmallValue(t *testing.T) {
builder := Inliner{cid.V0Builder{}, 64}
c, err := builder.Sum([]byte("Hello World"))
if err != nil {
t.Fatal(err)
}
if c.Prefix().MhType != mhash.ID {
t.Fatal("Inliner builder failed to use ID Multihash on small values")
}
}

func TestInlinerLargeValue(t *testing.T) {
builder := Inliner{cid.V0Builder{}, 64}
data := make([]byte, 512)
rand.Read(data)
c, err := builder.Sum(data)
if err != nil {
t.Fatal(err)
}
if c.Prefix().MhType == mhash.ID {
t.Fatal("Inliner builder used ID Multihash on large values")
}
}