All files / json-pack/src/json JsonEncoder.ts

78.94% Statements 135/171
77.77% Branches 28/36
35.48% Functions 11/31
79.01% Lines 128/162

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 29113x       13x 113x     49806x 49806x 49806x 49806x                         453621x   19831x   24339x   138991x   270456x 263873x 263873x   172240x   91564x   63x   6x 5x 5x       4x               6888x       4x 4x 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x       20532x 18598x 1934x       27163x 27163x                               59x 59x 59x   59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x       468480x 468480x 468480x 468480x 446604x 446604x 446604x 446604x 446604x 4697321x 4697321x     5539x 5539x   4697321x 17607x 17607x 17607x 17607x 17607x 4679714x   428997x 428997x 428997x   21876x 21876x 21876x                                                 91564x 91564x 91564x 91564x 91564x 18914x 18914x   91564x 91564x               169523x 169523x 169523x 169523x 163111x 163111x 323468x 323468x 323468x 323468x 323468x 323468x   163111x                                                                                                                          
import {toBase64Bin} from '@jsonjoy.com/base64/lib/toBase64Bin';
import type {IWriter, IWriterGrowable} from '@jsonjoy.com/buffers/lib';
import type {BinaryJsonEncoder, StreamingBinaryJsonEncoder} from '../types';
 
export class JsonEncoder implements BinaryJsonEncoder, StreamingBinaryJsonEncoder {
  constructor(public readonly writer: IWriter & IWriterGrowable) {}
 
  public encode(value: unknown): Uint8Array {
    const writer = this.writer;
    writer.reset();
    this.writeAny(value);
    return writer.flush();
  }
 
  /**
   * Called when the encoder encounters a value that it does not know how to encode.
   *
   * @param value Some JavaScript value.
   */
  public writeUnknown(value: unknown): void {
    this.writeNull();
  }
 
  public writeAny(value: unknown): void {
    switch (typeof value) {
      case 'boolean':
        return this.writeBoolean(value);
      case 'number':
        return this.writeNumber(value as number);
      case 'string':
        return this.writeStr(value);
      case 'object': {
        if (value === null) return this.writeNull();
        const constr = value.constructor;
        switch (constr) {
          case Object:
            return this.writeObj(value as Record<string, unknown>);
          case Array:
            return this.writeArr(value as unknown[]);
          case Uint8Array:
            return this.writeBin(value as Uint8Array);
          default:
            if (value instanceof Uint8Array) return this.writeBin(value);
            Iif (Array.isArray(value)) return this.writeArr(value);
            return this.writeUnknown(value);
        }
      }
      case 'undefined': {
        return this.writeUndef();
      }
      default:
        return this.writeUnknown(value);
    }
  }
 
  public writeNull(): void {
    this.writer.u32(0x6e756c6c); // null
  }
 
  public writeUndef(): void {
    const writer = this.writer;
    const length = 35;
    writer.ensureCapacity(length);
    // Write: "data:application/cbor,base64;9w=="
    const view = writer.view;
    let x = writer.x;
    view.setUint32(x, 0x22_64_61_74); // "dat
    x += 4;
    view.setUint32(x, 0x61_3a_61_70); // a:ap
    x += 4;
    view.setUint32(x, 0x70_6c_69_63); // plic
    x += 4;
    view.setUint32(x, 0x61_74_69_6f); // atio
    x += 4;
    view.setUint32(x, 0x6e_2f_63_62); // n/cb
    x += 4;
    view.setUint32(x, 0x6f_72_2c_62); // or,b
    x += 4;
    view.setUint32(x, 0x61_73_65_36); // ase6
    x += 4;
    view.setUint32(x, 0x34_3b_39_77); // 4;9w
    x += 4;
    view.setUint16(x, 0x3d_3d); // ==
    x += 2;
    writer.uint8[x++] = 0x22; // "
    writer.x = x;
  }
 
  public writeBoolean(bool: boolean): void {
    if (bool)
      this.writer.u32(0x74727565); // true
    else this.writer.u8u32(0x66, 0x616c7365); // false
  }
 
  public writeNumber(num: number): void {
    const str = num.toString();
    this.writer.ascii(str);
  }
 
  public writeInteger(int: number): void {
    this.writeNumber(int >> 0 === int ? int : Math.trunc(int));
  }
 
  public writeUInteger(uint: number): void {
    this.writeInteger(uint < 0 ? -uint : uint);
  }
 
  public writeFloat(float: number): void {
    this.writeNumber(float);
  }
 
