| 1 |
/** @define {boolean} */ |
| 2 |
const WITH_TEXT_ENCODER_POLYFILL = goog.define("WITH_TEXT_ENCODER_POLYFILL", false); |
| 3 |
|
| 4 |
/** @constructor */ |
| 5 |
function TextEncoderPoly() { |
| 6 |
this.encoding = "utf8"; |
| 7 |
return this; |
| 8 |
} |
| 9 |
|
| 10 |
TextEncoderPoly.prototype.encode = function (string_) { |
| 11 |
if (typeof string_ !== "string") { |
| 12 |
throw new TypeError("passed argument must be of type string " + string_ + " " + typeof string_); |
| 13 |
} |
| 14 |
const binstr = unescape(encodeURIComponent(string_)); |
| 15 |
const array = new Uint8Array(binstr.length); |
| 16 |
[...binstr].forEach(function (char, index) { |
| 17 |
array[index] = char.codePointAt(0); |
| 18 |
}); |
| 19 |
return array; |
| 20 |
}; |
| 21 |
|
| 22 |
/** @constructor */ |
| 23 |
function TextDecoderPoly() { |
| 24 |
this.encoding = "utf-8"; |
| 25 |
this.ignoreBOM = false; |
| 26 |
|
| 27 |
this.trimNull = (a) => { |
| 28 |
const c = a.indexOf("\0"); |
| 29 |
if (c > -1) { |
| 30 |
return a.slice(0, Math.max(0, c)); |
| 31 |
} |
| 32 |
return a; |
| 33 |
}; |
| 34 |
|
| 35 |
this.decode = function (view, options) { |
| 36 |
if (typeof view === "undefined") { |
| 37 |
return ""; |
| 38 |
} |
| 39 |
|
| 40 |
const stream = typeof options !== "undefined" && "stream" in options ? options.stream : false; |
| 41 |
if (typeof stream !== "boolean") { |
| 42 |
throw new TypeError("stream option must be boolean"); |
| 43 |
} |
| 44 |
|
| 45 |
if (!ArrayBuffer.isView(view)) { |
| 46 |
throw new TypeError("passed argument must be an array buffer view"); |
| 47 |
} else { |
| 48 |
const array = new Uint8Array(view.buffer, view.byteOffset, view.byteLength); |
| 49 |
const charArray = Array.from({ length: array.length }); |
| 50 |
array.forEach(function (charcode, index) { |
| 51 |
charArray[index] = String.fromCodePoint(charcode); |
| 52 |
}); |
| 53 |
return this.trimNull(charArray.join("")); |
| 54 |
} |
| 55 |
}; |
| 56 |
} |
| 57 |
|
| 58 |
export const decoder = WITH_TEXT_ENCODER_POLYFILL ? new TextDecoderPoly() : new TextDecoder("utf8"); |
| 59 |
|
| 60 |
export const encoder = WITH_TEXT_ENCODER_POLYFILL ? new TextEncoderPoly() : new TextEncoder("utf8"); |
| 61 |
|
| 62 |
export const uint2String = (uint) => decoder.decode(uint); |