All files / json-pack/src/ion IonDecoderBase.ts

73.61% Statements 120/163
57.14% Branches 36/63
94.11% Functions 16/17
77.3% Lines 109/141

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 2894x 4x       4x   4x           2041x 2041x       122873x 122873x 122873x   122873x   2678x   5331x   2859x   2718x   20655x   68165x   5x   7998x   10433x   2031x             2678x                                       5331x 5331x 2695x         2859x 2859x   2844x 2844x 13385x   2844x       2718x 2718x   2718x 2718x 13314x   2718x       20655x 20655x 20655x 20655x         68165x   68165x 68165x 13488x     68165x   68154x       5x   5x 5x 1x     5x   4x       7998x   7998x 7998x 5214x     7998x   6699x 6699x   6699x 65474x     6699x       6699x       10433x   10433x 10433x 7880x     10433x   9484x 9484x   9484x 51197x 51197x 51197x 51197x     9484x       9484x       2031x       2031x 2031x 2021x     2031x 2031x     2031x 2031x     2031x         2031x       83863x     83863x 92491x 92491x     83863x                                                     51197x       51197x 51197x       51197x       2140x 2140x             2140x 2140x 2140x   2140x   2031x     2031x 2031x 2031x   2031x   2031x 2031x              
import {Reader} from '@jsonjoy.com/buffers/lib/Reader';
import sharedCachedUtf8Decoder from '@jsonjoy.com/buffers/lib/utf8/sharedCachedUtf8Decoder';
import type {CachedUtf8Decoder} from '@jsonjoy.com/buffers/lib/utf8/CachedUtf8Decoder';
import type {IReader, IReaderResettable} from '@jsonjoy.com/buffers/lib';
import {TYPE} from './constants';
import {Import} from './Import';
 
export class IonDecoderBase<R extends IReader & IReaderResettable = IReader & IReaderResettable> {
  public readonly reader: R;
  public readonly utf8Decoder: CachedUtf8Decoder;
  protected symbols?: Import;
 
  constructor(reader?: R) {
    this.reader = (reader ?? new Reader()) as R;
    this.utf8Decoder = sharedCachedUtf8Decoder;
  }
 
  public val(): unknown {
    const typedesc = this.reader.u8();
    const type = (typedesc >> 4) & 0xf;
    const length = typedesc & 0xf;
 
    switch (type) {
      case TYPE.NULL:
        return this.readNull(length);
      case TYPE.BOOL:
        return this.readBool(length);
      case TYPE.UINT:
        return this.readUint(length);
      case TYPE.NINT:
        return this.readNint(length);
      case TYPE.FLOT:
        return this.readFloat(length);
      case TYPE.STRI:
        return this.readString(length);
      case TYPE.BINA:
        return this.readBinary(length);
      case TYPE.LIST:
        return this.readList(length);
      case TYPE.STRU:
        return this.readStruct(length);
      case TYPE.ANNO:
        return this.readAnnotation(length);
      default:
        throw new Error(`Unknown Ion type: 0x${type.toString(16)}`);
    }
  }
 
  protected readNull(length: number): null {
    if (length === 15) return null;
    Iif (length === 0) {
      // NOP padding - skip bytes
      this.val(); // Read and discard next value
      return null;
    }
    Iif (length === 14) {
      // Extended length NOP padding
      const padLength = this.readVUint();
      this.reader.x += padLength;
      this.val(); // Read and discard next value
      return null;
    }
    // Regular NOP padding
    this.reader.x += length;
    this.val(); // Read and discard next value
    return null;
  }
 
  protected readBool(length: number): boolean | null {
    Iif (length === 15) return null;
    if (length === 0) return false;
    if (length === 1) return true;
    throw new Error(`Invalid bool length: ${length}`);
  }
 
  protected readUint(length: number): number | null {
    Iif (length === 15) return null;
    if (length === 0) return 0;
 
    let value = 0;
    for (let i = 0; i < length; i++) {
      value = value * 256 + this.reader.u8();
    }
    return value;
  }
 
  protected readNint(length: number): number | null {
    Iif (length === 15) return null;
    Iif (length === 0) throw new Error('Negative zero is illegal');
 
    let value = 0;
    for (let i = 0; i < length; i++) {
      value = value * 256 + this.reader.u8();
    }
    return -value;
  }
 
  protected readFloat(length: number): number | null {
    Iif (length === 15) return null;
    Iif (length === 0) return 0.0;
    Iif (length === 4) return this.reader.f32();
    if (length === 8) return this.reader.f64();
    throw new Error(`Unsupported float length: ${length}`);
  }
 
  protected readString(length: number): string | null {
    Iif (length === 15) return null;
 
    let actualLength = length;
    if (length === 14) {
      actualLength = this.readVUint();
    }
 
    if (actualLength === 0) return '';
 
    return this.reader.utf8(actualLength);
  }
 
