univ-conv
Version:
The universal binary and text converter
107 lines • 3.29 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.HexConverter = void 0;
const AbstractConverter_1 = require("./AbstractConverter");
const core_1 = require("./core");
const Environment_1 = require("./Environment");
const StringUtil_1 = require("./StringUtil");
const BYTE_TO_HEX = [];
for (let n = 0; n <= 0xff; ++n) {
const hexOctet = n.toString(16).padStart(2, "0");
BYTE_TO_HEX.push(hexOctet);
}
const HEX_STRINGS = "0123456789abcdef";
const MAP_HEX = {
0: 0,
1: 1,
2: 2,
3: 3,
4: 4,
5: 5,
6: 6,
7: 7,
8: 8,
9: 9,
a: 10,
A: 10,
b: 11,
B: 11,
c: 12,
C: 12,
d: 13,
D: 13,
e: 14,
E: 14,
f: 15,
F: 15,
};
class HexConverter extends AbstractConverter_1.AbstractConverter {
constructor() {
super(...arguments);
this.type = "hex";
}
empty() {
return "";
}
is(input, options) {
return typeof input === "string" && options.inputStringType === "hex";
}
async _from(input, options) {
if (typeof input === "string" && options.inputStringType === "hex") {
if ((0, core_1.hasNoStartLength)(options)) {
return input;
}
const { start, end } = await this._getStartEnd(input, options);
return input.slice(start * 2, end ? end * 2 : undefined);
}
const u8 = await (0, AbstractConverter_1._)().convert("uint8array", input, options);
return (Array.from(u8)
.map((b) => HEX_STRINGS[b >> 4] + HEX_STRINGS[b & 15])
.join(""));
}
_getStartEnd(input, options) {
return Promise.resolve((0, core_1.getStartEnd)(options, input.length / 2));
}
_isEmpty(input) {
return !input;
}
async _merge(chunks) {
return Promise.resolve(chunks.join(""));
}
_size(input) {
return Promise.resolve(input.length / 2);
}
async _toArrayBuffer(input, options) {
const u8 = await this._toUint8Array(input, options);
return u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength);
}
async _toBase64(input, options) {
const u8 = await this._toUint8Array(input, options);
return await (0, AbstractConverter_1._)().convert("base64", u8, (0, core_1.deleteStartLength)(options));
}
async _toText(input, options) {
const u8 = await this._toUint8Array(input, options);
const textHelper = await (0, StringUtil_1.getTextHelper)();
return await textHelper.bufferToText(u8, options);
}
async _toUint8Array(input, options) {
const startEnd = await this._getStartEnd(input, options);
let start = startEnd.start;
const end = startEnd.end;
const size = end - start;
const u8 = (0, Environment_1.newBuffer)(size);
for (; start < end; start++) {
const ai = input[start * 2];
const a = MAP_HEX[ai];
const bi = input[start * 2 + 1];
const b = MAP_HEX[bi];
if (a == null || b == null) {
break;
}
u8[start] = (a << 4) | b;
}
return u8;
}
}
exports.HexConverter = HexConverter;
//# sourceMappingURL=HexConverter.js.map