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

91.9% Statements 227/247
92% Branches 92/100
97.14% Functions 34/35
90.64% Lines 184/203

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 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430  17x 17x       17x           117x 117x 117x 117x   117x             117x 117x         117x 117x 197856x 197856x 197856x   117x                                   35540x     38620x       38353x 38353x 38353x     2183x 2103x   543x 482x   19364x 19293x   6849x 4220x   6600x 6276x   2293x 2248x   521x 332x         27286x 8858x   8180x   386x   57x   46x   61x   128x             2183x 1089x   182x   145x   133x   549x   80x             548x 498x   13x 2x         12x 12x 12x 12x 6x 5x           19369x 19312x   17x 2x         17x 17x 17x 17x 6x 5x           6848x 6803x   87x 16x             6600x 6543x   22x 25x 17x 13x   7x             521x 465x 455x           2293x   10x 10x   36x 36x   30x 30x   359x 359x   1858x 45x                                     1963x 1963x 1963x 1963x 1963x 1263x 1263x           86x 86x                   86x 85x 85x 85x   14x   18x   53x                   33x 26x 26x     6x   20x         6x 6x 6x 4x 4x           18x 15x 3x       12x 12x 18x 12x 11x 8x   2x       3x 3x 4x 4x 3x 1x 1x                 14x 11x 1x       10x 18x 2x       1x 3x               223x 223x 223x 219x 219x 13x                   13x           58x       116x       49x       74x 74x 73x 67x 93x 93x 27x     6x 10x 10x 5x     1x       34x 34x 33x 26x 23x 22x   7x 8x 7x   6x 4x       53x 83x 83x 27x   44x      
import {CONST, ERROR, MAJOR} from './constants';
import {CborDecoderBase} from './CborDecoderBase';
import {JsonPackValue} from '../JsonPackValue';
import type {Path} from '@jsonjoy.com/json-pointer';
import type {IReader, IReaderResettable} from '@jsonjoy.com/buffers';
 
export class CborDecoder<
  R extends IReader & IReaderResettable = IReader & IReaderResettable,
