string-buf.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. "use strict";
  2. // StringBuf - a way to keep string memory operations to a minimum
  3. // while building the strings for the xml files
  4. class StringBuf {
  5. constructor(options) {
  6. this._buf = Buffer.alloc(options && options.size || 16384);
  7. this._encoding = options && options.encoding || 'utf8';
  8. // where in the buffer we are at
  9. this._inPos = 0;
  10. // for use by toBuffer()
  11. this._buffer = undefined;
  12. }
  13. get length() {
  14. return this._inPos;
  15. }
  16. get capacity() {
  17. return this._buf.length;
  18. }
  19. get buffer() {
  20. return this._buf;
  21. }
  22. toBuffer() {
  23. // return the current data as a single enclosing buffer
  24. if (!this._buffer) {
  25. this._buffer = Buffer.alloc(this.length);
  26. this._buf.copy(this._buffer, 0, 0, this.length);
  27. }
  28. return this._buffer;
  29. }
  30. reset(position) {
  31. position = position || 0;
  32. this._buffer = undefined;
  33. this._inPos = position;
  34. }
  35. _grow(min) {
  36. let size = this._buf.length * 2;
  37. while (size < min) {
  38. size *= 2;
  39. }
  40. const buf = Buffer.alloc(size);
  41. this._buf.copy(buf, 0);
  42. this._buf = buf;
  43. }
  44. addText(text) {
  45. this._buffer = undefined;
  46. let inPos = this._inPos + this._buf.write(text, this._inPos, this._encoding);
  47. // if we've hit (or nearing capacity), grow the buf
  48. while (inPos >= this._buf.length - 4) {
  49. this._grow(this._inPos + text.length);
  50. // keep trying to write until we've completely written the text
  51. inPos = this._inPos + this._buf.write(text, this._inPos, this._encoding);
  52. }
  53. this._inPos = inPos;
  54. }
  55. addStringBuf(inBuf) {
  56. if (inBuf.length) {
  57. this._buffer = undefined;
  58. if (this.length + inBuf.length > this.capacity) {
  59. this._grow(this.length + inBuf.length);
  60. }
  61. // eslint-disable-next-line no-underscore-dangle
  62. inBuf._buf.copy(this._buf, this._inPos, 0, inBuf.length);
  63. this._inPos += inBuf.length;
  64. }
  65. }
  66. }
  67. module.exports = StringBuf;
  68. //# sourceMappingURL=string-buf.js.map