decoder.js 2.1 KB

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