UNPKG

univ-conv

Version:

The universal binary and text converter

64 lines 2.06 kB
import "fast-text-encoding"; import { newBufferFrom } from "./Environment"; const textEncoder = new TextEncoder(); const textDecoder = new TextDecoder(); export class TextHelper { async bufferToText(u8, options) { const bufCharset = options.bufferToTextCharset; if (bufCharset === "utf8") { return textDecoder.decode(u8); } if (bufCharset === "utf16le") { return String.fromCharCode.apply(null, Array.from(u8)); } return await this.convert(u8, { to: "UNICODE", from: bufCharset.toUpperCase(), type: "string", }); } async textToBuffer(text, options) { const bufCharset = options.textToBufferCharset; if (bufCharset === "utf8") { return textEncoder.encode(text); } if (bufCharset === "utf16le") { const ab = this.textToUtf16leBuffer(text); return newBufferFrom(ab); } const ab = await this.convert(text, { to: bufCharset.toUpperCase(), from: "UNICODE", type: "arraybuffer", }); return newBufferFrom(ab); } async convert(data, options) { if (typeof this._convert === "undefined") { try { this._convert = (await import("encoding-japanese")).convert; } catch { this._convert = null; } } if (!this._convert) { throw new Error(`Illegal encoding: from=${options.from}, to=${options.to}`); } if (typeof data === "string") { return this.convert(data, options); } else { return this.convert(data, options); } } textToUtf16leBuffer(text) { const ab = new ArrayBuffer(text.length * 2); const u16 = new Uint16Array(ab); for (let i = 0, strLen = text.length; i < strLen; i++) { u16[i] = text.charCodeAt(i); } return ab; } } //# sourceMappingURL=TextHelper.js.map