UNPKG

univ-conv

Version:

The universal binary and text converter

65 lines 2.32 kB
import { encode } from "base64-arraybuffer"; import { AbstractConverter, _ } from "./AbstractConverter"; import { EMPTY_ARRAY_BUFFER, getStartEnd, hasNoStartLength, } from "./core"; import { hasBuffer, newBuffer, newBufferFrom } from "./Environment"; import { getTextHelper } from "./StringUtil"; const hasSharedArrayBuffer = typeof SharedArrayBuffer === "function"; export class ArrayBufferConverter extends AbstractConverter { constructor() { super(...arguments); this.type = "arraybuffer"; } empty() { return EMPTY_ARRAY_BUFFER; } is(input) { return (input instanceof ArrayBuffer || (hasSharedArrayBuffer && input instanceof SharedArrayBuffer)); } async _from(input, options) { const converter = _()._find(input, options); return await converter.toArrayBuffer(input, options); } _getStartEnd(input, options) { return Promise.resolve(getStartEnd(options, input.byteLength)); } _isEmpty(input) { return input.byteLength === 0; } _merge(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(newBufferFrom(chunk), pos); pos += chunk.byteLength; } return Promise.resolve(u8.buffer); } _size(input) { return Promise.resolve(input.byteLength); } async _toArrayBuffer(input, options) { if (hasNoStartLength(options)) { return input; } const { start, end } = await this._getStartEnd(input, options); return input.slice(start, end); } 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) { const ab = await this._toArrayBuffer(input, options); return hasBuffer ? Buffer.from(ab) : new Uint8Array(ab); } } //# sourceMappingURL=ArrayBufferConverter.js.map