is-utf8.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. function isUTF8(bytes) {
  2. var i = 0;
  3. while (i < bytes.length) {
  4. if ((// ASCII
  5. bytes[i] == 0x09 ||
  6. bytes[i] == 0x0A ||
  7. bytes[i] == 0x0D ||
  8. (0x20 <= bytes[i] && bytes[i] <= 0x7E)
  9. )
  10. ) {
  11. i += 1;
  12. continue;
  13. }
  14. if ((// non-overlong 2-byte
  15. (0xC2 <= bytes[i] && bytes[i] <= 0xDF) &&
  16. (0x80 <= bytes[i + 1] && bytes[i + 1] <= 0xBF)
  17. )
  18. ) {
  19. i += 2;
  20. continue;
  21. }
  22. if ((// excluding overlongs
  23. bytes[i] == 0xE0 &&
  24. (0xA0 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&
  25. (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF)
  26. ) ||
  27. (// straight 3-byte
  28. ((0xE1 <= bytes[i] && bytes[i] <= 0xEC) ||
  29. bytes[i] == 0xEE ||
  30. bytes[i] == 0xEF) &&
  31. (0x80 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&
  32. (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF)
  33. ) ||
  34. (// excluding surrogates
  35. bytes[i] == 0xED &&
  36. (0x80 <= bytes[i + 1] && bytes[i + 1] <= 0x9F) &&
  37. (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF)
  38. )
  39. ) {
  40. i += 3;
  41. continue;
  42. }
  43. if ((// planes 1-3
  44. bytes[i] == 0xF0 &&
  45. (0x90 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&
  46. (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) &&
  47. (0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF)
  48. ) ||
  49. (// planes 4-15
  50. (0xF1 <= bytes[i] && bytes[i] <= 0xF3) &&
  51. (0x80 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&
  52. (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) &&
  53. (0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF)
  54. ) ||
  55. (// plane 16
  56. bytes[i] == 0xF4 &&
  57. (0x80 <= bytes[i + 1] && bytes[i + 1] <= 0x8F) &&
  58. (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) &&
  59. (0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF)
  60. )
  61. ) {
  62. i += 4;
  63. continue;
  64. }
  65. return false;
  66. }
  67. return true;
  68. }