All files / src/common_serdes string.ts

100% Statements 21/21
100% Branches 2/2
100% Functions 3/3
100% Lines 19/19

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 16x   241592x   241592x 241591x 241591x 241591x 241586x 241586x   241586x   335x 333x   333x   1x   333x 333x 333x   20708x    
import { define } from "../define";
import { StringFactory } from "../types";
 
export const string: StringFactory = (encoding, headSd) =>
  define(
    (ctx, data) => {
      const head = ctx.i;
      // approximated payload length (unfavorable for ucs2, good enough for utf8, perfect for latin1)
      headSd.ser(ctx, data.length);
      const begin = ctx.i;
      const headSize = begin - head;
      encoding.encode(ctx, data);
      const end = ctx.i;
      const size = end - begin;
      // stop if approximation is correct
      if (size === data.length) return;
      // write actual header after payload
      headSd.ser(ctx, size);
      const requiredHeadSize = ctx.i - end;
      // check if approximated header size is wrong
      if (headSize !== requiredHeadSize) {
        // if yes, shift the payload
        ctx.bytes.copyWithin(head + requiredHeadSize, begin, end);
      }
      ctx.i = head;
      headSd.ser(ctx, size);
      ctx.i = end + (requiredHeadSize - headSize);
    },
    (ctx) => encoding.decode(ctx, headSd.des(ctx))
  );