From: James Halliday Date: Wed, 20 Mar 2013 18:55:18 +0000 (-0700) Subject: ported .copy() X-Git-Url: https://zoso.dev/?a=commitdiff_plain;h=f95cf3a2230a4f590cc42c3fc7fd139dc3d8c690;p=buffer.git ported .copy() --- diff --git a/index.js b/index.js index f56b93e..2f7514e 100644 --- a/index.js +++ b/index.js @@ -294,9 +294,42 @@ Buffer.prototype.slice = function(start, end) { return new Buffer(this, end - start, +start); }; -Buffer.prototype.copy = function(target, targetstart, sourcestart, sourceend) { +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function(target, target_start, start, end) { + var source = this; + start || (start = 0); + end || (end = this.length); + target_start || (target_start = 0); + + if (end < start) throw new Error('sourceEnd < sourceStart'); + + // Copy 0 bytes; we're done + if (end === start) return 0; + if (target.length == 0 || source.length == 0) return 0; + + if (target_start < 0 || target_start >= target.length) { + throw new Error('targetStart out of bounds'); + } + + if (start < 0 || start >= source.length) { + throw new Error('sourceStart out of bounds'); + } + + if (end < 0 || end > source.length) { + throw new Error('sourceEnd out of bounds'); + } + + // Are we oob? + if (end > this.length) { + end = this.length; + } + + if (target.length - target_start < end - start) { + end = target.length - target_start + start; + } + var temp = []; - for (var i=sourcestart; i= target.length) { - throw new Error('targetStart out of bounds'); - } - - if (start < 0 || start >= source.length) { - throw new Error('sourceStart out of bounds'); - } - - if (end < 0 || end > source.length) { - throw new Error('sourceEnd out of bounds'); - } - - // Are we oob? - if (end > this.length) { - end = this.length; - } - - if (target.length - target_start < end - start) { - end = target.length - target_start + start; - } - - return this.parent.copy(target.parent, - target_start + target.offset, - start + this.offset, - end + this.offset); -}; - - // slice(start, end) Buffer.prototype.slice = function(start, end) { if (end === undefined) end = this.length;