decoder.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.decode = decode;
  6. function con(b) {
  7. if ((b & 0xc0) === 0x80) {
  8. return b & 0x3f;
  9. } else {
  10. throw new Error("invalid UTF-8 encoding");
  11. }
  12. }
  13. function code(min, n) {
  14. if (n < min || 0xd800 <= n && n < 0xe000 || n >= 0x10000) {
  15. throw new Error("invalid UTF-8 encoding");
  16. } else {
  17. return n;
  18. }
  19. }
  20. function decode(bytes) {
  21. return _decode(bytes).map(function (x) {
  22. return String.fromCharCode(x);
  23. }).join("");
  24. }
  25. function _decode(bytes) {
  26. var result = [];
  27. while (bytes.length > 0) {
  28. var b1 = bytes[0];
  29. if (b1 < 0x80) {
  30. result.push(code(0x0, b1));
  31. bytes = bytes.slice(1);
  32. continue;
  33. }
  34. if (b1 < 0xc0) {
  35. throw new Error("invalid UTF-8 encoding");
  36. }
  37. var b2 = bytes[1];
  38. if (b1 < 0xe0) {
  39. result.push(code(0x80, ((b1 & 0x1f) << 6) + con(b2)));
  40. bytes = bytes.slice(2);
  41. continue;
  42. }
  43. var b3 = bytes[2];
  44. if (b1 < 0xf0) {
  45. result.push(code(0x800, ((b1 & 0x0f) << 12) + (con(b2) << 6) + con(b3)));
  46. bytes = bytes.slice(3);
  47. continue;
  48. }
  49. var b4 = bytes[3];
  50. if (b1 < 0xf8) {
  51. result.push(code(0x10000, (((b1 & 0x07) << 18) + con(b2) << 12) + (con(b3) << 6) + con(b4)));
  52. bytes = bytes.slice(4);
  53. continue;
  54. }
  55. throw new Error("invalid UTF-8 encoding");
  56. }
  57. return result;
  58. }