'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = replaceBuffer;


/**
 * replace string with another string inside Buffer without converting it to string.
 * other npm packages, such as replace-buffer and buffer-replace are recursive, and as such,
 * when using huge files (more than 8.5K lines of code), it crushes with an error "Maximum call
 * stack size exceeded".
 */
function replaceBuffer(buffer, oldStr, newStr) {
  if (!(buffer instanceof Buffer)) throw new Error(`replaceBuffer expect to get Buffer, got ${typeof buffer} instead`);
  if (!buffer.includes(oldStr)) return buffer;
  var bufferOldStr = Buffer.from(oldStr);
  var bufferOldStrLength = bufferOldStr.length;
  var bufferNewStr = Buffer.from(newStr);

  var idx = buffer.indexOf(oldStr);
  var bufferInProgress = Buffer.from('');
  var startingPoint = 0;

  while (idx !== -1) {
    var bufferStart = buffer.slice(startingPoint, idx);
    bufferInProgress = Buffer.concat([bufferInProgress, bufferStart, bufferNewStr]);
    startingPoint = idx + bufferOldStrLength;
    idx = buffer.indexOf(oldStr, idx + bufferOldStrLength);
  }
  var bufferEnd = buffer.slice(startingPoint, buffer.length);
  return Buffer.concat([bufferInProgress, bufferEnd]);
}