28 Companion zmachine.js (7/28)

  // Decode a Z-string. Returns {text, end} where end is the byte after it.
  decode(addr, noAbbrev = false) {
    const zchars = [];
    let a = addr;
    for (;;) {
      const w = this.rw(a);
      a += 2;
      zchars.push((w >> 10) & 31, (w >> 5) & 31, w & 31);
      if (w & 0x8000) break;
      if (a >= this.mem.length) break;
    }
    let text = '';
    let alpha = 0;
    for (let i = 0; i < zchars.length; i++) {
      const z = zchars[i];
      if (z === 0) { text += ' '; alpha = 0; continue; }
      if (z >= 1 && z <= 3) {
        if (i + 1 >= zchars.length) break;
        const idx = 32 * (z - 1) + zchars[++i];
        if (!noAbbrev) text += this.decode(this.rw(this.abbrevs + 2 * idx) * 2, true).text;
        alpha = 0;
        continue;
      }
      if (z === 4) { alpha = 1; continue; }
      if (z === 5) { alpha = 2; continue; }
      if (alpha === 2 && z === 6) {
        if (i + 2 >= zchars.length) break;
        text += this.zsciiToChar((zchars[i + 1] << 5) | zchars[i + 2]);
        i += 2;
      } else if (alpha === 2 && z === 7) {
        text += '\n';
      } else {
        text += this.alphabets[alpha][z - 6];
      }
      alpha = 0;
    }
    return { text, end: a };
  }
‹ PreviousReader file (.txt)Next ›