You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

is-utf8.js 2.4KB

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