UNPKG

univ-conv

Version:

The universal binary and text converter

68 lines 2.27 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TextHelper = void 0; require("fast-text-encoding"); const Environment_1 = require("./Environment"); const textEncoder = new TextEncoder(); const textDecoder = new TextDecoder(); 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 (0, Environment_1.newBufferFrom)(ab); } const ab = await this.convert(text, { to: bufCharset.toUpperCase(), from: "UNICODE", type: "arraybuffer", }); return (0, Environment_1.newBufferFrom)(ab); } async convert(data, options) { if (typeof this._convert === "undefined") { try { this._convert = (await Promise.resolve().then(() => require("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; } } exports.TextHelper = TextHelper; //# sourceMappingURL=TextHelper.js.map