decoder.js 2.1 KB

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