All files / buffers/src/utf8 isUtf8.ts

100% Statements 25/25
90.9% Branches 30/33
100% Functions 1/1
100% Lines 24/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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