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

Create a new Encode method that is like StringOfBase but never errors #60

Merged
merged 4 commits into from
Aug 30, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
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
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