UNPKG

univ-conv

Version:

The universal binary and text converter

73 lines 2.44 kB
import { decode } from "base64-arraybuffer"; import { AbstractConverter, _ } from "./AbstractConverter"; import { deleteStartLength, getStartEnd, hasNoStartLength, } from "./core"; import { isBrowser, newBufferFrom } from "./Environment"; import { getTextHelper } from "./StringUtil"; export class Base64Converter extends AbstractConverter { constructor() { super(...arguments); this.type = "base64"; } empty() { return ""; } is(input, options) { return typeof input === "string" && options.inputStringType === "base64"; } async _from(input, options) { const univConv = _()._find(input, options); return await univConv.toBase64(input, options); } async _getStartEnd(input, options) { const size = await this.size(input); return getStartEnd(options, size); } _isEmpty(input) { return !input; } async _merge(chunks, options) { if (isBrowser) { const blob = await _().merge("blob", chunks, options); return await this.from(blob); } else { const u8 = await _().merge("uint8array", chunks, options); return await this.from(u8); } } _size(input) { const len = input.length; const baseLen = (len * 3) / 4; let padding = 0; for (let i = len - 1; input[i] === "="; i--) { padding++; } const size = baseLen - padding; return Promise.resolve(size); } async _toArrayBuffer(input, options) { const ab = decode(input); if (hasNoStartLength(options)) { return ab; } const { start, end } = await this._getStartEnd(input, options); return ab.slice(start, end); } async _toBase64(input, options) { if (hasNoStartLength(options)) { return input; } const u8 = await this._toUint8Array(input, options); return await this._from(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 ab = await this._toArrayBuffer(input, options); return newBufferFrom(ab); } } //# sourceMappingURL=Base64Converter.js.map