decoder.js (2201B)
1 "use strict"; 2 3 Object.defineProperty(exports, "__esModule", { 4 value: true 5 }); 6 exports.decode = decode; 7 8 function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } 9 10 function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } 11 12 function con(b) { 13 if ((b & 0xc0) === 0x80) { 14 return b & 0x3f; 15 } else { 16 throw new Error("invalid UTF-8 encoding"); 17 } 18 } 19 20 function code(min, n) { 21 if (n < min || 0xd800 <= n && n < 0xe000 || n >= 0x10000) { 22 throw new Error("invalid UTF-8 encoding"); 23 } else { 24 return n; 25 } 26 } 27 28 function decode(bytes) { 29 return _decode(bytes).map(function (x) { 30 return String.fromCharCode(x); 31 }).join(""); 32 } 33 34 function _decode(bytes) { 35 if (bytes.length === 0) { 36 return []; 37 } 38 /** 39 * 1 byte 40 */ 41 42 43 { 44 var _bytes = _toArray(bytes), 45 b1 = _bytes[0], 46 bs = _bytes.slice(1); 47 48 if (b1 < 0x80) { 49 return [code(0x0, b1)].concat(_toConsumableArray(_decode(bs))); 50 } 51 52 if (b1 < 0xc0) { 53 throw new Error("invalid UTF-8 encoding"); 54 } 55 } 56 /** 57 * 2 bytes 58 */ 59 60 { 61 var _bytes2 = _toArray(bytes), 62 _b = _bytes2[0], 63 b2 = _bytes2[1], 64 _bs = _bytes2.slice(2); 65 66 if (_b < 0xe0) { 67 return [code(0x80, ((_b & 0x1f) << 6) + con(b2))].concat(_toConsumableArray(_decode(_bs))); 68 } 69 } 70 /** 71 * 3 bytes 72 */ 73 74 { 75 var _bytes3 = _toArray(bytes), 76 _b2 = _bytes3[0], 77 _b3 = _bytes3[1], 78 b3 = _bytes3[2], 79 _bs2 = _bytes3.slice(3); 80 81 if (_b2 < 0xf0) { 82 return [code(0x800, ((_b2 & 0x0f) << 12) + (con(_b3) << 6) + con(b3))].concat(_toConsumableArray(_decode(_bs2))); 83 } 84 } 85 /** 86 * 4 bytes 87 */ 88 89 { 90 var _bytes4 = _toArray(bytes), 91 _b4 = _bytes4[0], 92 _b5 = _bytes4[1], 93 _b6 = _bytes4[2], 94 b4 = _bytes4[3], 95 _bs3 = _bytes4.slice(4); 96 97 if (_b4 < 0xf8) { 98 return [code(0x10000, (((_b4 & 0x07) << 18) + con(_b5) << 12) + (con(_b6) << 6) + con(b4))].concat(_toConsumableArray(_decode(_bs3))); 99 } 100 } 101 throw new Error("invalid UTF-8 encoding"); 102 }