All files / src/data-types record-text.ts

96.66% Statements 29/30
92.3% Branches 24/26
100% Functions 6/6
96.55% Lines 28/29

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 80139x                             280x 280x 280x 280x 588x     588x 588x 280x   308x                     435x                   435x 13x   422x           290x 290x 290x       298x 298x 298x 5454x 5454x 78x 78x 5376x 298x   5078x 5078x            
const SPECIAL = /[\s"\\(),]/;
 
/**
 * Reads and writes the text form of a composite value, `(1,"a b",)`.
 *
 * @internal
 */
export class RecordText {
  /**
   * Splits record text into field texts.
   *
   * @param text - Record text, e.g. `(1,"say ""hi""",)`.
   * @returns One entry per field; `null` for an empty (NULL) field.
   */
  parse(text: string): (string | null)[] {
    const fields: (string | null)[] = [];
    const body = text.slice(1, -1);
    let index = 0;
    for (;;) {
      const [value, next] = body.startsWith('"', index)
        ? this.#quoted(body, index + 1)
        : this.#plain(body, index);
      fields.push(value);
      if (next >= body.length) {
        return fields;
      }
      index = next + 1;
    }
  }
 
  /**
   * Writes field texts as record text.
   *
   * @param fields - Field texts; `null` is written as an empty field.
   * @returns Record text.
   */
  format(fields: readonly (string | null)[]): string {
    return `(${fields.map((field) => this.quote(field)).join(',')})`;
  }
 
  /**
   * Quotes one field when it needs it.
   *
   * @param field - Field text or `null`.
   * @returns Field text for use inside a record or array literal.
   */
  quote(field: string | null): string {
    if (field === null) {
      return '';
    }
    return field === '' || SPECIAL.test(field)
      ? `"${field.replaceAll('\\', '\\\\').replaceAll('"', '""')}"`
      : field;
  }
 
  #plain(body: string, from: number): [string | null, number] {
    const end = body.indexOf(',', from);
    const stop = end === -1 ? body.length : end;
    return [from === stop ? null : body.slice(from, stop), stop];
  }
 
  #quoted(body: string, from: number): [string, number] {
    let value = '';
    let index = from;
    while (index < body.length) {
      const char = body[index] ?? '';
      if (char === '"' && body[index + 1] === '"') {
        value += '"';
        index += 2;
      } else if (char === '"') {
        return [value, index + 1];
      } else {
        value += char === '\\' ? (body[++index] ?? '') : char;
        index += 1;
      }
    }
    return [value, index];
  }
}