convert.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. var test = require('tape')
  2. var b64 = require('../')
  3. var checks = [
  4. 'a',
  5. 'aa',
  6. 'aaa',
  7. 'hi',
  8. 'hi!',
  9. 'hi!!',
  10. 'sup',
  11. 'sup?',
  12. 'sup?!'
  13. ]
  14. test('convert to base64 and back', function (t) {
  15. t.plan(checks.length * 2)
  16. for (var i = 0; i < checks.length; i++) {
  17. var check = checks[i]
  18. var b64Str, arr, str
  19. b64Str = b64.fromByteArray(map(check, function (char) { return char.charCodeAt(0) }))
  20. arr = b64.toByteArray(b64Str)
  21. str = map(arr, function (byte) { return String.fromCharCode(byte) }).join('')
  22. t.equal(check, str, 'Checked ' + check)
  23. t.equal(b64.byteLength(b64Str), arr.length, 'Checked length for ' + check)
  24. }
  25. })
  26. var data = [
  27. [[0, 0, 0], 'AAAA'],
  28. [[0, 0, 1], 'AAAB'],
  29. [[0, 1, -1], 'AAH/'],
  30. [[1, 1, 1], 'AQEB'],
  31. [[0, -73, 23], 'ALcX']
  32. ]
  33. test('convert known data to string', function (t) {
  34. for (var i = 0; i < data.length; i++) {
  35. var bytes = data[i][0]
  36. var expected = data[i][1]
  37. var actual = b64.fromByteArray(bytes)
  38. t.equal(actual, expected, 'Ensure that ' + bytes + ' serialise to ' + expected)
  39. }
  40. t.end()
  41. })
  42. test('convert known data from string', function (t) {
  43. for (var i = 0; i < data.length; i++) {
  44. var expected = data[i][0]
  45. var string = data[i][1]
  46. var actual = b64.toByteArray(string)
  47. t.ok(equal(actual, expected), 'Ensure that ' + string + ' deserialise to ' + expected)
  48. var length = b64.byteLength(string)
  49. t.equal(length, expected.length, 'Ensure that ' + string + ' has byte lentgh of ' + expected.length)
  50. }
  51. t.end()
  52. })
  53. function equal (a, b) {
  54. var i
  55. var length = a.length
  56. if (length !== b.length) return false
  57. for (i = 0; i < length; ++i) {
  58. if ((a[i] & 0xFF) !== (b[i] & 0xFF)) return false
  59. }
  60. return true
  61. }
  62. function map (arr, callback) {
  63. var res = []
  64. var kValue, mappedValue
  65. for (var k = 0, len = arr.length; k < len; k++) {
  66. if ((typeof arr === 'string' && !!arr.charAt(k))) {
  67. kValue = arr.charAt(k)
  68. mappedValue = callback(kValue, k, arr)
  69. res[k] = mappedValue
  70. } else if (typeof arr !== 'string' && k in arr) {
  71. kValue = arr[k]
  72. mappedValue = callback(kValue, k, arr)
  73. res[k] = mappedValue
  74. }
  75. }
  76. return res
  77. }