1// Hex JavaScript decoder
2// Copyright (c) 2008-2014 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
16/*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
17(function (undefined) {
18"use strict";
19
20var Hex = {},
21 decoder;
22
23Hex.decode = function(a) {
24 var i;
25 if (decoder === undefined) {
26 var hex = "0123456789ABCDEF",
27 ignore = " \f\n\r\t\u00A0\u2028\u2029";
28 decoder = [];
29 for (i = 0; i < 16; ++i)
30 decoder[hex.charAt(i)] = i;
31 hex = hex.toLowerCase();
32 for (i = 10; i < 16; ++i)
33 decoder[hex.charAt(i)] = i;
34 for (i = 0; i < ignore.length; ++i)
35 decoder[ignore.charAt(i)] = -1;
36 }
37 var out = [],
38 bits = 0,
39 char_count = 0;
40 for (i = 0; i < a.length; ++i) {
41 var c = a.charAt(i);
42 if (c == '=')
43 break;
44 c = decoder[c];
45 if (c == -1)
46 continue;
47 if (c === undefined)
48 throw 'Illegal character at offset ' + i;
49 bits |= c;
50 if (++char_count >= 2) {
51 out[out.length] = bits;
52 bits = 0;
53 char_count = 0;
54 } else {
55 bits <<= 4;
56 }
57 }
58 if (char_count)
59 throw "Hex encoding incomplete: 4 bits missing";
60 return out;
61};
62
63// export globals
64window.Hex = Hex;
65})();