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