All files / util/src/strings utf8.ts

100% Statements 17/17
100% Branches 9/9
100% Functions 1/1
100% Lines 15/15

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              3x 5830x 5830x 5830x 5830x 2944739x 2944739x 2926439x   2926439x 18300x   5727x 9x 9x   5727x     5830x    
/**
 * Given a JavaScript string, computes how many bytes it will take to encode
 * that string in UTF-8.
 *
 * @param str JavaScript string.
 * @returns Length in bytes if encoded as UTF-8.
 */
export function utf8Size(str: string): number {
  const length = str.length;
  let size = 0;
  let pos = 0;
  while (pos < length) {
    let value = str.charCodeAt(pos++);
    if ((value & 0xffffff80) === 0) {
      size++;
      // biome-ignore lint: keep this continue
      continue;
    } else if ((value & 0xfffff800) === 0) size += 2;
    else {
      if (value >= 0xd800 && value <= 0xdbff && pos < length) {
        const extra = str.charCodeAt(pos);
        if ((extra & 0xfc00) === 0xdc00) value = (pos++, ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000);
      }
      size += 3 + +((value & 0xffff0000) !== 0);
    }
  }
  return size;
}