blob: 8c931bf914a816dccedcc8478d52affe25db2794 [file] [log] [blame]
Meki Cherkaoui97e7a592012-04-14 02:50:06 -07001
2
3var DataUtils = function DataUtils(){
4
5
6};
7
8//exports.DataUtils =DataUtils;
9
10
11 var keyStr = "ABCDEFGHIJKLMNOP" +
12 "QRSTUVWXYZabcdef" +
13 "ghijklmnopqrstuv" +
14 "wxyz0123456789+/" +
15 "=";
16
17DataUtils.encode64=function encode64(input) {
18 input = escape(input);
19 var output = "";
20 var chr1, chr2, chr3 = "";
21 var enc1, enc2, enc3, enc4 = "";
22 var i = 0;
23
24 do {
25 chr1 = input.charCodeAt(i++);
26 chr2 = input.charCodeAt(i++);
27 chr3 = input.charCodeAt(i++);
28
29 enc1 = chr1 >> 2;
30 enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
31 enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
32 enc4 = chr3 & 63;
33
34 if (isNaN(chr2)) {
35 enc3 = enc4 = 64;
36 } else if (isNaN(chr3)) {
37 enc4 = 64;
38 }
39
40 output = output +
41 keyStr.charAt(enc1) +
42 keyStr.charAt(enc2) +
43 keyStr.charAt(enc3) +
44 keyStr.charAt(enc4);
45 chr1 = chr2 = chr3 = "";
46 enc1 = enc2 = enc3 = enc4 = "";
47 } while (i < input.length);
48
49 return output;
50 }
51
52DataUtils.decode64 = function decode64(input) {
53 var output = "";
54 var chr1, chr2, chr3 = "";
55 var enc1, enc2, enc3, enc4 = "";
56 var i = 0;
57
58 // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
59 var base64test = /[^A-Za-z0-9\+\/\=]/g;
60 if (base64test.exec(input)) {
61 alert("There were invalid base64 characters in the input text.\n" +
62 "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
63 "Expect errors in decoding.");
64 }
65 input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
66
67 do {
68 enc1 = keyStr.indexOf(input.charAt(i++));
69 enc2 = keyStr.indexOf(input.charAt(i++));
70 enc3 = keyStr.indexOf(input.charAt(i++));
71 enc4 = keyStr.indexOf(input.charAt(i++));
72
73 chr1 = (enc1 << 2) | (enc2 >> 4);
74 chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
75 chr3 = ((enc3 & 3) << 6) | enc4;
76
77 output = output + String.fromCharCode(chr1);
78
79 if (enc3 != 64) {
80 output = output + String.fromCharCode(chr2);
81 }
82 if (enc4 != 64) {
83 output = output + String.fromCharCode(chr3);
84 }
85
86 chr1 = chr2 = chr3 = "";
87 enc1 = enc2 = enc3 = enc4 = "";
88
89 } while (i < input.length);
90
91 return unescape(output);
92 };
93
94
95
96
97
98//byte []
99DataUtils.prototype.unsignedLongToByteArray= function( value) {
100 if( 0 == value )
101 return [0];
102
103 if( 0 <= value && value <= 0x00FF ) {
104 //byte []
105 bb = new Array[1];
106 bb[0] = (value & 0x00FF);
107 return bb;
108 }
109
110
111 //byte []
112 out = null;
113 //int
114 var offset = -1;
115 for(var i = 7; i >=0; --i) {
116 //byte
117 b = ((value >> (i * 8)) & 0xFF);
118 if( out == null && b != 0 ) {
119 out = new byte[i+1];
120 offset = i;
121 }
122 if( out != null )
123 out[ offset - i ] = b;
124 }
125 return out;
126}
127
128//function init(){
129
130 //var encoded = DataUtils.encode64('abc');
131 //console.log(encoded);
132//}
133//init();
134
135