Skip to content

Commit

Permalink
Merge pull request #60 from ipfs/kevina/cid-fmtb
Browse files Browse the repository at this point in the history
Create a new Encode method that is like StringOfBase but never errors
  • Loading branch information
Stebalien committed Aug 30, 2018
2 parents 1766ab0 + b3d85b3 commit 6ddb575
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
14 changes: 14 additions & 0 deletions cid.go
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,20 @@ func (c *Cid) StringOfBase(base mbase.Encoding) (string, error) {
}
}

// Encode return the string representation of a Cid in a given base
// when applicable. Version 0 Cid's are always in Base58 as they do
// not take a multibase prefix.
func (c *Cid) Encode(base mbase.Encoder) string {
switch c.version {
case 0:
return c.hash.B58String()
case 1:
return base.Encode(c.bytesV1())
default:
panic("not possible to reach this point")
}
}

// Hash returns the multihash contained by a Cid.
func (c *Cid) Hash() mh.Multihash {
return c.hash
Expand Down
25 changes: 25 additions & 0 deletions cid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,15 @@ func TestBasesMarshaling(t *testing.T) {
}

assertEqual(t, cid, out2)

encoder, err := mbase.NewEncoder(b)
if err != nil {
t.Fatal(err)
}
s2 := cid.Encode(encoder)
if s != s2 {
t.Fatalf("'%s' != '%s'", s, s2)
}
}
}

Expand Down Expand Up @@ -181,6 +190,22 @@ func TestV0Handling(t *testing.T) {
if cid.String() != old {
t.Fatal("marshaling roundtrip failed")
}

new, err := cid.StringOfBase(mbase.Base58BTC)
if err != nil {
t.Fatal(err)
}
if new != old {
t.Fatal("StringOfBase roundtrip failed")
}

encoder, err := mbase.NewEncoder(mbase.Base58BTC)
if err != nil {
t.Fatal(err)
}
if cid.Encode(encoder) != old {
t.Fatal("Encode roundtrip failed")
}
}

func TestV0ErrorCases(t *testing.T) {
Expand Down

0 comments on commit 6ddb575

Please sign in to comment.