All files / json-pack/src/cbor CborEncoderFast.ts

80.59% Statements 162/201
76.34% Branches 71/93
63.63% Functions 28/44
81.81% Lines 135/165

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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 32812x         12x           12x     55x     41647x 41645x       10448x   2788x   3212x   728x   3720x 3434x 3434x   1413x   2021x                     33x       4x                 282390x 8804x 8804x       953x 515x       438x 6x       515x 4x 4x       273586x 1681x       272337x 272337x 272337x 272337x 272337x 270152x 2185x 569x 569x 1616x 451x 451x 451x 1165x 308x 308x 308x   857x 857x 857x   272337x                                     2192x 2192x 2192x 2192x 2192x 2192x 298x 1894x 430x 430x 1464x 397x 397x 397x 1067x 235x 235x 235x   832x 832x 832x   2192x       2115x       49x 49x 49x       49x 49x 14x 6x 2x         80600x 80600x 80600x 80600x 80600x 80600x 80600x 71976x 60447x 60447x 60447x 11529x 6496x 6496x 6496x   5033x 5033x 5033x   80600x 80600x 71976x 11529x 5033x                                 6040x 6040x 280476x       6040x 6040x 18x 8x 2x         4479x 4479x 4479x 4479x 25914x 25914x 25914x         8564x 8564x 149x 4x           3x       5x       20x 20x       25x 25x 7x             48x 48x             3x                       2x                       22x                                              
import {Writer} from '@jsonjoy.com/buffers/lib/Writer';
import {CONST, MAJOR_OVERLAY} from './constants';
import type {IWriter, IWriterGrowable} from '@jsonjoy.com/buffers/lib';
import type {BinaryJsonEncoder, StreamingBinaryJsonEncoder, TlvBinaryJsonEncoder} from '../types';
 
const isSafeInteger = Number.isSafeInteger;
 
/**
 * Fast CBOR encoder supports only JSON values. Use regular `CborEncoder` if
 * you need ability to encode all CBOR value types.
 */