> extends CborDecoderBase<R> {
  // -------------------------------------------------------------- Map reading
 
  public readAsMap(): Map<unknown, unknown> {
    const octet = this.reader.u8();
    const major = octet >> 5;
    const minor = octet & CONST.MINOR_MASK;
    switch (major) {
      case MAJOR.MAP:
        return this.readMap(minor);
      default:
        throw ERROR.UNEXPECTED_MAJOR;
    }
  }
 
  public readMap(minor: number): Map<unknown, unknown> {
    const length = this.readMinorLen(minor);
    if (length >= 0) return this.readMapRaw(length);
    else Ereturn this.readMapIndef();
  }
 
  public readMapRaw(length: number): Map<unknown, unknown> {
    const map: Map<unknown, unknown> = new Map();
    for (let i = 0; i < length; i++) {
      const key = this.readAny();
      const value = this.readAny();
      map.set(key, value);
    }
    return map;
  }
 
  public readMapIndef(): Map<unknown, unknown> {
    const map: Map<unknown, unknown> = new Map();
    while (this.reader.peak() !== CONST.END) {
      const key = this.readAny();
      if (this.reader.peak() === CONST.END) throw ERROR.UNEXPECTED_OBJ_BREAK;
      const value = this.readAny();
      map.set(key, value);
    }
    this.reader.x++;
    return map;
  }
 
  // ----------------------------------------------------------- Value skipping
 
  public skipN(n: number): void {
    for (let i = 0; i < n; i++) this.skipAny();
  }
  public skipAny(): void {
    this.skipAnyRaw(this.reader.u8());
  }
 
  public skipAnyRaw(octet: number): void {
    const major = octet >> 5;
    const minor = octet & CONST.MINOR_MASK;
    switch (major) {
      case MAJOR.UIN:
      case MAJOR.NIN:
        this.skipUNint(minor);
        break;
      case MAJOR.BIN:
        this.skipBin(minor);
        break;
      case MAJOR.STR:
        this.skipStr(minor);
        break;
      case MAJOR.ARR:
        this.skipArr(minor);
        break;
      case MAJOR.MAP:
        this.skipObj(minor);
        break;
      case MAJOR.TKN:
        this.skipTkn(minor);
        break;
      case MAJOR.TAG:
        this.skipTag(minor);
        break;
    }
  }
 
  public skipMinorLen(minor: number): number {
    if (minor <= 23) return minor;
    switch (minor) {
      case 24:
        return this.reader.u8();
      case 25:
        return this.reader.u16();
      case 26:
        return this.reader.u32();
      case 27:
        return Number(this.reader.u64());
      case 31:
        return -1;
      default:
        throw ERROR.UNEXPECTED_MINOR;
    }
  }
 
  // --------------------------------------------------------- Integer skipping
 
  public skipUNint(minor: number): void {
    if (minor <= 23) return;
    switch (minor) {
      case 24:
        return this.reader.skip(1);
      case 25:
        return this.reader.skip(2);
      case 26:
        return this.reader.skip(4);
      case 27:
        return this.reader.skip(8);
      default:
        throw ERROR.UNEXPECTED_MINOR;
    }
  }
 
  // ---------------------------------------------------------- Binary skipping
 
  public skipBin(minor: number): void {
    const length = this.skipMinorLen(minor);
    if (length >= 0) this.reader.skip(length);
    else {
      while (this.reader.peak() !== CONST.END) this.skipBinChunk();
      this.reader.x++;
    }
  }
 
  public skipBinChunk(): void {
    const octet = this.reader.u8();
    const major = octet >> 5;
    const minor = octet & CONST.MINOR_MASK;
    if (major !== MAJOR.BIN) throw ERROR.UNEXPECTED_BIN_CHUNK_MAJOR;
    if (minor > 27) throw ERROR.UNEXPECTED_BIN_CHUNK_MINOR;
    this.skipBin(minor);
  }
 
  // ---------------------------------------------------------- String skipping
 
  public skipStr(minor: number): void {
    const length = this.skipMinorLen(minor);
    if (length >= 0) this.reader.skip(length);
    else {
      while (this.reader.peak() !== CONST.END) this.skipStrChunk();
      this.reader.x++;
    }
  }
 
  public skipStrChunk(): void {
    const octet = this.reader.u8();
    const major = octet >> 5;
    const minor = octet & CONST.MINOR_MASK;
    if (major !== MAJOR.STR) throw ERROR.UNEXPECTED_STR_CHUNK_MAJOR;
    if (minor > 27) throw ERROR.UNEXPECTED_STR_CHUNK_MINOR;
    this.skipStr(minor);
  }
 
  // ----------------------------------------------------------- Array skipping
 
  public skipArr(minor: number): void {
    const length = this.skipMinorLen(minor);
    if (length >= 0) this.skipN(length);
    else {
      while (this.reader.peak() !== CONST.END) this.skipAny();
      this.reader.x++;
    }
  }
 
  // ---------------------------------------------------------- Object skipping
 
  public skipObj(minor: number): void {
    const length = this.readMinorLen(minor);
    if (length >= 0) return this.skipN(length * 2);
    else {
      while (this.reader.peak() !== CONST.END) {
        this.skipAny();
        if (this.reader.peak() === CONST.END) throw ERROR.UNEXPECTED_OBJ_BREAK;
        this.skipAny();
      }
      this.reader.x++;
    }
  }
 
  // ------------------------------------------------------------- Tag skipping
 
  public skipTag(minor: number): void {
    const length = this.skipMinorLen(minor);
    if (length < 0) throw ERROR.UNEXPECTED_MINOR;
    this.skipAny();
  }
 
  // ----------------------------------------------------------- Token skipping
 
  public skipTkn(minor: number): void {
    switch (minor) {
      case 0xf8 & CONST.MINOR_MASK:
        this.reader.skip(1);
        return;
      case 0xf9 & CONST.MINOR_MASK:
        this.reader.skip(2);
        return;
      case 0xfa & CONST.MINOR_MASK:
        this.reader.skip(4);
        return;
      case 0xfb & CONST.MINOR_MASK:
        this.reader.skip(8);
        return;
    }
    if (minor <= 23) return;
    throw ERROR.UNEXPECTED_MINOR;
  }
 
  // --------------------------------------------------------------- Validation
 
  /**
   * Throws if at given offset in a buffer there is an invalid CBOR value, or
   * if the value does not span the exact length specified in `size`. I.e.
   * throws if:
   *
   * - The value is not a valid CBOR value.
   * - The value is shorter than `size`.
   * - The value is longer than `size`.
   *
   * @param value Buffer in which to validate CBOR value.
   * @param offset Offset at which the value starts.
   * @param size Expected size of the value.
   */
  public validate(value: Uint8Array, offset: number = 0, size: number = value.length): void {
    const reader = this.reader;
    reader.reset(value);
    reader.x = offset;
    const start = offset;
    this.skipAny();
    const end = reader.x;
    if (end - start !== size) throw ERROR.INVALID_SIZE;
  }
 
  // -------------------------------------------- One level reading - any value
 
  public decodeLevel(value: Uint8Array): unknown {
    this.reader.reset(value);
    return this.readLevel();
  }
 
  /**
   * Decodes only one level of objects and arrays. Other values are decoded
   * completely.
   *
   * @returns One level of decoded CBOR value.
   */
  public readLevel(): unknown {
    const octet = this.reader.u8();
    const major = octet >> 5;
    const minor = octet & CONST.MINOR_MASK;
    switch (major) {
      case MAJOR.ARR:
        return this.readArrLevel(minor);
      case MAJOR.MAP:
        return this.readObjLevel(minor);
      default:
        return super.readAnyRaw(octet);
    }
  }
 
  /**
   * Decodes primitive values, returns container values as `JsonPackValue`.
   *
   * @returns A primitive value, or CBOR container value as a blob.
   */
  public readPrimitiveOrVal(): unknown | JsonPackValue {
    const octet = this.reader.peak();
    const major = octet >> 5;
    switch (major) {
      case MAJOR.ARR:
      case MAJOR.MAP:
        return this.readAsValue();
      default:
        return this.readAny();
    }
  }
 
  public readAsValue(): JsonPackValue {
    const reader = this.reader;
    const start = reader.x;
    this.skipAny();
    const end = reader.x;
    return new JsonPackValue(reader.uint8.subarray(start, end));
  }
 
  // ----------------------------------------------- One level reading - object
 
  public readObjLevel(minor: number): Record<string, unknown> {
    const length = this.readMinorLen(minor);
    if (length >= 0) return this.readObjRawLevel(length);
    else return this.readObjIndefLevel();
  }
 
  public readObjRawLevel(length: number): Record<string, unknown> {
    const obj: Record<string, unknown> = {};
    for (let i = 0; i < length; i++) {
      const key = this.key();
      if (key === '__proto__') throw ERROR.UNEXPECTED_OBJ_KEY;
      const value = this.readPrimitiveOrVal();
      obj[key] = value;
    }
    return obj;
  }
 
  public readObjIndefLevel(): Record<string, unknown> {
    const obj: Record<string, unknown> = {};
    while (this.reader.peak() !== CONST.END) {
      const key = this.key();
      if (key === '__proto__') throw ERROR.UNEXPECTED_OBJ_KEY;
      if (this.reader.peak() === CONST.END) throw ERROR.UNEXPECTED_OBJ_BREAK;
      const value = this.readPrimitiveOrVal();
      obj[key] = value;
    }
    this.reader.x++;
    return obj;
  }
 
  // ------------------------------------------------ One level reading - array
 
  public readArrLevel(minor: number): unknown[] {
    const length = this.readMinorLen(minor);
    if (length >= 0) return this.readArrRawLevel(length);
    return this.readArrIndefLevel();
  }
 
  public readArrRawLevel(length: number): unknown[] {
    const arr: unknown[] = [];
    for (let i = 0; i < length; i++) arr.push(this.readPrimitiveOrVal());
    return arr;
  }
 
  public readArrIndefLevel(): unknown[] {
    const arr: unknown[] = [];
    while (this.reader.peak() !== CONST.END) arr.push(this.readPrimitiveOrVal());
    this.reader.x++;
    return arr;
  }
 
  // ---------------------------------------------------------- Shallow reading
 
  public readHdr(expectedMajor: number): number {
    const octet = this.reader.u8();
    const major = octet >> 5;
    if (major !== expectedMajor) throw ERROR.UNEXPECTED_MAJOR;
    const minor = octet & CONST.MINOR_MASK;
    if (minor < 24) return minor;
    switch (minor) {
      case 24:
        return this.reader.u8();
      case 25:
        return this.reader.u16();
      case 26:
        return this.reader.u32();
      case 27:
        return Number(this.reader.u64());
      case 31:
        return -1;
    }
    throw ERROR.UNEXPECTED_MINOR;
  }
 
  public readStrHdr(): number {
    return this.readHdr(MAJOR.STR);
  }
 
  public readObjHdr(): number {
    return this.readHdr(MAJOR.MAP);
  }
 
  public readArrHdr(): number {
    return this.readHdr(MAJOR.ARR);
  }
 
  public findKey(key: string): this {
    const reader = this.reader;
    const size = this.readObjHdr();
    if (size >= 0) {
      for (let i = 0; i < size; i++) {
        const k = this.key();
        if (k === key) return this;
        this.skipAny();
      }
    } else {
      while (reader.peak() !== CONST.END) {
        const k = this.key();
        if (k === key) return this;
        this.skipAny();
      }
    }
    throw ERROR.KEY_NOT_FOUND;
  }
 
  public findIndex(index: number): this {
    const reader = this.reader;
    const size = this.readArrHdr();
    if (size >= 0) {
      if (index >= size) throw ERROR.INDEX_OUT_OF_BOUNDS;
      for (let i = 0; i < index; i++) this.skipAny();
      return this;
    }
    for (let i = 0; i < index; i++) {
      if (reader.peak() === CONST.END) throw ERROR.INDEX_OUT_OF_BOUNDS;
      this.skipAny();
    }
    if (reader.peak() === CONST.END) throw ERROR.INDEX_OUT_OF_BOUNDS;
    return this;
  }
 
  public find(path: Path): this {
    for (let i = 0; i < path.length; i++) {
      const segment = path[i];
      if (typeof segment === 'string') this.findKey(segment);
      else this.findIndex(segment);
    }
    return this;
  }
}