decoder.js 1.3 KB

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