isUtf8.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.isUtf8 = void 0;
  4. /**
  5. * Validates that the given data is valid UTF-8 text.
  6. * @param buf Data to check.
  7. * @returns True if the data is valid UTF-8.
  8. */
  9. const isUtf8 = (buf, from, length) => {
  10. const to = from + length;
  11. while (from < to) {
  12. const c = buf[from];
  13. if (c <= 0x7f) {
  14. from++;
  15. continue;
  16. }
  17. if (c >= 0xc2 && c <= 0xdf) {
  18. if (buf[from + 1] >> 6 === 2) {
  19. from += 2;
  20. continue;
  21. }
  22. else
  23. return false;
  24. }
  25. const c1 = buf[from + 1];
  26. if (((c === 0xe0 && c1 >= 0xa0 && c1 <= 0xbf) || (c === 0xed && c1 >= 0x80 && c1 <= 0x9f)) &&
  27. buf[from + 2] >> 6 === 2) {
  28. from += 3;
  29. continue;
  30. }
  31. if (((c >= 0xe1 && c <= 0xec) || (c >= 0xee && c <= 0xef)) && c1 >> 6 === 2 && buf[from + 2] >> 6 === 2) {
  32. from += 3;
  33. continue;
  34. }
  35. if (((c === 0xf0 && c1 >= 0x90 && c1 <= 0xbf) ||
  36. (c >= 0xf1 && c <= 0xf3 && c1 >> 6 === 2) ||
  37. (c === 0xf4 && c1 >= 0x80 && c1 <= 0x8f)) &&
  38. buf[from + 2] >> 6 === 2 &&
  39. buf[from + 3] >> 6 === 2) {
  40. from += 4;
  41. continue;
  42. }
  43. return false;
  44. }
  45. return true;
  46. };
  47. exports.isUtf8 = isUtf8;
  48. //# sourceMappingURL=isUtf8.js.map