-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #4 from ipfs/kevina/inliner
Add Inliner CID Builder.
- Loading branch information
Showing
2 changed files
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
) | ||
|
||
// InlineBuilder is a cid.Builder that will use the id multihash when the | ||
// size of the content is no more than limit | ||
type InlineBuilder struct { | ||
cid.Builder // Parent Builder | ||
Limit int // Limit (inclusive) | ||
} | ||
|
||
// WithCodec implements the cid.Builder interface | ||
func (p InlineBuilder) WithCodec(c uint64) cid.Builder { | ||
return InlineBuilder{p.Builder.WithCodec(c), p.Limit} | ||
} | ||
|
||
// Sum implements the cid.Builder interface | ||
func (p InlineBuilder) 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) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 TestInlineBuilderSmallValue(t *testing.T) { | ||
builder := InlineBuilder{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 TestInlinerBuilderLargeValue(t *testing.T) { | ||
builder := InlineBuilder{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") | ||
} | ||
} |