All files / src/data-types ewkb-reader.ts

100% Statements 48/48
100% Branches 24/24
100% Functions 16/16
100% Lines 44/44

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      139x 139x 139x     12x 12x       12x       19x       40x     40x 40x       58x     58x 58x                                       12x 12x 12x 12x           19x 19x 19x 19x       19x                   19x 19x 1x   18x 1x   17x       17x   8x   8x   12x   5x         4x 7x 7x         13x 13x       28x 28x 1x   28x 1x   28x      
/** GeoJSON geometry as produced by the EWKB reader. */
export type GeoJsonGeometry = Readonly<Record<string, unknown>>;
 
const HAS_Z = 0x80000000;
const HAS_M = 0x40000000;
const HAS_SRID = 0x20000000;
 
class Cursor {
  little = true;
  offset = 0;
  readonly #bytes: Buffer;
 
  constructor(bytes: Buffer) {
    this.#bytes = bytes;
  }
 
  byte(): number {
    return this.#bytes.readUInt8(this.offset++);
  }
 
  uint32(): number {
    const value = this.little
      ? this.#bytes.readUInt32LE(this.offset)
      : this.#bytes.readUInt32BE(this.offset);
    this.offset += 4;
    return value;
  }
 
  float64(): number {
    const value = this.little
      ? this.#bytes.readDoubleLE(this.offset)
      : this.#bytes.readDoubleBE(this.offset);
    this.offset += 8;
    return value;
  }
}
 
type Header = Readonly<{ type: number; z: boolean; m: boolean; srid: number | undefined }>;
 
/**
 * Reads hex-encoded EWKB (what PostGIS sends for `geometry` and `geography`) into GeoJSON.
 *
 * @internal
 */
export class EwkbReader {
  /**
   * Parses hex EWKB.
   *
   * @param hex - Hex string of an EWKB geometry.
   * @returns GeoJSON geometry; `crs` is set (`EPSG:<srid>`) when the EWKB carries an SRID, like v6.
   * @throws Error for a geometry type this reader does not support (curves, TIN, …).
   */
  parse(hex: string): GeoJsonGeometry {
    const cursor = new Cursor(Buffer.from(hex, 'hex'));
    const header = this.#header(cursor);
    const geometry = this.#geometry(cursor, header);
    return header.srid === undefined
      ? geometry
      : { ...geometry, crs: { type: 'name', properties: { name: `EPSG:${header.srid}` } } };
  }
 
  #header(cursor: Cursor): Header {
    cursor.little = cursor.byte() === 1;
    const raw = cursor.uint32();
    const srid = (raw & HAS_SRID) === 0 ? undefined : cursor.uint32();
    return { type: raw & 0xff, z: (raw & HAS_Z) !== 0, m: (raw & HAS_M) !== 0, srid };
  }
 
  #geometry(cursor: Cursor, header: Header): GeoJsonGeometry {
    const names = [
      '',
      'Point',
      'LineString',
      'Polygon',
      'MultiPoint',
      'MultiLineString',
      'MultiPolygon',
      'GeometryCollection',
    ];
    const type = names[header.type];
    if (type === undefined || type === '') {
      throw new Error(`Unsupported EWKB geometry type ${header.type}`);
    }
    if (header.type === 7) {
      return { type, geometries: this.#members(cursor) };
    }
    return { type, coordinates: this.#coordinates(cursor, header) };
  }
 
  #coordinates(cursor: Cursor, header: Header): unknown {
    switch (header.type) {
      case 1:
        return this.#position(cursor, header);
      case 2:
        return this.#list(cursor, () => this.#position(cursor, header));
      case 3:
        return this.#list(cursor, () => this.#list(cursor, () => this.#position(cursor, header)));
      default:
        return this.#members(cursor).map((member) => member['coordinates']);
    }
  }
 
  #members(cursor: Cursor): GeoJsonGeometry[] {
    return this.#list(cursor, () => {
      const header = this.#header(cursor);
      return this.#geometry(cursor, header);
    });
  }
 
  #list<T>(cursor: Cursor, item: () => T): T[] {
    const count = cursor.uint32();
    return Array.from({ length: count }, item);
  }
 
  #position(cursor: Cursor, header: Header): number[] {
    const position = [cursor.float64(), cursor.float64()];
    if (header.z) {
      position.push(cursor.float64());
    }
    if (header.m) {
      cursor.float64();
    }
    return Number.isNaN(position[0]) ? [] : position;
  }
}