1 /* -*- Mode: js; js-indent-level: 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
7 if (typeof define !== 'function') {
8 var define = require('amdefine')(module, require);
10 define(function (require, exports, module) {
12 var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
15 * Encode an integer in the range of 0 to 63 to a single base 64 digit.
17 exports.encode = function (number) {
18 if (0 <= number && number < intToCharMap.length) {
19 return intToCharMap[number];
21 throw new TypeError("Must be between 0 and 63: " + aNumber);
25 * Decode a single base 64 character code digit to an integer. Returns -1 on
28 exports.decode = function (charCode) {
32 var littleA = 97; // 'a'
33 var littleZ = 122; // 'z'
39 var slash = 47; // '/'
41 var littleOffset = 26;
42 var numberOffset = 52;
44 // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
45 if (bigA <= charCode && charCode <= bigZ) {
46 return (charCode - bigA);
49 // 26 - 51: abcdefghijklmnopqrstuvwxyz
50 if (littleA <= charCode && charCode <= littleZ) {
51 return (charCode - littleA + littleOffset);
54 // 52 - 61: 0123456789
55 if (zero <= charCode && charCode <= nine) {
56 return (charCode - zero + numberOffset);
60 if (charCode == plus) {
65 if (charCode == slash) {
69 // Invalid base64 digit.