From ff30f4cacaca06794535ecb6318a2ffe6f33fe8c Mon Sep 17 00:00:00 2001 From: kawanet Date: Thu, 6 Aug 2015 19:13:09 +0900 Subject: [PATCH] descending copy from end --- index.js | 11 +++++++++-- test/methods.js | 11 +++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index d72a180..6c6be99 100644 --- a/index.js +++ b/index.js @@ -1171,9 +1171,16 @@ Buffer.prototype.copy = function copy (target, targetStart, start, end) { } var len = end - start + var i - if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < len; i++) { + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; i--) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; i++) { target[i + targetStart] = this[i + start] } } else { diff --git a/test/methods.js b/test/methods.js index b6b7c74..be92568 100644 --- a/test/methods.js +++ b/test/methods.js @@ -100,6 +100,17 @@ test('copy() after slice()', function (t) { t.end() }) +test('copy() ascending and descending', function (t) { + var b + b = new B('abcdefghij') + b.copy(b, 0, 3, 10) // ascending copy + t.equal(b.toString(), 'defghijhij') + b = new B('abcdefghij') + b.copy(b, 3, 0, 7) // descending copy + t.equal(b.toString(), 'abcabcdefg') + t.end() +}) + test('buffer.slice sets indexes', function (t) { t.equal((new B('hallo')).slice(0, 5).toString(), 'hallo') t.end() -- 2.34.1