export class CborEncoderFast<W extends IWriter & IWriterGrowable = IWriter & IWriterGrowable>
  implements BinaryJsonEncoder, StreamingBinaryJsonEncoder, TlvBinaryJsonEncoder
{
  constructor(public readonly writer: W = new Writer() as any) {}
 
  public encode(value: unknown): Uint8Array {
    this.writeAny(value);
    return this.writer.flush();
  }
 
  public writeAny(value: unknown): void {
    switch (typeof value) {
      case 'number':
        return this.writeNumber(value as number);
      case 'string':
        return this.writeStr(value);
      case 'boolean':
        return this.writer.u8(0xf4 + +value);
      case 'object': {
        if (!value) return this.writer.u8(0xf6);
        const constr = value.constructor;
        switch (constr) {
          case Array:
            return this.writeArr(value as unknown[]);
          default:
            return this.writeObj(value as Record<string, unknown>);
        }
      }
    }
  }
 
  public writeCbor(): void {
    this.writer.u8u16(0xd9, 0xd9f7);
  }
 
  public writeEnd(): void {
    this.writer.u8(CONST.END);
  }
 
  public writeNull(): void {
    this.writer.u8(0xf6);
  }
 
  public writeBoolean(bool: boolean): void {
    if (bool) this.writer.u8(0xf5);
    else this.writer.u8(0xf4);
  }
 
  public writeNumber(num: number): void {
    if (isSafeInteger(num)) this.writeInteger(num);
    else Iif (typeof num === 'bigint') this.writeBigInt(num);
    else this.writeFloat(num);
  }
 
  public writeBigInt(int: bigint): void {
    if (int >= 0) this.writeBigUint(int);
    else this.writeBigSint(int);
  }
 
  public writeBigUint(uint: bigint): void {
    if (uint <= Number.MAX_SAFE_INTEGER) return this.writeUInteger(Number(uint));
    this.writer.u8u64(0x1b, uint);
  }
 
  public writeBigSint(int: bigint): void {
    if (int >= Number.MIN_SAFE_INTEGER) return this.encodeNint(Number(int));
    const uint = -BigInt(1) - int;
    this.writer.u8u64(0x3b, uint);
  }
 
  public writeInteger(int: number): void {
    if (int >= 0) this.writeUInteger(int);
    else this.encodeNint(int);
  }
 
  public writeUInteger(uint: number): void {
    const writer = this.writer;
    writer.ensureCapacity(9);
    const uint8 = writer.uint8;
    let x = writer.x;
    if (uint <= 23) {
      uint8[x++] = MAJOR_OVERLAY.UIN + uint;
    } else if (uint <= 0xff) {
      uint8[x++] = 0x18;
      uint8[x++] = uint;
    } else if (uint <= 0xffff) {
      uint8[x++] = 0x19;
      writer.view.setUint16(x, uint);
      x += 2;
    } else if (uint <= 0xffffffff) {
      uint8[x++] = 0x1a;
      writer.view.setUint32(x, uint);
      x += 4;
    } else {
      uint8[x++] = 0x1b;
      writer.view.setBigUint64(x, BigInt(uint));
      x += 8;
    }
    writer.x = x;
  }
 
  /** @deprecated Remove and use `writeNumber` instead. */
  public encodeNumber(num: number): void {
    this.writeNumber(num);
  }
 
  /** @deprecated Remove and use `writeInteger` instead. */
  public encodeInteger(int: number): void {
    this.writeInteger(int);
  }
 
  /** @deprecated */
  public encodeUint(uint: number): void {
    this.writeUInteger(uint);
  }
 
  public encodeNint(int: number): void {
    const uint = -1 - int;
    const writer = this.writer;
    writer.ensureCapacity(9);
    const uint8 = writer.uint8;
    let x = writer.x;
    if (uint < 24) {
      uint8[x++] = MAJOR_OVERLAY.NIN + uint;
    } else if (uint <= 0xff) {
      uint8[x++] = 0x38;
      uint8[x++] = uint;
    } else if (uint <= 0xffff) {
      uint8[x++] = 0x39;
      writer.view.setUint16(x, uint);
      x += 2;
    } else if (uint <= 0xffffffff) {
      uint8[x++] = 0x3a;
      writer.view.setUint32(x, uint);
      x += 4;
    } else {
      uint8[x++] = 0x3b;
      writer.view.setBigUint64(x, BigInt(uint));
      x += 8;
    }
    writer.x = x;
  }
 
  public writeFloat(float: number): void {
    this.writer.u8f64(0xfb, float);
  }
 
  public writeBin(buf: Uint8Array): void {
    const length = buf.length;
    this.writeBinHdr(length);
    this.writer.buf(buf, length);
  }
 
  public writeBinHdr(length: number): void {
    const writer = this.writer;
    if (length <= 23) writer.u8(MAJOR_OVERLAY.BIN + length);
    else if (length <= 0xff) writer.u16((0x58 << 8) + length);
    else if (length <= 0xffff) writer.u8u16(0x59, length);
    else if (length <= 0xffffffff) writer.u8u32(0x5a, length);
    else Ewriter.u8u64(0x5b, length);
  }
 
  public writeStr(str: string): void {
    const writer = this.writer;
    const length = str.length;
    const maxSize = length * 4;
    writer.ensureCapacity(5 + maxSize);
    const uint8 = writer.uint8;
    let lengthOffset: number = writer.x;
    if (maxSize <= 23) writer.x++;
    else if (maxSize <= 0xff) {
      uint8[writer.x++] = 0x78;
      lengthOffset = writer.x;
      writer.x++;
    } else if (maxSize <= 0xffff) {
      uint8[writer.x++] = 0x79;
      lengthOffset = writer.x;
      writer.x += 2;
    } else {
      uint8[writer.x++] = 0x7a;
      lengthOffset = writer.x;
      writer.x += 4;
    }
    const bytesWritten = writer.utf8(str);
    if (maxSize <= 23) uint8[lengthOffset] = MAJOR_OVERLAY.STR + bytesWritten;
    else if (maxSize <= 0xff) uint8[lengthOffset] = bytesWritten;
    else if (maxSize <= 0xffff) writer.view.setUint16(lengthOffset, bytesWritten);
    else writer.view.setUint32(lengthOffset, bytesWritten);
  }
 
  public writeStrHdr(length: number): void {
    const writer = this.writer;
    if (length <= 23) writer.u8(MAJOR_OVERLAY.STR + length);
    else if (length <= 0xff) writer.u16((0x78 << 8) + length);
    else if (length <= 0xffff) writer.u8u16(0x79, length);
    else writer.u8u32(0x7a, length);
  }
 
  public writeAsciiStr(str: string): void {
    this.writeStrHdr(str.length);
    this.writer.ascii(str);
  }
 
  public writeArr(arr: unknown[]): void {
    const length = arr.length;
    this.writeArrHdr(length);
    for (let i = 0; i < length; i++) this.writeAny(arr[i]);
  }
 
  public writeArrHdr(length: number): void {
    const writer = this.writer;
    if (length <= 23) writer.u8(MAJOR_OVERLAY.ARR + length);
    else if (length <= 0xff) writer.u16((0x98 << 8) + length);
    else if (length <= 0xffff) writer.u8u16(0x99, length);
    else if (length <= 0xffffffff) writer.u8u32(0x9a, length);
    else Ewriter.u8u64(0x9b, length);
  }
 
  public writeObj(obj: Record<string, unknown>): void {
    const keys = Object.keys(obj);
    const length = keys.length;
    this.writeObjHdr(length);
    for (let i = 0; i < length; i++) {
      const key = keys[i];
      this.writeStr(key);
      this.writeAny(obj[key]);
    }
  }
 
  public writeObjHdr(length: number): void {
    const writer = this.writer;
    if (length <= 23) writer.u8(MAJOR_OVERLAY.MAP + length);
    else if (length <= 0xff) writer.u16((0xb8 << 8) + length);
    else if (length <= 0xffff) writer.u8u16(0xb9, length);
    else Eif (length <= 0xffffffff) writer.u8u32(0xba, length);
    else writer.u8u64(0xbb, length);
  }
 
  public writeMapHdr(length: number): void {
    this.writeObjHdr(length);
  }
 
  public writeStartMap(): void {
    this.writer.u8(0xbf);
  }
 
  public writeTag(tag: number, value: unknown): void {
    this.writeTagHdr(tag);
    this.writeAny(value);
  }
 
  public writeTagHdr(tag: number): void {
    const writer = this.writer;
    if (tag <= 23) writer.u8(MAJOR_OVERLAY.TAG + tag);
    else if (tag <= 0xff) writer.u16((0xd8 << 8) + tag);
    else Eif (tag <= 0xffff) writer.u8u16(0xd9, tag);
    else if (tag <= 0xffffffff) writer.u8u32(0xda, tag);
    else writer.u8u64(0xdb, tag);
  }
 
  public writeTkn(value: number): void {
    const writer = this.writer;
    if (value <= 23) writer.u8(MAJOR_OVERLAY.TKN + value);
    else Eif (value <= 0xff) writer.u16((0xf8 << 8) + value);
  }
 
  // ------------------------------------------------------- Streaming encoding
 
  public writeStartStr(): void {
    this.writer.u8(0x7f);
  }
 
  public writeStrChunk(str: string): void {
    throw new Error('Not implemented');
  }
 
  public writeEndStr(): void {
    throw new Error('Not implemented');
  }
 
  public writeStartBin(): void {
    this.writer.u8(0x5f);
  }
 
  public writeBinChunk(buf: Uint8Array): void {
    throw new Error('Not implemented');
  }
 
  public writeEndBin(): void {
    throw new Error('Not implemented');
  }
 
  public writeStartArr(): void {
    this.writer.u8(0x9f);
  }
 
  public writeArrChunk(item: unknown): void {
    throw new Error('Not implemented');
  }
 
  public writeEndArr(): void {
    this.writer.u8(CONST.END);
  }
 
  public writeStartObj(): void {
    this.writer.u8(0xbf);
  }
 
  public writeObjChunk(key: string, value: unknown): void {
    throw new Error('Not implemented');
  }
 
  public writeEndObj(): void {
    this.writer.u8(CONST.END);
  }
}