1// Hex JavaScript decoder
2// Copyright (c) 2008-2023 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(typeof define != 'undefined' ? define : function (factory) { 'use strict';
17 if (typeof module == 'object') module.exports = factory();
18 else window.hex = factory();
19})(function () {
20'use strict';
21
22const
23 haveU8 = (typeof Uint8Array == 'function');
24
25let decoder; // populated on first usage
26
27class Hex {
28
29 /**
30 * Decodes an hexadecimal value.
31 * @param {string|Array|Uint8Array} a - a string representing hexadecimal data, or an array representation of its charcodes
32 */
33 static decode(a) {
34 let isString = (typeof a == 'string');
35 let i;
36 if (decoder === undefined) {
37 let hex = '0123456789ABCDEF',
38 ignore = ' \f\n\r\t\u00A0\u2028\u2029';
39 decoder = [];
40 for (i = 0; i < 16; ++i)
41 decoder[hex.charCodeAt(i)] = i;
42 hex = hex.toLowerCase();
43 for (i = 10; i < 16; ++i)
44 decoder[hex.charCodeAt(i)] = i;
45 for (i = 0; i < ignore.length; ++i)
46 decoder[ignore.charCodeAt(i)] = -1;
47 }
48 let out = haveU8 ? new Uint8Array(a.length >> 1) : [],
49 bits = 0,
50 char_count = 0,
51 len = 0;
52 for (i = 0; i < a.length; ++i) {
53 let c = isString ? a.charCodeAt(i) : a[i];
54 c = decoder[c];
55 if (c == -1)
56 continue;
57 if (c === undefined)
58 throw 'Illegal character at offset ' + i;
59 bits |= c;
60 if (++char_count >= 2) {
61 out[len++] = bits;
62 bits = 0;
63 char_count = 0;
64 } else {
65 bits <<= 4;
66 }
67 }
68 if (char_count)
69 throw 'Hex encoding incomplete: 4 bits missing';
70 if (haveU8 && out.length > len) // in case it was originally longer because of ignored characters
71 out = out.subarray(0, len);
72 return out;
73 }
74
75}
76
77return Hex;
78
79});