univ-conv
Version:
The universal binary and text converter
88 lines • 3.12 kB
JavaScript
import { encode } from "base64-arraybuffer";
import { AbstractConverter, _ } from "./AbstractConverter";
import { EMPTY_UINT8_ARRAY, getStartEnd, hasNoStartLength, } from "./core";
import { hasBuffer, isBuffer, newBuffer, newBufferFrom } from "./Environment";
import { getTextHelper } from "./StringUtil";
export class Uint8ArrayConverter extends AbstractConverter {
constructor() {
super(...arguments);
this.type = "uint8array";
}
empty() {
return EMPTY_UINT8_ARRAY;
}
is(input) {
return input instanceof Uint8Array || isBuffer(input);
}
async _from(input, options) {
if (hasBuffer && typeof input === "string") {
const type = options.inputStringType;
let buffer;
if (type === "base64") {
buffer = Buffer.from(input, "base64");
}
else if (type === "binary") {
buffer = Buffer.from(input, "binary");
}
else if (type === "hex") {
buffer = Buffer.from(input, "hex");
}
else if (type === "text") {
const textHelper = await getTextHelper();
const u8 = await textHelper.textToBuffer(input, options);
buffer = u8;
}
if (buffer) {
const { start, end } = await this._getStartEnd(buffer, options);
return buffer.subarray(start, end);
}
}
const ab = await _().convert("arraybuffer", input, options);
return newBufferFrom(ab);
}
_getStartEnd(input, options) {
return Promise.resolve(getStartEnd(options, input.byteLength));
}
_isEmpty(input) {
return input.byteLength === 0;
}
_merge(chunks) {
if (hasBuffer) {
return Promise.resolve(Buffer.concat(chunks));
}
const byteLength = chunks.reduce((sum, chunk) => {
return sum + chunk.byteLength;
}, 0);
const u8 = newBuffer(byteLength);
let pos = 0;
for (const chunk of chunks) {
u8.set(chunk, pos);
pos += chunk.byteLength;
}
return Promise.resolve(u8);
}
_size(input) {
return Promise.resolve(input.byteLength);
}
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 encode(u8);
}
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) {
if (hasNoStartLength(options)) {
return input;
}
const { start, end } = await this._getStartEnd(input, options);
return input.subarray(start, end);
}
}
//# sourceMappingURL=Uint8ArrayConverter.js.map