cryptocoinjs / base-x

Encode/decode any base
MIT License
312 stars 75 forks source link

Gracefully accept string input to encode #49

Closed wraithgar closed 6 years ago

wraithgar commented 6 years ago

Since strings behave similarly to Buffers (they have .length and can be indexed via []) the encode function accepts them, but returns ultimately erroneous output. That is, the string returned will not decode back into the original string passed to encode.

Originally in #48 I thought that input validation was the answer, however because there are already several valid buffer types (Buffer, Int8Array) that do work, it seemed a better practice to simply cast a string to a Buffer if one is passed in. The default encoding was used since that's also the default encoding on a string and I felt that was a safe assumption to make (if a string is being passed in it's actually a utf8 string).

The existing test fixtures don't really work with this, and most of them are using input that doesn't translate cleanly to a utf8 string so I just added a hard coded test to the end of the suite.

dcousens commented 6 years ago

@wraithgar Buffer.isBuffer should work with the multiple variants of Buffer

wraithgar commented 6 years ago

@dcousens ok I've changed it to use Buffer.isBuffer and throw an exception patterned after the same one decode throws on a non-string.