All files / base64/src createToBase64Bin.ts

84.78% Statements 39/46
64.28% Branches 9/14
100% Functions 3/3
86.04% Lines 37/43

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 47 48 49 50 51 52 53 54 55 56 57 58 592x   2x 3x   192x 3x   3x 192x 12288x 12288x       3x 3x 3x   3x 300x 300x 300x 5007x 5007x 5007x 5007x 5007x 5007x 5007x   300x 101x 101x 101x 101x         199x 91x 91x 91x 91x 91x 91x 91x               300x      
import {alphabet} from './constants';
 
export const createToBase64Bin = (chars: string = alphabet, pad: string = '=') => {
  Iif (chars.length !== 64) throw new Error('chars must be 64 characters long');
 
  const table = chars.split('').map((c) => c.charCodeAt(0));
  const table2: number[] = [];
 
  for (const c1 of table) {
    for (const c2 of table) {
      const two = (c1 << 8) + c2;
      table2.push(two);
    }
  }
 
  const doAddPadding = pad.length === 1;
  const E: number = doAddPadding ? pad.charCodeAt(0) : 0;
  const EE: number = doAddPadding ? (E << 8) | E : 0;
 
  return (uint8: Uint8Array, start: number, length: number, dest: DataView, offset: number): number => {
    const extraLength = length % 3;
    const baseLength = length - extraLength;
    for (; start < baseLength; start += 3) {
      const o1 = uint8[start];
      const o2 = uint8[start + 1];
      const o3 = uint8[start + 2];
      const v1 = (o1 << 4) | (o2 >> 4);
      const v2 = ((o2 & 0b1111) << 8) | o3;
      dest.setInt32(offset, (table2[v1] << 16) + table2[v2]);
      offset += 4;
    }
    if (extraLength === 1) {
      const o1 = uint8[baseLength];
      if (doAddPadding) {
        dest.setInt32(offset, (table2[o1 << 4] << 16) + EE);
        offset += 4;
      } else E{
        dest.setInt16(offset, table2[o1 << 4]);
        offset += 2;
      }
    } else if (extraLength) {
      const o1 = uint8[baseLength];
      const o2 = uint8[baseLength + 1];
      const v1 = (o1 << 4) | (o2 >> 4);
      const v2 = (o2 & 0b1111) << 2;
      if (doAddPadding) {
        dest.setInt32(offset, (table2[v1] << 16) + (table[v2] << 8) + E);
        offset += 4;
      } else E{
        dest.setInt16(offset, table2[v1]);
        offset += 2;
        dest.setInt8(offset, table[v2]);
        offset += 1;
      }
    }
    return offset;
  };
};