All files / json-size msgpackSizeFast.ts

100% Statements 31/31
100% Branches 9/9
100% Functions 3/3
100% Lines 21/21

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 431x 1x   1x 2x 11x 2x     1x 4x   13x 4x                         1x 39x 36x   6x   7x   6x   17x 15x 10x 7x 4x    
import {JsonPackExtension, JsonPackValue} from '@jsonjoy.com/json-pack/lib/msgpack';
import {isUint8Array} from '@jsonjoy.com/util/lib/buffers/isUint8Array';
 
const arraySize = (arr: unknown[]): number => {
  let size = 2;
  for (let i = arr.length - 1; i >= 0; i--) size += msgpackSizeFast(arr[i]);
  return size;
};
 
const objectSize = (obj: Record<string, unknown>): number => {
  let size = 2;
  // biome-ignore lint: object hasOwnProperty check is intentional, Object.hasOwn is too recent
  for (const key in obj) if (obj.hasOwnProperty(key)) size += 2 + key.length + msgpackSizeFast(obj[key]);
  return size;
};
 
/**
 * Same as `jsonSizeFast`, but for MessagePack.
 *
 * - Allows Buffers or Uint8Arrays a MessagePack `bin` values. Adds 5 bytes overhead for them.
 * - Allows embedded `JsonPackValue` values.
 * - Allows MessagePack `JsonPackExtension` extensions. Adds 6 bytes overhead for them.
 *
 * @param value MessagePack value, which can contain binary data, extensions and embedded MessagePack.
 * @returns Approximate size of the value in bytes.
 */
export const msgpackSizeFast = (value: unknown): number => {
  if (value === null) return 1;
  switch (typeof value) {
    case 'number':
      return 9;
    case 'string':
      return 4 + value.length;
    case 'boolean':
      return 1;
  }
  if (value instanceof Array) return arraySize(value);
  if (isUint8Array(value)) return 5 + value.length;
  if (value instanceof JsonPackValue) return (value as JsonPackValue).val.length;
  if (value instanceof JsonPackExtension) return 6 + (value as JsonPackExtension).val.length;
  return objectSize(value as Record<string, unknown>);
};