From: Andreas Madsen Date: Wed, 21 Aug 2013 16:52:54 +0000 (+0200) Subject: support out of range slice X-Git-Url: https://zoso.dev/?a=commitdiff_plain;h=0b3ad4717542b4237dc859273e182af43bbe2b58;p=buffer.git support out of range slice --- diff --git a/index.js b/index.js index 3272ce8..08a15a9 100644 --- a/index.js +++ b/index.js @@ -292,18 +292,21 @@ Buffer.prototype.write = function(string, offset, length, encoding) { } }; - // slice(start, end) -Buffer.prototype.slice = function(start, end) { - if (end === undefined) end = this.length; - - if (end > this.length) { - throw new Error('oob'); - } - if (start > end) { - throw new Error('oob'); - } +function clamp(index, len, defaultValue) { + if (typeof index !== 'number') return defaultValue; + index = ~~index; // Coerce to integer. + if (index >= len) return len; + if (index >= 0) return index; + index += len; + if (index >= 0) return index; + return 0; +} +Buffer.prototype.slice = function(start, end) { + var len = this.length; + start = clamp(start, len, 0); + end = clamp(end, len, len); return new Buffer(this, end - start, +start); }; diff --git a/test/buffer.js b/test/buffer.js index d4ddbae..74c939e 100644 --- a/test/buffer.js +++ b/test/buffer.js @@ -246,3 +246,10 @@ test('buffer.slice sets indexes', function (t) { t.equal((new B('hallo')).slice(0, 5).toString(), 'hallo'); t.end(); }); + +test('buffer.slice out of range', function (t) { + t.plan(2); + t.equal((new B('hallo')).slice(0, 10).toString(), 'hallo'); + t.equal((new B('hallo')).slice(10, 2).toString(), ''); + t.end(); +});