All files / json-pack/src/msgpack MsgPackEncoder.ts

95.45% Statements 21/22
90.9% Branches 10/11
100% Functions 1/1
94.44% Lines 17/18

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 4012x 12x 12x 12x             12x       271235x   148x   61x   404x   270622x 268721x   198053x   67794x   2874x 2867x 2853x 2845x              
import {MsgPackEncoderFast} from './MsgPackEncoderFast';
import {isUint8Array} from '@jsonjoy.com/buffers/lib/isUint8Array';
import {JsonPackExtension} from '../JsonPackExtension';
import {JsonPackValue} from '../JsonPackValue';
import {MSGPACK} from './constants';
import type {IWriter, IWriterGrowable} from '@jsonjoy.com/buffers/lib';
 
/**
 * @category Encoder
 */
export class MsgPackEncoder<
  W extends IWriter & IWriterGrowable = IWriter & IWriterGrowable,
> extends MsgPackEncoderFast<W> {
  public writeAny(value: unknown): void {
    switch (value) {
      case null:
        return this.writer.u8(MSGPACK.NULL);
      case false:
        return this.writer.u8(MSGPACK.FALSE);
      case true:
        return this.writer.u8(MSGPACK.TRUE);
    }
    if (value instanceof Array) return this.encodeArray(value);
    switch (typeof value) {
      case 'number':
        return this.encodeNumber(value);
      case 'string':
        return this.encodeString(value);
      case 'object': {
        if (value instanceof JsonPackValue) return this.writer.buf(value.val, value.val.length);
        if (value instanceof JsonPackExtension) return this.encodeExt(value);
        if (isUint8Array(value)) return this.encodeBinary(value);
        return this.encodeObject(value as Record<string, unknown>);
      }
      case 'undefined':
        return this.writer.u8(MSGPACK.UNDEFINED);
    }
  }
}