All files / src context.ts

100% Statements 26/26
100% Branches 5/5
100% Functions 5/5
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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62    14x 18x 18x             14x 6x 6x     14x           4x 9x 9x 9x 9x 3x   6x   5x       14x         3x 3x 1x 1x 1x   2x       14x 3x                    
import { Context, Des, Ser } from "./types";
 
export function createContext(size = 4096): Context {
  const buffer = new ArrayBuffer(size);
  return {
    i: 0,
    view: new DataView(buffer),
    bytes: new Uint8Array(buffer)
  };
}
 
export function growContext(ctx: Context) {
  ctx.bytes = new Uint8Array(ctx.bytes.length * 2);
  ctx.view = new DataView(ctx.bytes.buffer);
}
 
export function contextSer<T>(
  ctx: Context,
  ser: Ser<T>,
  data: T
): Uint8Array {
  // eslint-disable-next-line no-constant-condition
  while (true) {
    const limit = ctx.bytes.length - 8;
    ctx.i = 0;
    try {
      ser(ctx, data);
      if (ctx.i < limit) return ctx.bytes;
    } catch (error) {
      if (ctx.i < limit) throw error;
    }
    growContext(ctx);
  }
}
 
export function contextDes<T>(
  ctx: Context,
  des: Des<T>,
  bytes: Uint8Array
): T {
  const { length } = bytes;
  if (length < 4096) {
    ctx.bytes.set(bytes);
    ctx.i = 0;
    return des(ctx);
  } else {
    return des(contextFromBytes(bytes));
  }
}
 
export function contextFromBytes(array: Uint8Array): Context {
  return {
    i: 0,
    bytes: array,
    view: new DataView(
      array.buffer,
      array.byteOffset,
      array.byteLength
    )
  };
}