All files / json-pack/src/resp RespDecoder.ts

83.65% Statements 220/263
77.61% Branches 52/67
79.41% Functions 27/34
85.89% Lines 201/234

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 4275x   5x     5x   5x                     139x   139x     2268x 2268x                               2942168x 2942168x 2942029x   44007x   40921x   1699835x   38x   101109x   29932x   567939x   456979x   1205x   10x   7x   10x   12x   11x   14x           1030796x 1030796x 1030796x 2067081x 2066986x 1036285x         3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 4x 4x   3x           101109x 101109x 101102x 101088x           44007x 44007x 44007x 44000x 44000x 9004x 34996x 44000x 170448x 170433x 43985x 43979x   126448x         40921x 40921x 40921x 477648x 477622x 40895x 40895x 40895x 40895x   80x   5x   5x   70x   20033x 5x   20028x   40880x 40879x         7x 7x 7x 35x 35x 7x 7x 7x 7x 7x             1699835x 1699835x 1699835x 17659188x 17658252x 1698899x 1698899x 1698899x 1698899x 1698811x         42x 42x 1x 1x   41x   41x 39x 41x 41x       3x 3x 3x 3x 3x 3x       1205x 1205x 1196x 1183x 1183x 1183x 1137x 1130x                   12x 12x 12x 60x 56x 8x 8x 8x 8x 7x         11x 11x 8x 7x 5x           456989x 456989x 456967x 1x 1x   456966x 456926x 456926x 456320x       10x 10x 20x 10x           567953x 567863x 567863x 1312073x 1311269x   563518x                   13758x 13758x 13758x   342x   100x   8196x   28x   398x   118x   2712x   1842x   22x                                   398x       342x 342x 1470x 342x 342x         100x 100x 514x 100x 100x                           8196x 8196x 81040x 8196x 8196x         28x 28x       28x       22x 22x                                   1842x 1842x 1842x       1842x 1842x                 2712x 2712x 6006x 6006x        
import {Reader} from '@jsonjoy.com/buffers/lib/Reader';
import {RESP} from './constants';
import {RespAttributes, RespPush} from './extensions';
import type {IReader, IReaderResettable} from '@jsonjoy.com/buffers/lib';
import type {BinaryJsonDecoder, PackValue} from '../types';
import {isUtf8} from '@jsonjoy.com/buffers/lib/utf8/isUtf8';
 
