Merge pull request #60 from ipfs/kevina/cid-fmtb
Create a new Encode method that is like StringOfBase but never errors
This commit is contained in:
14
cid.go
14
cid.go
@@ -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
|
||||
|
||||
25
cid_test.go
25
cid_test.go
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user