  protected readBinary(length: number): Uint8Array | null {
    Iif (length === 15) return null;
 
    let actualLength = length;
    if (length === 14) {
      actualLength = this.readVUint();
    }
 
    if (actualLength === 0) return new Uint8Array(0);
 
    return this.reader.buf(actualLength);
  }
 
  protected readList(length: number): unknown[] | null {
    Iif (length === 15) return null;
 
    let actualLength = length;
    if (length === 14) {
      actualLength = this.readVUint();
    }
 
    if (actualLength === 0) return [];
 
    const endPos = this.reader.x + actualLength;
    const list: unknown[] = [];
 
    while (this.reader.x < endPos) {
      list.push(this.val());
    }
 
    Iif (this.reader.x !== endPos) {
      throw new Error('List parsing error: incorrect length');
    }
 
    return list;
  }
 
  protected readStruct(length: number): Record<string, unknown> | null {
    Iif (length === 15) return null;
 
    let actualLength = length;
    if (length === 14) {
      actualLength = this.readVUint();
    }
 
    if (actualLength === 0) return {};
 
    const endPos = this.reader.x + actualLength;
    const struct: Record<string, unknown> = {};
 
    while (this.reader.x < endPos) {
      const fieldNameId = this.readVUint();
      const fieldName = this.getSymbolText(fieldNameId);
      const fieldValue = this.val();
      struct[fieldName] = fieldValue;
    }
 
    Iif (this.reader.x !== endPos) {
      throw new Error('Struct parsing error: incorrect length');
    }
 
    return struct;
  }
 
  protected readAnnotation(length: number): unknown {
    Iif (length < 3) {
      throw new Error('Annotation wrapper must have at least 3 bytes');
    }
 
    let _actualLength = length;
    if (length === 14) {
      _actualLength = this.readVUint();
    }
 
    const annotLength = this.readVUint();
    const endAnnotPos = this.reader.x + annotLength;
 
    // Skip annotations for now - just read and ignore them
    while (this.reader.x < endAnnotPos) {
      this.readVUint(); // Skip annotation symbol ID
    }
 
    Iif (this.reader.x !== endAnnotPos) {
      throw new Error('Annotation parsing error: incorrect annotation length');
    }
 
    // Return the actual value, ignoring annotations
    return this.val();
  }
 
  protected readVUint(): number {
    let value = 0;
    let byte: number;
 
    do {
      byte = this.reader.u8();
      value = (value << 7) | (byte & 0x7f);
    } while ((byte & 0x80) === 0);
 
    return value;
  }
 
  protected readVInt(): number {
    const firstByte = this.reader.u8();
 
    // Single byte case
    Iif (firstByte & 0x80) {
      const sign = firstByte & 0x40 ? -1 : 1;
      const magnitude = firstByte & 0x3f;
      return sign * magnitude;
    }
 
    // Multi-byte case
    const sign = firstByte & 0x40 ? -1 : 1;
    let magnitude = firstByte & 0x3f;
    let byte: number;
 
    do {
      byte = this.reader.u8();
      magnitude = (magnitude << 7) | (byte & 0x7f);
    } while ((byte & 0x80) === 0);
 
    return sign * magnitude;
  }
 
  protected getSymbolText(symbolId: number): string {
    Iif (!this.symbols) {
      throw new Error('No symbol table available');
    }
 
    const symbol = this.symbols.getText(symbolId);
    Iif (symbol === undefined) {
      throw new Error(`Unknown symbol ID: ${symbolId}`);
    }
 
    return symbol;
  }
 
  protected validateBVM(): void {
    const bvm = this.reader.u32();
    Iif (bvm !== 0xe00100ea) {
      throw new Error(`Invalid Ion Binary Version Marker: 0x${bvm.toString(16)}`);
    }
  }
 
  protected readSymbolTable(): void {
    // Check if there's enough data and if the next byte indicates an annotation
    if (this.reader.x < this.reader.uint8.length) {
      const nextByte = this.reader.peak();
      const type = (nextByte >> 4) & 0xf;
 
      if (type === TYPE.ANNO) {
        // This might be a symbol table annotation
        const annotValue = this.val();
 
        // The annotated value should be a struct with a 'symbols' field
        if (annotValue && typeof annotValue === 'object' && !Array.isArray(annotValue)) {
          const symbolsKey = 'symbols'; // This is what symbol ID 7 maps to
          const obj = annotValue as Record<string, unknown>;
 
          if (symbolsKey in obj && Array.isArray(obj[symbolsKey])) {
            // Update the symbol table with new symbols
            const newSymbols = obj[symbolsKey] as string[];
            this.symbols = new Import(this.symbols || null, newSymbols);
          }
        }
      }
    }
  }
}