export class RespDecoder<R extends IReader & IReaderResettable = IReader & IReaderResettable>
  implements BinaryJsonDecoder
{
  /**
   * When set to true, the decoder will attempt to decode RESP Bulk strings
   * (which are binary strings, i.e. Uint8Array) as UTF-8 strings. If the
   * string is not valid UTF-8, it will be returned as a Uint8Array.
   *
   * You can toggle this setting at any time, before each call to `decode()`
   * or `read()`, or other methods.
   */
  public tryUtf8 = false;
 
  public constructor(public reader: R = new Reader() as any) {}
 
  public read(uint8: Uint8Array): PackValue {
    this.reader.reset(uint8);
    return this.readAny() as PackValue;
  }
 
  /** @deprecated */
  public decode(uint8: Uint8Array): unknown {
    this.reader.reset(uint8);
    return this.readAny();
  }
 
  // -------------------------------------------------------- Any value reading
 
  public val(): unknown {
    return this.readAny();
  }
 
  public readAny(): unknown {
    const reader = this.reader;
    const type = reader.u8();
    switch (type) {
      case RESP.INT:
        return this.readInt();
      case RESP.FLOAT:
        return this.readFloat();
      case RESP.STR_SIMPLE:
        return this.readStrSimple();
      case RESP.STR_BULK:
        return this.readStrBulk();
      case RESP.BOOL:
        return this.readBool();
      case RESP.NULL:
        return reader.skip(2), null;
      case RESP.OBJ:
        return this.readObj();
      case RESP.ARR:
        return this.readArr();
      case RESP.STR_VERBATIM:
        return this.readStrVerbatim();
      case RESP.PUSH:
        return new RespPush(this.readArr() || []);
      case RESP.BIG:
        return this.readBigint();
      case RESP.SET:
        return this.readSet();
      case RESP.ERR_SIMPLE:
        return this.readErrSimple();
      case RESP.ERR_BULK:
        return this.readErrBulk();
      case RESP.ATTR:
        return new RespAttributes(this.readObj());
    }
    throw new Error('UNKNOWN_TYPE');
  }
 
  protected readLength(): number {
    const reader = this.reader;
    let number: number = 0;
    while (true) {
      const c = reader.u8();
      if (c === RESP.R) return reader.skip(1), number;
      number = number * 10 + (c - 48);
    }
  }
 
  public readCmd(): [cmd: string, ...args: Uint8Array[]] {
    const reader = this.reader;
    const type = reader.u8();
    Iif (type !== RESP.ARR) throw new Error('INVALID_COMMAND');
    const c = reader.peak();
    Iif (c === RESP.MINUS) throw new Error('INVALID_COMMAND');
    const length = this.readLength();
    Iif (length === 0) throw new Error('INVALID_COMMAND');
    const cmd = this.readAsciiAsStrBulk().toUpperCase();
    const args: [cmd: string, ...args: Uint8Array[]] = [cmd];
    this.tryUtf8 = false;
    for (let i = 1; i < length; i++) {
      const type = reader.u8();
      Iif (type !== RESP.STR_BULK) throw new Error('INVALID_COMMAND');
      args.push(this.readStrBulk() as Uint8Array);
    }
    return args;
  }
 
  // ---------------------------------------------------------- Boolean reading
 
  public readBool(): boolean {
    const reader = this.reader;
    const c = reader.u8();
    reader.skip(2); // Skip "\r\n".
    return c === 116; // t
  }
 
  // ----------------------------------------------------------- Number reading
 
  public readInt(): number {
    const reader = this.reader;
    let negative = false;
    let c = reader.u8();
    let number: number = 0;
    if (c === RESP.MINUS) {
      negative = true;
    } else if (c !== RESP.PLUS) number = c - 48;
    while (true) {
      c = reader.u8();
      if (c === RESP.R) {
        reader.skip(1); // Skip "\n".
        return negative ? -number : number;
      }
      number = number * 10 + (c - 48);
    }
  }
 
  public readFloat(): number {
    const reader = this.reader;
    const x = reader.x;
    while (true) {
      const c = reader.u8();
      if (c !== RESP.R) continue;
      const length = reader.x - x - 1;
      reader.x = x;
      const str = reader.ascii(length);
      switch (length) {
        case 3:
          switch (str) {
            case 'inf':
              return reader.skip(2), Infinity;
            case 'nan':
              return reader.skip(2), NaN;
          }
          break;
        case 4:
          if (str === '-inf') {
            return reader.skip(2), -Infinity;
          }
          break;
      }
      reader.skip(2); // Skip "\n".
      return Number(str);
    }
  }
 
  public readBigint(): bigint {
    const reader = this.reader;
    const x = reader.x;
    while (true) {
      const c = reader.u8();
      if (c !== RESP.R) continue;
      const length = reader.x - x;
      reader.x = x;
      const str = reader.ascii(length);
      reader.skip(1); // Skip "\n".
      return BigInt(str);
    }
  }
 
  // ----------------------------------------------------------- String reading
 
  public readStrSimple(): string {
    const reader = this.reader;
    const x = reader.x;
    while (true) {
      const c = reader.u8();
      if (c !== RESP.R) continue;
      const size = reader.x - x - 1;
      reader.x = x;
      const str = reader.utf8(size);
      reader.skip(2); // Skip "\r\n".
      return str;
    }
  }
 
  public readStrBulk(): Uint8Array | string | null {
    const reader = this.reader;
    if (reader.peak() === RESP.MINUS) {
      reader.skip(4); // Skip "-1\r\n".
      return null;
    }
    const length = this.readLength();
    let res: Uint8Array | string;
    if (this.tryUtf8 && isUtf8(reader.uint8, reader.x, length)) res = reader.utf8(length);
    else res = reader.buf(length);
    reader.skip(2); // Skip "\r\n".
    return res;
  }
 
  public readAsciiAsStrBulk(): string {
    const reader = this.reader;
    reader.skip(1); // Skip "$".
    const length = this.readLength();
    const buf = reader.ascii(length);
    reader.skip(2); // Skip "\r\n".
    return buf;
  }
 
  public readStrVerbatim(): string | Uint8Array {
    const reader = this.reader;
    const length = this.readLength();
    const u32 = reader.u32();
    const isTxt = u32 === 1954051130; // "txt:"
    if (isTxt) {
      const str = reader.utf8(length - 4);
      reader.skip(2); // Skip "\r\n".
      return str;
    }
    const buf = reader.buf(length - 4);
    reader.skip(2); // Skip "\r\n".
    return buf;
  }
 
  // ------------------------------------------------------------ Error reading
 
  public readErrSimple(): Error {
    const reader = this.reader;
    const x = reader.x;
    while (true) {
      const c = reader.u8();
      if (c !== RESP.R) continue;
      const size = reader.x - x - 1;
      reader.x = x;
      const str = reader.utf8(size);
      reader.skip(2); // Skip "\r\n".
      return new Error(str);
    }
  }
 
  public readErrBulk(): Error {
    const reader = this.reader;
    const length = this.readLength();
    const message = reader.utf8(length);
    reader.skip(2); // Skip "\r\n".
    return new Error(message);
  }
 
  // ------------------------------------------------------------ Array reading
 
  public readArr(): unknown[] | null {
    const reader = this.reader;
    const c = reader.peak();
    if (c === RESP.MINUS) {
      reader.skip(4); // Skip "-1\r\n".
      return null;
    }
    const length = this.readLength();
    const arr: unknown[] = [];
    for (let i = 0; i < length; i++) arr.push(this.readAny());
    return arr;
  }
 
  public readSet(): Set<unknown> {
    const length = this.readLength();
    const set = new Set();
    for (let i = 0; i < length; i++) set.add(this.readAny());
    return set;
  }
 
  // ----------------------------------------------------------- Object reading
 
  public readObj(): Record<string, unknown> {
    const length = this.readLength();
    const obj: Record<string, unknown> = {};
    for (let i = 0; i < length; i++) {
      const key = this.readAny() + '';
      obj[key] = this.readAny();
    }
    return obj;
  }
 
  // ----------------------------------------------------------------- Skipping
 
  public skipN(n: number): void {
    for (let i = 0; i < n; i++) this.skipAny();
  }
 
  public skipAny(): void {
    const reader = this.reader;
    const type = reader.u8();
    switch (type) {
      case RESP.INT:
        return this.skipInt();
      case RESP.FLOAT:
        return this.skipFloat();
      case RESP.STR_SIMPLE:
        return this.skipStrSimple();
      case RESP.STR_BULK:
        return this.skipStrBulk();
      case RESP.BOOL:
        return this.skipBool();
      case RESP.NULL:
        return reader.skip(2);
      case RESP.OBJ:
        return this.skipObj();
      case RESP.ARR:
        return this.skipArr();
      case RESP.STR_VERBATIM:
        return this.skipStrVerbatim();
      case RESP.PUSH:
        return this.skipArr();
      case RESP.BIG:
        return this.skipBigint();
      case RESP.SET:
        return this.skipSet();
      case RESP.ERR_SIMPLE:
        return this.skipErrSimple();
      case RESP.ERR_BULK:
        return this.skipErrBulk();
      case RESP.ATTR:
        return this.skipObj();
    }
    throw new Error('UNKNOWN_TYPE');
  }
 
  public skipBool(): void {
    this.reader.skip(3);
  }
 
  public skipInt(): void {
    const reader = this.reader;
    while (true) {
      if (reader.u8() !== RESP.R) continue;
      reader.skip(1); // Skip "\n".
      return;
    }
  }
 
  public skipFloat(): void {
    const reader = this.reader;
    while (true) {
      if (reader.u8() !== RESP.R) continue;
      reader.skip(1); // Skip "\n".
      return;
    }
  }
 
  public skipBigint(): void {
    const reader = this.reader;
    while (true) {
      Iif (reader.u8() !== RESP.R) continue;
      reader.skip(1); // Skip "\n".
      return;
    }
  }
 
  public skipStrSimple(): void {
    const reader = this.reader;
    while (true) {
      if (reader.u8() !== RESP.R) continue;
      reader.skip(1); // Skip "\n".
      return;
    }
  }
 
  public skipStrBulk(): void {
    const reader = this.reader;
    Iif (reader.peak() === RESP.MINUS) {
      reader.skip(4); // Skip "-1\r\n".
      return;
    }
    reader.skip(this.readLength() + 2); // Skip "\r\n".
  }
 
  public skipStrVerbatim(): void {
    const length = this.readLength();
    this.reader.skip(length + 2); // Skip "\r\n".
  }
 
  public skipErrSimple(): void {
    const reader = this.reader;
    while (true) {
      Iif (reader.u8() !== RESP.R) continue;
      reader.skip(1); // Skip "\n".
      return;
    }
  }
 
  public skipErrBulk(): void {
    const length = this.readLength();
    this.reader.skip(length + 2); // Skip "\r\n".
  }
 
  public skipArr(): void {
    const reader = this.reader;
    const c = reader.peak();
    Iif (c === RESP.MINUS) {
      reader.skip(4); // Skip "-1\r\n".
      return;
    }
    const length = this.readLength();
    for (let i = 0; i < length; i++) this.skipAny();
  }
 
  public skipSet(): void {
    const length = this.readLength();
    for (let i = 0; i < length; i++) this.skipAny();
  }
 
  public skipObj(): void {
    const length = this.readLength();
    for (let i = 0; i < length; i++) {
      this.skipAny();
      this.skipAny();
    }
  }
}