string-buf.js 1.9 KB

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