univ-conv
Version:
The universal binary and text converter
103 lines • 3.04 kB
JavaScript
import { AbstractConverter, _ } from "./AbstractConverter";
import { deleteStartLength, getStartEnd, hasNoStartLength, } from "./core";
import { newBuffer } from "./Environment";
import { getTextHelper } from "./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,
};
export class HexConverter extends 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 (hasNoStartLength(options)) {
return input;
}
const { start, end } = await this._getStartEnd(input, options);
return input.slice(start * 2, end ? end * 2 : undefined);
}
const u8 = await _().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(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 _().convert("base64", u8, deleteStartLength(options));
}
async _toText(input, options) {
const u8 = await this._toUint8Array(input, options);
const textHelper = await 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 = 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;
}
}
//# sourceMappingURL=HexConverter.js.map