blob: f617183ca0f6c21fcb052e34ebf536023ffd2cfc [file] [log] [blame]
Wentao Shang882e34e2013-01-05 02:49:51 -08001// Hex JavaScript decoder
2// Copyright (c) 2008 Lapo Luchini <lapo@lapo.it>
3
4// Permission to use, copy, modify, and/or distribute this software for any
5// purpose with or without fee is hereby granted, provided that the above
6// copyright notice and this permission notice appear in all copies.
7//
8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15
16Hex = {};
17
18Hex.decode = function(a) {
19 if (Hex.decoder == undefined) {
20 var hex = "0123456789ABCDEF";
21 var allow = " \f\n\r\t\u00A0\u2028\u2029";
22 var dec = [];
23 for (var i = 0; i < 16; ++i)
24 dec[hex.charAt(i)] = i;
25 hex = hex.toLowerCase();
26 for (var i = 10; i < 16; ++i)
27 dec[hex.charAt(i)] = i;
28 for (var i = 0; i < allow.length; ++i)
29 dec[allow.charAt(i)] = -1;
30 Hex.decoder = dec;
31 }
32 var out = [];
33 var bits = 0, char_count = 0;
34 for (var i = 0; i < a.length; ++i) {
35 var c = a.charAt(i);
36 if (c == '=')
37 break;
38 c = Hex.decoder[c];
39 if (c == -1)
40 continue;
41 if (c == undefined)
42 throw 'Illegal character at offset ' + i;
43 bits |= c;
44 if (++char_count >= 2) {
45 out[out.length] = bits;
46 bits = 0;
47 char_count = 0;
48 } else {
49 bits <<= 4;
50 }
51 }
52 if (char_count)
53 throw "Hex encoding incomplete: 4 bits missing";
54 return out;
55}