base64.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /* -*- Mode: js; js-indent-level: 2; -*- */
  2. /*
  3. * Copyright 2011 Mozilla Foundation and contributors
  4. * Licensed under the New BSD license. See LICENSE or:
  5. * http://opensource.org/licenses/BSD-3-Clause
  6. */
  7. if (typeof define !== 'function') {
  8. var define = require('amdefine')(module, require);
  9. }
  10. define(function (require, exports, module) {
  11. var charToIntMap = {};
  12. var intToCharMap = {};
  13. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  14. .split('')
  15. .forEach(function (ch, index) {
  16. charToIntMap[ch] = index;
  17. intToCharMap[index] = ch;
  18. });
  19. /**
  20. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  21. */
  22. exports.encode = function base64_encode(aNumber) {
  23. if (aNumber in intToCharMap) {
  24. return intToCharMap[aNumber];
  25. }
  26. throw new TypeError("Must be between 0 and 63: " + aNumber);
  27. };
  28. /**
  29. * Decode a single base 64 digit to an integer.
  30. */
  31. exports.decode = function base64_decode(aChar) {
  32. if (aChar in charToIntMap) {
  33. return charToIntMap[aChar];
  34. }
  35. throw new TypeError("Not a valid base 64 digit: " + aChar);
  36. };
  37. });