Browse Source

Add byteLength

master
Kirill Fomichev 8 years ago
parent
commit
718f83bfaf
  1. 5
      README.md
  2. 17
      lib/b64.js
  3. 3
      test/convert.js

5
README.md

@ -21,11 +21,12 @@ With [npm](https://npmjs.org) do:
`var base64 = require('base64-js')`
`base64` has two exposed functions, `toByteArray` and `fromByteArray`, which both take a single argument.
`base64` has three exposed functions, `byteLength`, `toByteArray` and `fromByteArray`, which both take a single argument.
* `byteLength` - Takes a base64 string and returns length of byte array
* `toByteArray` - Takes a base64 string and returns a byte array
* `fromByteArray` - Takes a byte array and returns a base64 string
## license
MIT
MIT

17
lib/b64.js

@ -1,5 +1,6 @@
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
@ -20,10 +21,8 @@ function init () {
init()
function toByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
function placeHoldersCount (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
@ -33,9 +32,19 @@ function toByteArray (b64) {
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
}
function byteLength (b64) {
// base64 is 4/3 + up to two characters of the original data
return b64.length * 3 / 4 - placeHoldersCount(b64)
}
function toByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
var len = b64.length
placeHolders = placeHoldersCount(b64)
arr = new Arr(len * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars

3
test/convert.js

@ -13,7 +13,7 @@ var checks = [
]
test('convert to base64 and back', function (t) {
t.plan(checks.length)
t.plan(checks.length * 2)
for (var i = 0; i < checks.length; i++) {
var check = checks[i]
@ -25,6 +25,7 @@ test('convert to base64 and back', function (t) {
str = map(arr, function (byte) { return String.fromCharCode(byte) }).join('')
t.equal(check, str, 'Checked ' + check)
t.equal(b64.byteLength(b64Str), arr.length, 'Checked length for ' + check)
}
})

Loading…
Cancel
Save