B64Builder.js 2.2 KB
Newer Older
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
/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 *
 * @format
 */
"use strict";

const encode = require("./encode");

const MAX_SEGMENT_LENGTH = 7;
const ONE_MEG = 1024 * 1024;
const COMMA = 0x2c;
const SEMICOLON = 0x3b;
/**
 * Efficient builder for base64 VLQ mappings strings.
 *
 * This class uses a buffer that is preallocated with one megabyte and is
 * reallocated dynamically as needed, doubling its size.
 *
 * Encoding never creates any complex value types (strings, objects), and only
 * writes character values to the buffer.
 *
 * For details about source map terminology and specification, check
 * https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
 */

class B64Builder {
  constructor() {
    this.buffer = Buffer.alloc(ONE_MEG);
    this.pos = 0;
    this.hasSegment = false;
  }
  /**
   * Adds `n` markers for generated lines to the mappings.
   */

  markLines(n) {
    if (n < 1) {
      return this;
    }

    this.hasSegment = false;

    if (this.pos + n >= this.buffer.length) {
      this._realloc();
    }

    while (n--) {
      this.buffer[this.pos++] = SEMICOLON;
    }

    return this;
  }
  /**
   * Starts a segment at the specified column offset in the current line.
   */

  startSegment(column) {
    if (this.hasSegment) {
      this._writeByte(COMMA);
    } else {
      this.hasSegment = true;
    }

    this.append(column);
    return this;
  }
  /**
   * Appends a single number to the mappings.
   */

  append(value) {
    if (this.pos + MAX_SEGMENT_LENGTH >= this.buffer.length) {
      this._realloc();
    }

    this.pos = encode(value, this.buffer, this.pos);
    return this;
  }
  /**
   * Returns the string representation of the mappings.
   */

  toString() {
    return this.buffer.toString("ascii", 0, this.pos);
  }

  _writeByte(byte) {
    if (this.pos === this.buffer.length) {
      this._realloc();
    }

    this.buffer[this.pos++] = byte;
  }

  _realloc() {
    const buffer = this.buffer;
    this.buffer = Buffer.alloc(buffer.length * 2);
    buffer.copy(this.buffer);
  }
}

module.exports = B64Builder;