validate_utf8.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.validateUtf8 = void 0;
  4. var FIRST_BIT = 0x80;
  5. var FIRST_TWO_BITS = 0xc0;
  6. var FIRST_THREE_BITS = 0xe0;
  7. var FIRST_FOUR_BITS = 0xf0;
  8. var FIRST_FIVE_BITS = 0xf8;
  9. var TWO_BIT_CHAR = 0xc0;
  10. var THREE_BIT_CHAR = 0xe0;
  11. var FOUR_BIT_CHAR = 0xf0;
  12. var CONTINUING_CHAR = 0x80;
  13. /**
  14. * Determines if the passed in bytes are valid utf8
  15. * @param bytes - An array of 8-bit bytes. Must be indexable and have length property
  16. * @param start - The index to start validating
  17. * @param end - The index to end validating
  18. */
  19. function validateUtf8(bytes, start, end) {
  20. var continuation = 0;
  21. for (var i = start; i < end; i += 1) {
  22. var byte = bytes[i];
  23. if (continuation) {
  24. if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) {
  25. return false;
  26. }
  27. continuation -= 1;
  28. }
  29. else if (byte & FIRST_BIT) {
  30. if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) {
  31. continuation = 1;
  32. }
  33. else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) {
  34. continuation = 2;
  35. }
  36. else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) {
  37. continuation = 3;
  38. }
  39. else {
  40. return false;
  41. }
  42. }
  43. }
  44. return !continuation;
  45. }
  46. exports.validateUtf8 = validateUtf8;
  47. //# sourceMappingURL=validate_utf8.js.map