All files / src use.ts

100% Statements 15/15
100% Branches 2/2
100% Functions 3/3
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 30 31 32 33 3419x             19x 1x 1x     2x 9x 9x 9x 9x 1x 1x     8x 1x     7x       1x        
import {
  contextFromArray,
  createContext,
  growContext
} from "./context";
import { Converter, Typer } from "./types";
 
export function use<T>(type: Typer<T>): Converter<T> {
  const ctx = createContext(1024);
  return {
    encode(data) {
      // eslint-disable-next-line no-constant-condition
      while (true) {
        const limit = ctx.bytes.length - 8;
        try {
          ctx.i = 0;
          type.encode(ctx, data);
          if (ctx.i < limit) {
            return ctx.bytes.subarray(0, ctx.i);
          }
        } catch (error) {
          if (ctx.i < limit) {
            throw error;
          }
        }
        growContext(ctx);
      }
    },
    decode(array: Uint8Array) {
      return type.decode(contextFromArray(array));
    }
  };
}