multiformats / js-cid

CID implementation in JavaScript
MIT License
97 stars 39 forks source link

toBaseEncodedString should default to the base of the cid string use to construct the instance #76

Closed olizilla closed 5 years ago

olizilla commented 5 years ago

Where a CID instance is constructed from a string, we should preserve the base that it was given in, and use it as the default base when toBaseEncodedString is called, so the information is not lost.

In IPLD explorer, we construct a CID from a user provided string. That means we lose the information about the base encoding we were given. See: https://github.com/ipfs-shipyard/ipfs-webui/issues/999

Ideally we'd have it so you could

const Cid = require('cids')
const x = new Cid('bafybeihj5nwgbaan7eh4ryrx5vjsi3zzn2dvpgv2ibvku6lwublilhxcfu')

x.toString()
// 'bafybeihj5nwgbaan7eh4ryrx5vjsi3zzn2dvpgv2ibvku6lwublilhxcfu'

x.toBaseEncodedString()
// 'bafybeihj5nwgbaan7eh4ryrx5vjsi3zzn2dvpgv2ibvku6lwublilhxcfu'

x.toBaseEncodedString('base58btc')
// 'zdj7WmB2HKhmNYQT1nRJaJckMuvLJChCAvwuKA7jXvfzZEJ1a'

const y = new Cid('zdj7WmB2HKhmNYQT1nRJaJckMuvLJChCAvwuKA7jXvfzZEJ1a')

x.toString()
// 'zdj7WmB2HKhmNYQT1nRJaJckMuvLJChCAvwuKA7jXvfzZEJ1a'

x.toBaseEncodedString()
// 'zdj7WmB2HKhmNYQT1nRJaJckMuvLJChCAvwuKA7jXvfzZEJ1a'

x.toBaseEncodedString('base32')
// 'bafybeihj5nwgbaan7eh4ryrx5vjsi3zzn2dvpgv2ibvku6lwublilhxcfu'
olizilla commented 5 years ago

This would affect #73, @alanshaw @vmx what you think?

vmx commented 5 years ago

That sounds reasonable to me. Though @alanshaw is really the base encoding specialist in the JS team.

alanshaw commented 5 years ago

I think this is a good idea. I believe go-ipfs actually uses strings as the backing representation for CIDs so you get back what you put in.

mikeal commented 5 years ago

ooooooo, I think this would also open up some nice lazy properties we could put on CID’s so that they don’t actually do buffer allocations if all someone does is instantiate one with a string and then ask for it base encoded again. Love it!