diff --git a/index.js b/index.js index bb57088..196a7d0 100644 --- a/index.js +++ b/index.js @@ -2,27 +2,29 @@ var RFC4648 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' var RFC4648_HEX = '0123456789ABCDEFGHIJKLMNOPQRSTUV' var CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ' -module.exports = function base32Encode (buffer, variant) { - var alphabet, padding +module.exports = function base32Encode (buffer, variant, options) { + options = options || {} + var alphabet, defaultPadding switch (variant) { case 'RFC3548': case 'RFC4648': alphabet = RFC4648 - padding = true + defaultPadding = true break case 'RFC4648-HEX': alphabet = RFC4648_HEX - padding = true + defaultPadding = true break case 'Crockford': alphabet = CROCKFORD - padding = false + defaultPadding = false break default: throw new Error('Unknown base32 variant: ' + variant) } + var padding = (options.padding !== undefined ? options.padding : defaultPadding) var length = buffer.byteLength var view = new Uint8Array(buffer) diff --git a/readme.md b/readme.md index 9a4b8b5..f711eaa 100644 --- a/readme.md +++ b/readme.md @@ -20,16 +20,21 @@ console.log(base32Encode(buffer, 'Crockford')) console.log(base32Encode(buffer, 'RFC4648')) //=> ORSXG5A= +console.log(base32Encode(buffer, 'RFC4648', { padding: false })) +//=> ORSXG5A + console.log(base32Encode(buffer, 'RFC4648-HEX')) //=> EHIN6T0= ``` ## API -### base32Encode(buffer, variant) +### base32Encode(buffer, variant, options) - `buffer` <ArrayBuffer> - `variant` <String> +- `options` <Object> + - `padding` <Boolean> Encode the data in `buffer`. `variant` should be one of the supported variants listed below. @@ -39,6 +44,8 @@ listed below. - `'RFC4648-HEX'` - [base32hex from RFC4648](https://tools.ietf.org/html/rfc4648) - `'Crockford'` - [Crockford's Base32](http://www.crockford.com/wrmg/base32.html) +Options may have a `padding` property which provides a way to forcefully enable or disable padding. The default behavior is to follow the default of the selected variant. + ## See also - [base32-decode](https://github.com/LinusU/base32-decode) - Base32 decoder diff --git a/test.js b/test.js index 76cbcfe..05804a6 100644 --- a/test.js +++ b/test.js @@ -65,6 +65,12 @@ var testCases = [ ['Crockford', '666f6f626172', 'CSQPYRK1E8'] ] +// base32 encode with no options testCases.forEach(function (testCase) { assert.equal(base32Encode(hexToArrayBuffer(testCase[1]), testCase[0]), testCase[2]) }) + +// base32 encode with disabled padding option +testCases.forEach(function (testCase) { + assert.equal(base32Encode(hexToArrayBuffer(testCase[1]), testCase[0], { padding: false }), testCase[2].replace(/=/g, '')) +})