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
8 var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
11 * Encode an integer in the range of 0 to 63 to a single base 64 digit.
13 exports.encode = function (number) {
14 if (0 <= number && number < intToCharMap.length) {
15 return intToCharMap[number];
17 throw new TypeError("Must be between 0 and 63: " + number);
21 * Decode a single base 64 character code digit to an integer. Returns -1 on
24 exports.decode = function (charCode) {
28 var littleA = 97; // 'a'
29 var littleZ = 122; // 'z'
35 var slash = 47; // '/'
37 var littleOffset = 26;
38 var numberOffset = 52;
40 // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
41 if (bigA <= charCode && charCode <= bigZ) {
42 return (charCode - bigA);
45 // 26 - 51: abcdefghijklmnopqrstuvwxyz
46 if (littleA <= charCode && charCode <= littleZ) {
47 return (charCode - littleA + littleOffset);
50 // 52 - 61: 0123456789
51 if (zero <= charCode && charCode <= nine) {
52 return (charCode - zero + numberOffset);
56 if (charCode == plus) {
61 if (charCode == slash) {
65 // Invalid base64 digit.