All files / src/msgpack pack.ts

100% Statements 25/25
100% Branches 9/9
100% Functions 1/1
100% Lines 25/25

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 5319x   19x 19x 19x   19x             638808x   2x 2x   1x 1x   4x 4x     638801x   431315x 431310x   5x 5x   431309x   207463x 207461x   23x 11x 7x   12x             8x      
import { uint8 } from "..";
import { Context, Ser } from "../types";
import { packArray } from "./array";
import { packInt } from "./int";
import { packMap } from "./map";
 
export function pack(
  ctx: Context,
  data: unknown,
  floatHead: number,
  float: Ser<number>,
  str: Ser<string>
) {
  switch (data) {
    case null:
      uint8.ser(ctx, 0xc0);
      return;
    case false:
      uint8.ser(ctx, 0xc2);
      return;
    case true:
      uint8.ser(ctx, 0xc3);
      return;
  }
 
  switch (typeof data) {
    case "number":
      if (Number.isInteger(data)) {
        packInt(ctx, data);
      } else {
        uint8.ser(ctx, floatHead);
        float(ctx, data);
      }
      return;
    case "string":
      str(ctx, data);
      return;
    case "object":
      if (Array.isArray(data)) {
        packArray(ctx, data, floatHead, float, str);
        return;
      }
      packMap(
        ctx,
        data as Record<string | number, unknown>,
        floatHead,
        float,
        str
      );
      return;
  }
}