All files / src asyncUse.ts

100% Statements 16/16
100% Branches 2/2
100% Functions 3/3
100% Lines 16/16

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 3119x     19x 1x 1x     2x 13x 13x 13x 13x 13x 1x 1x     12x 1x     11x       1x        
import { contextFromArray, createContext } from "./context";
import { AsyncConverter, AsyncTyper } from "./types";
 
export function asyncUse<T>(type: AsyncTyper<T>): AsyncConverter<T> {
  let size = 64;
  return {
    async encode(data) {
      // eslint-disable-next-line no-constant-condition
      while (true) {
        const ctx = createContext(size);
        const limit = ctx.bytes.length - 8;
        try {
          ctx.i = 0;
          await type.encode(ctx, data);
          if (ctx.i < limit) {
            return ctx.bytes.subarray(0, ctx.i);
          }
        } catch (error) {
          if (ctx.i < limit) {
            throw error;
          }
        }
        size = ctx.i * 2;
      }
    },
    decode(array: Uint8Array) {
      return type.decode(contextFromArray(array));
    }
  };
}