nitdoc: moved base64 and github to their own modules
[nit.git] / share / nitdoc / scripts / base64.js
1 /*
2 * Base64
3 */
4 base64 = {};
5 base64.PADCHAR = '=';
6 base64.ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
7 base64.getbyte64 = function(s,i) {
8 // This is oddly fast, except on Chrome/V8.
9 // Minimal or no improvement in performance by using a
10 // object with properties mapping chars to value (eg. 'A': 0)
11 var idx = base64.ALPHA.indexOf(s.charAt(i));
12 if (idx == -1) {
13 throw "Cannot decode base64";
14 }
15 return idx;
16 }
17
18 base64.decode = function(s) {
19 // convert to string
20 s = "" + s;
21 var getbyte64 = base64.getbyte64;
22 var pads, i, b10;
23 var imax = s.length
24 if (imax == 0) {
25 return s;
26 }
27
28 if (imax % 4 != 0) {
29 throw "Cannot decode base64";
30 }
31
32 pads = 0
33 if (s.charAt(imax -1) == base64.PADCHAR) {
34 pads = 1;
35 if (s.charAt(imax -2) == base64.PADCHAR) {
36 pads = 2;
37 }
38 // either way, we want to ignore this last block
39 imax -= 4;
40 }
41
42 var x = [];
43 for (i = 0; i < imax; i += 4) {
44 b10 = (getbyte64(s,i) << 18) | (getbyte64(s,i+1) << 12) |
45 (getbyte64(s,i+2) << 6) | getbyte64(s,i+3);
46 x.push(String.fromCharCode(b10 >> 16, (b10 >> 8) & 0xff, b10 & 0xff));
47 }
48
49 switch (pads) {
50 case 1:
51 b10 = (getbyte64(s,i) << 18) | (getbyte64(s,i+1) << 12) | (getbyte64(s,i+2) << 6)
52 x.push(String.fromCharCode(b10 >> 16, (b10 >> 8) & 0xff));
53 break;
54 case 2:
55 b10 = (getbyte64(s,i) << 18) | (getbyte64(s,i+1) << 12);
56 x.push(String.fromCharCode(b10 >> 16));
57 break;
58 }
59 return x.join('');
60 }
61
62 base64.getbyte = function(s,i) {
63 var x = s.charCodeAt(i);
64 if (x > 255) {
65 throw "INVALID_CHARACTER_ERR: DOM Exception 5";
66 }
67 return x;
68 }
69
70
71 base64.encode = function(s) {
72 if (arguments.length != 1) {
73 throw "SyntaxError: Not enough arguments";
74 }
75 var padchar = base64.PADCHAR;
76 var alpha = base64.ALPHA;
77 var getbyte = base64.getbyte;
78
79 var i, b10;
80 var x = [];
81
82 // convert to string
83 s = "" + s;
84
85 var imax = s.length - s.length % 3;
86
87 if (s.length == 0) {
88 return s;
89 }
90 for (i = 0; i < imax; i += 3) {
91 b10 = (getbyte(s,i) << 16) | (getbyte(s,i+1) << 8) | getbyte(s,i+2);
92 x.push(alpha.charAt(b10 >> 18));
93 x.push(alpha.charAt((b10 >> 12) & 0x3F));
94 x.push(alpha.charAt((b10 >> 6) & 0x3f));
95 x.push(alpha.charAt(b10 & 0x3f));
96 }
97 switch (s.length - imax) {
98 case 1:
99 b10 = getbyte(s,i) << 16;
100 x.push(alpha.charAt(b10 >> 18) + alpha.charAt((b10 >> 12) & 0x3F) +
101 padchar + padchar);
102 break;
103 case 2:
104 b10 = (getbyte(s,i) << 16) | (getbyte(s,i+1) << 8);
105 x.push(alpha.charAt(b10 >> 18) + alpha.charAt((b10 >> 12) & 0x3F) +
106 alpha.charAt((b10 >> 6) & 0x3f) + padchar);
107 break;
108 }
109 return x.join('');
110 }