All files / src context.ts

100% Statements 37/37
100% Branches 7/7
100% Functions 6/6
100% Lines 33/33

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 68 69 70 71 72 73 74 75 76 77 78 79 80 81    19x 482x 482x             19x 11x 11x     19x           4x 9x 9x 9x 9x 3x   6x   5x       19x           3x 8x 8x 8x 8x 2x   6x   5x       19x         3x 3x 1x 1x 1x   2x       19x 5x                    
import { AsyncSer, 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
): void {
  // 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;
    } catch (error) {
      if (ctx.i < limit) throw error;
    }
    growContext(ctx);
  }
}
 
export async function asyncContextSer<T>(
  ctx: Context,
  ser: AsyncSer<T>,
  data: T
) {
  // eslint-disable-next-line no-constant-condition
  while (true) {
    const limit = ctx.bytes.length - 8;
    ctx.i = 0;
    try {
      await ser(ctx, data);
      if (ctx.i < limit) return;
    } catch (error) {
      if (ctx.i < limit) throw error;
    }
    growContext(ctx);
  }
}
 
export function contextDes<T>(
  ctx: Context,
  des: Des<T>,
  buf: Uint8Array
): T {
  const { length } = buf;
  if (length < 4096) {
    ctx.bytes.set(buf);
    ctx.i = 0;
    return des(ctx);
  } else {
    return des(contextFromBytes(buf));
  }
}
 
export function contextFromBytes(array: Uint8Array): Context {
  return {
    i: 0,
    bytes: array,
    view: new DataView(
      array.buffer,
      array.byteOffset,
      array.byteLength
    )
  };
}