  public writeBin(buf: Uint8Array): void {
    const writer = this.writer;
    const length = buf.length;
    writer.ensureCapacity(38 + 3 + (length << 1));
    // Write: "data:application/octet-stream;base64, - 22 64 61 74 61 3a 61 70 70 6c 69 63 61 74 69 6f 6e 2f 6f 63 74 65 74 2d 73 74 72 65 61 6d 3b 62 61 73 65 36 34 2c
    const view = writer.view;
    let x = writer.x;
    view.setUint32(x, 0x22_64_61_74); // "dat
    x += 4;
    view.setUint32(x, 0x61_3a_61_70); // a:ap
    x += 4;
    view.setUint32(x, 0x70_6c_69_63); // plic
    x += 4;
    view.setUint32(x, 0x61_74_69_6f); // atio
    x += 4;
    view.setUint32(x, 0x6e_2f_6f_63); // n/oc
    x += 4;
    view.setUint32(x, 0x74_65_74_2d); // tet-
    x += 4;
    view.setUint32(x, 0x73_74_72_65); // stre
    x += 4;
    view.setUint32(x, 0x61_6d_3b_62); // am;b
    x += 4;
    view.setUint32(x, 0x61_73_65_36); // ase6
    x += 4;
    view.setUint16(x, 0x34_2c); // 4,
    x += 2;
    x = toBase64Bin(buf, 0, length, view, x);
    writer.uint8[x++] = 0x22; // "
    writer.x = x;
  }
 
  public writeStr(str: string): void {
    const writer = this.writer;
    const length = str.length;
    writer.ensureCapacity(length * 4 + 2);
    if (length < 256) {
      const startX = writer.x;
      let x = startX;
      const uint8 = writer.uint8;
      uint8[x++] = 0x22; // "
      for (let i = 0; i < length; i++) {
        const code = str.charCodeAt(i);
        switch (code) {
          case 34: // "
          case 92: // \
            uint8[x++] = 0x5c; // \
            break;
        }
        if (code < 32 || code > 126) {
          writer.x = startX;
          const jsonStr = JSON.stringify(str);
          writer.ensureCapacity(jsonStr.length * 4 + 4);
          writer.utf8(jsonStr);
          return;
        } else uint8[x++] = code;
      }
      uint8[x++] = 0x22; // "
      writer.x = x;
      return;
    }
    const jsonStr = JSON.stringify(str);
    writer.ensureCapacity(jsonStr.length * 4 + 4);
    writer.utf8(jsonStr);
  }
 
  public writeAsciiStr(str: string): void {
    const length = str.length;
    const writer = this.writer;
    writer.ensureCapacity(length * 2 + 2);
    const uint8 = writer.uint8;
    let x = writer.x;
    uint8[x++] = 0x22; // "
    for (let i = 0; i < length; i++) {
      const code = str.charCodeAt(i);
      switch (code) {
        case 34: // "
        case 92: // \
          uint8[x++] = 0x5c; // \
          break;
      }
      uint8[x++] = code;
    }
    uint8[x++] = 0x22; // "
    writer.x = x;
  }
 
  public writeArr(arr: unknown[]): void {
    const writer = this.writer;
    writer.u8(0x5b); // [
    const length = arr.length;
    const last = length - 1;
    for (let i = 0; i < last; i++) {
      this.writeAny(arr[i]);
      writer.u8(0x2c); // ,
    }
    if (last >= 0) this.writeAny(arr[last]);
    writer.u8(0x5d); // ]
  }
 
  public writeArrSeparator(): void {
    this.writer.u8(0x2c); // ,
  }
 
  public writeObj(obj: Record<string, unknown>): void {
    const writer = this.writer;
    const keys = Object.keys(obj);
    const length = keys.length;
    if (!length) return writer.u16(0x7b7d); // {}
    writer.u8(0x7b); // {
    for (let i = 0; i < length; i++) {
      const key = keys[i];
      const value = obj[key];
      this.writeStr(key);
      writer.u8(0x3a); // :
      this.writeAny(value);
      writer.u8(0x2c); // ,
    }
    writer.uint8[writer.x - 1] = 0x7d; // }
  }
 
  public writeObjSeparator(): void {
    this.writer.u8(0x2c); // ,
  }
 
  public writeObjKeySeparator(): void {
    this.writer.u8(0x3a); // :
  }
 
  // ------------------------------------------------------- Streaming encoding
 
  public writeStartStr(): void {
    throw new Error('Method not implemented.');
  }
 
  public writeStrChunk(str: string): void {
    throw new Error('Method not implemented.');
  }
 
  public writeEndStr(): void {
    throw new Error('Method not implemented.');
  }
 
  public writeStartBin(): void {
    throw new Error('Method not implemented.');
  }
 
  public writeBinChunk(buf: Uint8Array): void {
    throw new Error('Method not implemented.');
  }
 
  public writeEndBin(): void {
    throw new Error('Method not implemented.');
  }
 
  public writeStartArr(): void {
    this.writer.u8(0x5b); // [
  }
 
  public writeArrChunk(item: unknown): void {
    throw new Error('Method not implemented.');
  }
 
  public writeEndArr(): void {
    this.writer.u8(0x5d); // ]
  }
 
  public writeStartObj(): void {
    this.writer.u8(0x7b); // {
  }
 
  public writeObjChunk(key: string, value: unknown): void {
    throw new Error('Method not implemented.');
  }
 
  public writeEndObj(): void {
    this.writer.u8(0x7d); // }
  }
}