All files / src context.ts

100% Statements 29/29
100% Branches 8/8
100% Functions 5/5
100% Lines 27/27

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 63 64 65 66 67    19x 25x 25x             19x 15x 15x     19x           49x 63x 63x 63x 63x 48x   15x   14x       19x         50x 50x 44x 44x   6x   50x 48x 2x     46x     19x 7x                    
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 && !(error instanceof RangeError)) 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;
  } else {
    ctx = contextFromBytes(bytes);
  }
  const data = des(ctx);
  if (ctx.i !== length)
    throw RangeError(
      `Expected to process ${length} bytes, processed ${ctx.i} bytes instead`
    );
  return data;
}
 
export function contextFromBytes(array: Uint8Array): Context {
  return {
    i: 0,
    bytes: array,
    view: new DataView(
      array.buffer,
      array.byteOffset,
      array.byteLength
    )
  };
}